public void CanEnsureUserCreationIsValid()
        {
            User userFromForm = new User { Login = String.Empty, Password = String.Empty };
            ViewResult result = controller.Create(userFromForm, String.Empty).AssertViewRendered();

            result.ViewData.Model.ShouldNotBeNull();
            result.ViewData.Model.ShouldBeOfType(typeof(User));
        }
        public ActionResult Create(User user, string confirmPassword)
        {
            AccountController.ValidateRegistration(user.Login, user.Password, confirmPassword,
                                                   ModelState, membershipService, UserRepository);

            if (ViewData.ModelState.IsValid && user.IsValid())
            {
                user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(user.Password, "SHA1");
                UserRepository.SaveOrUpdate(user);

                Message = "Пользователь успешно создан.";
                return this.RedirectToAction(c => c.Index());
            }

            return View(user);
        }
        public Stream GetReport(User user)
        {
            DataTable dt = GetReportDataTable(user);
            if (dt != null)
            {
                MemoryStream ms = new MemoryStream();
                ZipOutputStream zipOutputStream = new ZipOutputStream(ms);
                ZipEntry zipEntry = new ZipEntry("report.csv");
                zipOutputStream.PutNextEntry(zipEntry);
                zipOutputStream.SetLevel(5);
                string st = CsvWriter.WriteToString(dt, true, false);
                zipOutputStream.Write(Encoding.Default.GetBytes(st), 0, st.Length);
                zipOutputStream.Finish();
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);

                return ms;
            }
            return null;
        }
        private static DataTable GetReportDataTable(User user)
        {
            if (user.Role.IsAuthor)
            {
                DataTable dt = new DataTable("Report");

                dt.Columns.Add(new DataColumn("Команда", typeof(String)));
                foreach (Task task in user.Game.Tasks)
                {
                    dt.Columns.Add(new DataColumn(task.Name, typeof(String)));
                }

                foreach (Team team in user.Game.Teams)
                {
                    //
                    DataRow[] rows = new [] {
                        dt.NewRow(),    //Получено - <время>
                        dt.NewRow(),    //Подсказки - <время><пробел><время>...<время>
                        dt.NewRow(),    //Коды - список <код>(<время>)<пробел><код>(<время>)...<код>(<время>)
                        dt.NewRow(),    //Потрачено - <всего_минут>
                        dt.NewRow(),    //Итог задания - <итог><пробел>в<пробел><время>
                        dt.NewRow()     //Разделитель - пустая строка.
                    };

                    //[Cтрока(число)][Столбец(0|ИмяЗадания)]
                    rows[0][0] = team.Name;
                    rows[1][0] = ""; //"подсказки";
                    rows[2][0] = ""; //"коды";
                    rows[3][0] = ""; //"длилось";
                    rows[4][0] = ""; //"итог";
                    rows[5][0] = "";

                    if (team.TeamGameState != null)
                    {
                        foreach (TeamTaskState taskState in team.TeamGameState.AcceptedTasks)
                        {
                            //Указываем время начала задания
                            rows[0][taskState.Task.Name] = String.Format("{0}", taskState.TaskStartTime);

                            //Выписываем все подсказки
                            foreach (AcceptedTip tip in taskState.AcceptedTips)
                            {
                                //Стартовая подсказка (SuspendTime = 0) не нужна.
                                if (tip.Tip.SuspendTime > 0)
                                {
                                    rows[1][taskState.Task.Name] = String.Format("{0} {1}", rows[1][taskState.Task.Name], tip.AcceptTime.TimeOfDay);
                                }
                            }

                            //Выписываем все коды
                            foreach (AcceptedCode code in taskState.AcceptedCodes)
                            {
                                rows[2][taskState.Task.Name] = String.Format("{0} {1}({2})", rows[2][taskState.Task.Name], code.Code.Name, code.AcceptTime.TimeOfDay);
                            }

                            //Указываем количество потраченных минут.
                            if (taskState.TaskFinishTime != null)
                            {
                                rows[3][taskState.Task.Name] =
                                    Math.Round(((DateTime)taskState.TaskFinishTime -
                                         taskState.TaskStartTime).TotalMinutes);
                            }

                            //Указываем итог задания.
                            if (taskState.TaskFinishTime != null)
                            {
                                string state = String.Empty;
                                state = taskState.State == (int)TeamTaskStateFlag.Success ? "ОК!" : state;
                                state = taskState.State == (int)TeamTaskStateFlag.Overtime ? "ПРОСР." : state;
                                state = taskState.State == (int)TeamTaskStateFlag.Canceled ? "СЛИТО" : state;
                                state = taskState.State == (int)TeamTaskStateFlag.Cheat ? "БАН!" : state;
                                rows[4][taskState.Task.Name] = String.Format("{0} в {1}", state, ((DateTime)taskState.TaskFinishTime).TimeOfDay);
                            }
                        }
                    }

                    dt.Rows.Add(rows[0]);
                    dt.Rows.Add(rows[1]);
                    dt.Rows.Add(rows[2]);
                    dt.Rows.Add(rows[3]);
                    dt.Rows.Add(rows[4]);
                    dt.Rows.Add(rows[5]);
                }
                dt.AcceptChanges();
                return dt;
            }
            return null;
        }
Esempio n. 5
0
 /// <summary>
 /// Обработка принятого кода от команды.
 /// </summary>
 /// <param name="codes">Принятый код.</param>
 /// <param name="teamGameState">Команда отправившая код.</param>
 /// <param name="user">Игрок отправившый код.</param>
 /// <param name="dateTimeNow"></param>
 public void SubmitCode(string codes, TeamGameState teamGameState, User user, DateTime dateTimeNow)
 {
     taskService.SubmitCode(codes, teamGameState, user, dateTimeNow);
 }
 public MembershipCreateStatus CreateUser(string userName, string password/*, string email*/)
 {
     User user = new User();
     user.Login = userName;
     user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
     user.Nick = userName;
     user.Role = Role.Player;
     _provider.SaveOrUpdate(user);
     return MembershipCreateStatus.Success;
 }
 public EncounterViewData WithUser(User user)
 {
     User = user;
     return this;
 }
        public void SetUp()
        {
            ServiceLocatorInitializer.Init();

            controller = new TasksController(
                CreateMockTaskRepository(),
                MockRepository.GenerateMock<IUserRepository>(),
                TipsControllerTests.CreateMockTipRepository(),
                CodesControllerTests.CreateMockCodeRepository());

            testContext = new ControllerTestContext(controller);
            user = new User { Game = new Game() };
        }
        public void CanEnsureUserEditionIsValid()
        {
            User userFromForm = new User { Login = String.Empty, Password = String.Empty };
            EntityIdSetter.SetIdOf(userFromForm, 1);
            ViewResult result = controller.Edit(userFromForm).AssertViewRendered();

            result.ViewData.Model.ShouldNotBeNull();
            result.ViewData.Model.ShouldBeOfType(typeof(AdminUsersController.UserFormViewModel));
        }
        /// <summary>
        /// Creates a valid, transient Game; typical of something retrieved back from a form submission
        /// </summary>
        private static User CreateTransientUser()
        {
            User user = new User
            {
                Login = "******",
                Password = "******"
            };

            return user;
        }
 private static void TransferFormValuesTo(User userToUpdate, User user)
 {
     userToUpdate.Nick = user.Nick;
     userToUpdate.Icq = user.Icq;
     userToUpdate.Phone = user.Phone;
     userToUpdate.Game = user.Game;
     userToUpdate.Team = user.Team;
     //userToUpdate.IsEnabled = user.IsEnabled;
     //userToUpdate.Role = user.Role;
 }
        public ActionResult Edit(User user)
        {
            User userToUpdate = UserRepository.Get(user.Id);
            TransferFormValuesTo(userToUpdate, user);

            if (ViewData.ModelState.IsValid && user.IsValid())
            {
                Message = "Изменения успешно сохранены.";
                return this.RedirectToAction(c => c.Index());
            }
            UserRepository.DbContext.RollbackTransaction();

            var viewModel = UserFormViewModel.CreateTipFormViewModel();
            viewModel.User = user;
            viewModel.Teams = teamRepository.GetAll();
            viewModel.Games = gameRepository.GetAll();
            return View(viewModel);
        }
Esempio n. 13
0
 /// <summary>
 /// Обработка принятого кода от команды.
 /// </summary>
 /// <param name="codes">Принятый код.</param>
 /// <param name="teamGameState">Команда отправившая код.</param>
 /// <param name="user">Игрок отправившый код.</param>
 public void SubmitCode(string codes, TeamGameState teamGameState, User user)
 {
     taskService.SubmitCode(codes, teamGameState, user);
 }
 private void AuthenticateAs(HttpContextBase context, User user)
 {
     Thread.CurrentPrincipal = context.User = user;
 }
        public void SetUp()
        {
            ServiceLocatorInitializer.Init();

            controller = new GamesController(
                CreateMockGameRepository(),
                MockRepository.GenerateMock<IUserRepository>(),
                MockRepository.GenerateMock<IGameService>());
            testContext = new ControllerTestContext(controller);

            user = new User {Game = new Game()};
        }
Esempio n. 16
0
        public void SubmitCode(string codes, TeamGameState teamGameState, User user, DateTime recalcTime)
        {
            if (teamGameState.ActiveTaskState == null ||
                teamGameState.ActiveTaskState.AcceptedBadCodes.Count >= GameConsnt.BadCodesLimit)
                return;

            List<string> codesList = GetCodes(codes, teamGameState.Game.PrefixMainCode, teamGameState.Game.PrefixBonusCode);
            if (codesList.Count == 0)
                return;

            if (codesList.Count > teamGameState.ActiveTaskState.Task.Codes.Count)
                throw new MaxCodesCountException(String.Format("Запрещено вводить количество кодов, за один раз, большее, чем количество кодов в задании."));

            foreach (Code code in teamGameState.ActiveTaskState.Task.Codes)
            {
                if (codesList.Contains(code.Name.Trim().ToUpper()))
                {
                    codesList.Remove(code.Name.Trim().ToUpper());
                    if (!teamGameState.ActiveTaskState.AcceptedCodes.Any(x => x.Code == code))
                    {
                        // Добавляем правильный принятый код
                        AcceptedCode acceptedCode = new AcceptedCode
                        {
                            AcceptTime = recalcTime,
                            Code = code,
                            TeamTaskState = teamGameState.ActiveTaskState
                        };

                        teamGameState.ActiveTaskState.AcceptedCodes.Add(acceptedCode);
                        acceptedCodeRepository.SaveOrUpdate(acceptedCode);
                    }
                }
            }

            // Добавляем некорректные принятые коды
            foreach (string badCode in codesList)
            {
                if (!teamGameState.ActiveTaskState.AcceptedBadCodes.Any(x => x.Name.Trim().ToUpper() == badCode))
                {
                    AcceptedBadCode acceptedBadCode = new AcceptedBadCode
                    {
                        AcceptTime = recalcTime,
                        Name = badCode,
                        TeamTaskState = teamGameState.ActiveTaskState
                    };

                    teamGameState.ActiveTaskState.AcceptedBadCodes.Add(acceptedBadCode);
                    acceptedBadCodeRepository.SaveOrUpdate(acceptedBadCode);
                }
            }

            // Если приняты все основные коды, то помечаем задание выполненым и назначаем новое
            if (teamGameState.ActiveTaskState.AcceptedCodes.Count == teamGameState.ActiveTaskState.Task.Codes.Count/*(x => x.IsBonus == 0)*/ &&
                teamGameState.ActiveTaskState.AcceptedCodes.Count > 0)
            {
                Task oldTask = teamGameState.ActiveTaskState.Task;
                CloseTaskForTeam(teamGameState.ActiveTaskState, TeamTaskStateFlag.Success, recalcTime);
                AssignNewTask(teamGameState, oldTask, recalcTime);
            }

            CheckExceededBadCodes(teamGameState, recalcTime);
        }