public ActionResult Create()
        {
            var model = new TeamViewModel();
            model.GameList = new SelectList (_gameService.GetAll(), SelectLists.DataValueField, SelectLists.DataTextField, SelectLists.UnitializedSelectValue);

            return View(model);
        }
Beispiel #2
0
 public async void reloadTeam(TeamViewModel team)
 {
   var user = await _client.Organization.Team.GetAllMembers(team.team.Id);
   var repo = await _client.Organization.Team.GetAllRepositories(team.team.Id);
   team.Users = user;
   team.Repos = repo;
   onUpdateTeam();
 }
Beispiel #3
0
 public ActionResult Edit(TeamViewModel viewModel)
 {
     if (!ModelState.IsValid)
         return View("Create", viewModel);
     var model = Map<TeamViewModel, Team>(viewModel);
     Site.TeamManager.Update(model);
     return RedirectToAction("List");
 }
Beispiel #4
0
 private async Task<TeamViewModel> initTeam(Team t)
 {
   
   var team = new TeamViewModel(t);
   var user = await _client.Organization.Team.GetAllMembers(t.Id);
   var repo = await _client.Organization.Team.GetAllRepositories(t.Id);
   team.Users = user;
   team.Repos = repo;
   return team;
 }
        public ActionResult Create(TeamViewModel model)
        {
            if (ModelState.IsValid)
            {
                var businessObject = new BOTeam();
                Mapper.Map<TeamViewModel, BOTeam>(model, businessObject);

                businessObject.Game = new BOGame(model.GameListID);

                _teamService.Save(businessObject);

                return RedirectToAction("Index");
            }
            model.GameList = new SelectList (_gameService.GetAll(), SelectLists.DataValueField, SelectLists.DataTextField, SelectLists.UnitializedSelectValue);

            return View(model);
        }
        public ActionResult RegisterTeam(TeamViewModel model)
        {
            if (ModelState.IsValid)
            {
                model.TeamLeadID = Request.Params["employeesSelectList"];
                model.TeamID     = Guid.NewGuid().ToString();

                TeamCreationService.RegisterTeam(model, Request.Params["members"], _employeeService, _teamService, UserManager);

                ViewBag.ListService     = _pageListsService;
                ViewBag.ListOfEmployees =
                    Mapper.MapCollection <EmployeeDTO, EmployeeViewModel>(_employeeService.GetAll().ToArray());

                ViewData["employeesSelectList"] = _pageListsService.EmployeesList();

                ViewData["listOfEmployees"] =
                    Mapper.MapCollection <EmployeeDTO, EmployeeViewModel>(_employeeService.GetAllFreeEmployees()
                                                                          .ToArray());
            }

            return(RedirectToAction("TeamsList", "Admin"));
        }
Beispiel #7
0
        public void UpdateTeam(Team oldTeam, TeamViewModel newViewModel)
        {
            if (oldTeam.Id != newViewModel.Id)
            {
                throw new ArgumentException("Can't update a different team");
            }

            oldTeam.ActiveSince  = newViewModel.ActiveSince;
            oldTeam.Description  = newViewModel.Description;
            oldTeam.Email        = newViewModel.Email;
            oldTeam.FacebookUrl  = newViewModel.FacebookUrl;
            oldTeam.InstagramUrl = newViewModel.InstagramUrl;
            oldTeam.Members      = newViewModel.Members.Where(m => !string.IsNullOrWhiteSpace(m)).ToList();
            oldTeam.Name         = newViewModel.Name;
            oldTeam.TagLine      = newViewModel.TagLine;
            oldTeam.WebsiteUrl   = newViewModel.WebsiteUrl;

            UpdateTeamPhoto(oldTeam, newViewModel);
            UpdateLogoImage(oldTeam, newViewModel);

            _dbContext.SaveChanges();
        }
        public async Task <ActionResult> Create([Bind(Include = "Team")] TeamViewModel _teamViewModel)
        {
            Tournament tournament = tournamentService.GetById(_teamViewModel.Team.TournamentId);

            if (ModelState.IsValid)
            {
                Team team        = teamService.Create(_teamViewModel.Team);
                var  userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();

                ApplicationUser user = await userManager.FindByNameAsync(tournament.Organizer);

                string subject = string.Format("Team \"{0}\" wants to participate in your tournament \"{1}\".", team.Name, team.Tournament.Name);
                string body    = MailTemplateBody.GetBody(user.FullName, String.Format("Team \"{0}\" with the coach {2} want to participate in your tournament \"{1}\". <br/> <br/>Please confirm participation.", team.Name, team.Tournament.Name, team.Coach.GetFullName()));

                await userManager.SendEmailAsync(user.Id, subject, body);

                return(RedirectToAction("Details", "Teams", new { id = team.Id }));
            }
            _teamViewModel.CountryList = GetCountryList();
            _teamViewModel.RankingList = GetRankingList(tournament);
            return(View(_teamViewModel));
        }
Beispiel #9
0
        public async Task <ActionResult> GetInstallDetailPartial(string teamId, string installId)
        {
            try
            {
                var viewModel = new TeamViewModel();
                await viewModel.Load(teamId);

                var install = viewModel.Team.TeamInstall.TeamInstalls.FirstOrDefault(x => x.Id == installId);
                ViewData["TeamId"] = teamId;

                var playViewModel = new PlayViewModel();
                await playViewModel.Load(teamId);

                var coachUsers = playViewModel.TeamUsers.Where(x => x.Roles.Contains("Coach")).ToList();
                ViewData["Users"] = coachUsers;
                return(PartialView("_AddEditTeamInstall", install));
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Creates Team
        /// </summary>
        /// <param name="team"> The  team as ViewModel. </param>
        /// <returns> Has been saved successfully - Created OData result
        /// unsuccessfully - Bad request </returns>
        public IHttpActionResult Post(TeamViewModel team)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var teamToCreate = team.ToDomain();

            try
            {
                _teamService.Create(teamToCreate);
            }
            catch (MissingEntityException ex)
            {
                ModelState.AddModelError(string.Format("{0}.{1}", CONTROLLER_NAME, ex.Source), ex.Message);
                return(BadRequest(ModelState));
            }

            team.Id = teamToCreate.Id;
            return(Ok(team));
        }
Beispiel #11
0
        public async Task <IActionResult> Edit(int id, TeamViewModel teamViewModel)
        {
            if (id != teamViewModel.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                string path = teamViewModel.LogoPath;

                if (teamViewModel.LogoFile != null)
                {
                    path = await _imageHelper.UploadImageAsync(teamViewModel.LogoFile, "Teams");
                }

                TeamEntity teamEntity = _converterHelper.ToTeamEntity(teamViewModel, path, false);
                _context.Update(teamEntity);

                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (System.Exception ex)
                {
                    if (ex.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, $"Already exists the team: {teamEntity.Name}");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, ex.InnerException.Message);
                    }
                }
            }
            return(View(teamViewModel));
        }
Beispiel #12
0
        public void ViewModelToModelTest()
        {
            var viewModel = new TeamViewModel
            {
                Name           = "c",
                Number         = 2,
                RaceId         = Guid.NewGuid(),
                FinishedStages = new List <FinishedStageViewModel>(),
                FinishTime     = DateTime.Now,
                TeamId         = Guid.NewGuid(),
                VisitedPoints  = new List <VisitedPointViewModel>()
            };

            var result = _Sut.Map <TeamViewModel>(viewModel);

            Assert.AreEqual(viewModel.Name, result.Name);
            Assert.AreEqual(viewModel.Number, result.Number);
            Assert.AreEqual(viewModel.RaceId, result.RaceId);
            Assert.IsNotNull(result.FinishedStages);
            Assert.AreEqual(viewModel.FinishTime, result.FinishTime);
            Assert.IsNotNull(result.VisitedPoints);
        }
Beispiel #13
0
        public ActionResult Create(TeamViewModel vm)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    this.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    return(this.JsonNet(this.ModelState.AsModelErrorCollection()));
                }

                var team = this.mapper.Map <Team>(vm);

                this.teamService.Add(team);

                return(this.JsonNet(vm));
            }
            catch (Exception ex)
            {
                this.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                return(this.JsonNet(ex.AsModelErrorCollection()));
            }
        }
Beispiel #14
0
        public ParticipantsViewModel Participants(Guid meetingId)
        {
            List <ParticipantViewModel> participants = new List <ParticipantViewModel>();

            Meeting meeting = this.bunchOfMeetings.Get(meetingId);

            if (meeting is null)
            {
                throw new ArgumentException($"Meeting with id {@meetingId} does not exis");
            }

            participants.AddRange(meeting.Leaders.Select(x => new LeaderViewModel(x.Name, x.Id)));
            participants.AddRange(meeting.Members.Select(x => new MemberViewModel(x.Name, x.Id)));

            ParticipantsViewModel viewModel = new ParticipantsViewModel(meeting.Name, meeting.Id);

            viewModel.Participants = participants;

            viewModel.Teams = meeting.Teams.Select(x => TeamViewModel.FromTeam(x)).ToList();

            return(viewModel);
        }
Beispiel #15
0
        public async Task UpdateAsync(TeamViewModel model)
        {
            var dbSport = await _repo.Teams.GetByIdAsync(model.Id);

            if (model.ProfileBlob != dbSport.ProfileBlob)
            {
                //delete current one
                new AzureStorage(dbSport.ProfileContainer, true).DeleteFile(dbSport.ProfileBlob);
            }
            if (model.IsActive == false)
            {
                var feeds = await _repo.RssFeeds.Where(m => m.TeamId == model.Id && m.DateDeletedUtc == null).ToListAsync();

                foreach (var feed in feeds)
                {
                    feed.IsActive = false;
                }
            }
            await _repo.SaveAsync();

            await _repo.Teams.AddOrUpdateAndSaveAsync(MapAddUpdate(true).CreateMapper().Map(model, dbSport));
        }
Beispiel #16
0
        public async Task PutTeam_Valid()
        {
            // Arrange
            var teamId  = 1;
            var team    = GetTestTeams().First(e => e.TeamId == teamId);
            var newTeam = new Team {
                TeamId = teamId, Name = "New Team Name", City = "New City", CountryId = 100
            };
            var teamService = new Mock <ITeamService>();

            teamService.Setup(repo => repo.UpdateTeamAsync(teamId, team)).Returns(Task.FromResult(newTeam));
            var controller = InitTeamsController(teamService);
            var vm         = new TeamViewModel {
                TeamId = newTeam.TeamId, Name = newTeam.Name, City = newTeam.City
            };

            // Act
            var result = await controller.PutTeam(teamId, vm);

            // Assert
            Assert.IsType <OkResult>(result);
        }
Beispiel #17
0
        public async Task <ServiceResponse <TeamEmp> > UpdateTeam(TeamViewModel teamviewmodel)

        {
            ServiceResponse <TeamEmp> serviceResponse = new ServiceResponse <TeamEmp>();

            try
            {
                TeamEmp teamUser = await _teamRepository.GetSingle(teamviewmodel.Id);

                if (teamUser != null)
                {
                    //CreatePasswordHash(userResetViewModel.Password, out byte[] passwordHash, out byte[] passwordSalt);

                    //oUser.PasswordHash = passwordHash;
                    //oUser.PasswordSalt = passwordSalt;

                    teamUser.TeamId   = teamviewmodel.TeamId;
                    teamUser.Teamtype = teamviewmodel.Teamtype;

                    serviceResponse.Data = await _teamRepository.UpdateData(teamUser);

                    serviceResponse.Message = "Update successfully";
                    serviceResponse.Data    = null;
                }
                else
                {
                    serviceResponse.Message   = "User not found";
                    serviceResponse.IsSuccess = false;
                }
            }
            catch (Exception ex)
            {
                serviceResponse.IsSuccess = false;
                serviceResponse.Message   = ex.Message;
                _logger.LogError($"Something went wrong inside Register action: {ex.Message}");
            }

            return(serviceResponse);
        }
Beispiel #18
0
        }                                                           // TODO move to model class


        public GameViewModel(Settings settings, GameState state, AudioPlaybackEngine audioPlaybackEngine, ActiveSceneContainer activeSceneContainer)
        {
            Random random = new Random();
            var    audioPlaybackEngine1 = audioPlaybackEngine;

            ScoreBoardTeam1   = new ScoreboardViewModel(state.Team1, HorizontalAlignment.Left);
            ScoreBoardTeam2   = new ScoreboardViewModel(state.Team2, HorizontalAlignment.Right);
            WordGameViewModel = new WordGameViewModel(state, audioPlaybackEngine);

            var bingoCardSettingsTeam1 = new BingoCardSettings(true, settings.ExcludedBallNumbersEven);
            var bingoCardSettingsTeam2 = new BingoCardSettings(false, settings.ExcludedBallNumbersOdd);

            Team1ViewModel = new TeamViewModel(0, ScoreBoardTeam1, ScoreBoardTeam2, WordGameViewModel, bingoCardSettingsTeam1, random, audioPlaybackEngine1, activeSceneContainer);
            Team2ViewModel = new TeamViewModel(1, ScoreBoardTeam1, ScoreBoardTeam2, WordGameViewModel, bingoCardSettingsTeam2, random, audioPlaybackEngine1, activeSceneContainer);

            CountDownStarted = ReactiveCommand.Create(() => new Unit());

            this.WhenAnyValue(x => x.WordGameViewModel.BoardViewModel).Where(x => x != null).Subscribe(x =>
            {
                WordGameStarted();
            });
        }
Beispiel #19
0
        public IActionResult Save(TeamViewModel vm)
        {
            try
            {
                bool isNew = vm.Id == Guid.Empty;
                vm.UserId = CurrentUserId;

                IEnumerable <Guid> oldMembers = vm.Members.Where(x => x.Id != Guid.Empty).Select(x => x.Id);

                OperationResultVo <Guid> saveResult = teamAppService.Save(CurrentUserId, vm);

                if (saveResult.Success)
                {
                    string url = Url.Action("Index", "Team", new { area = string.Empty, id = vm.Id.ToString(), pointsEarned = saveResult.PointsEarned });

                    Notify(vm, oldMembers);

                    bool recruiting = !vm.RecruitingBefore && vm.Recruiting;
                    GenerateTeamPost(vm, isNew, recruiting);


                    if (isNew)
                    {
                        NotificationSender.SendTeamNotificationAsync($"New team Created: {vm.Name}");
                    }

                    return(Json(new OperationResultRedirectVo(saveResult, url)));
                }
                else
                {
                    return(Json(new OperationResultVo(false)));
                }
            }
            catch (Exception ex)
            {
                return(Json(new OperationResultVo(ex.Message)));
            }
        }
        public static void RegisterTeam(TeamViewModel model, string employees, IEmployeeService employeeService, ITeamService teamService, ApplicationUserManager userManager)

        {
            using (TransactionScope transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                teamService.CreateTeam(Mapper.Map <TeamViewModel, TeamDTO>(new TeamViewModel
                {
                    TeamLeadID = model.TeamLeadID,
                    TeamID     = model.TeamID,
                    TeamName   = model.TeamName
                }));

                string members = employees;

                if (members != null)
                {
                    var result = members.Split(',');
                    foreach (var employeeId in result)
                    {
                        if (employeeId != model.TeamLeadID)
                        {
                            employeeService.AddToTeam(employeeId, model.TeamID);
                        }
                    }
                }

                var userRole = userManager.GetRoles(model.TeamLeadID).First();

                if (userRole == RoleEnum.Employee.ToString())

                {
                    userManager.RemoveFromRole(model.TeamLeadID, userRole);
                    userManager.AddToRoles(model.TeamLeadID, RoleEnum.TeamLeader.ToString());
                }

                transaction.Complete();
            }
        }
Beispiel #21
0
        public async Task <LogicResult> SetLeader(TeamViewModel viewModel)
        {
            LogicResult logicResult = new LogicResult();
            Team        team        = await _teamService.Include(s => s.Users).FirstOrDefaultAsync(a => a.TeamId == viewModel.TeamId);

            if (team != null)
            {
                await _userTeams.SetOffAllTeam(viewModel.UserId);

                team.Users.Add(new UserTeam
                {
                    TeamId        = viewModel.TeamId,
                    UserId        = viewModel.UserId,
                    IsLeader      = true,
                    IsCurrentTeam = true
                });
                _teamService.Update(team);
                int rowEffect = await _unitOfWork.SaveChangesAsync();

                if (rowEffect == 0)
                {
                    logicResult.MessageType = MessageType.Error;
                    logicResult.Message.Add(NotificationMessages.InvalidRecord);
                }
                else
                {
                    logicResult.MessageType = MessageType.Success;
                    logicResult.Message.Add(NotificationMessages.CreateSuccess);
                }
            }
            else
            {
                logicResult.MessageType = MessageType.Error;
                logicResult.Message.Add(NotificationMessages.RecordNotFounded);
            }

            return(logicResult);
        }
Beispiel #22
0
        public async Task <IActionResult> CreateTeam(TeamViewModel model)
        {
            if (ModelState.IsValid)
            {
                var path = string.Empty;
                model.Initials = model.Initials.ToUpper();
                model.League   = await _context.Leagues
                                 .FirstOrDefaultAsync(p => p.Id == model.LeagueId);

                if (model.LogoFile != null)
                {
                    path = await _imageHelper.UploadImageAsync(model.LogoFile, "Teams");
                }

                var team = _converterHelper.ToTeamEntity(model, path, true);
                _context.Teams.Add(team);
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction($"Details/{model.Id}"));
                }
                catch (Exception ex)
                {
                    if (ex.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, "Este Equipo ya existe");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, ex.InnerException.Message);
                    }
                }
            }

            //model.Leagues = _combosHelper.GetComboLeagues();
            return(View(model));
        }
Beispiel #23
0
        public async Task <IActionResult> Edit(int id, TeamViewModel teamViewModel)
        {
            if (id != teamViewModel.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                //Para esto se tenia que guardar en el hidden el .path
                string path = teamViewModel.LogoPath;
                if (teamViewModel.LogoFile != null)
                {
                    path = await _imageHelper.UploadImageAsync(teamViewModel.LogoFile, "Teams");
                }
                //Ahora creamos el entity usando el convertidor y lo guardamos pero con false
                TeamEntity teamEntity = _converterHelper.ToTeamEntity(teamViewModel, path, false);
                _context.Update(teamEntity);
                try
                {
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
                catch (Exception e)
                {
                    if (e.InnerException.Message.Contains("duplicate"))
                    {
                        ModelState.AddModelError(string.Empty, $"Ya existe un equipo con el nombre{teamEntity.Name}");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, e.InnerException.Message);
                    }
                }
            }
            return(View(teamViewModel));
        }
Beispiel #24
0
        public IActionResult GetMyTeam(string id)
        {
            var person = personService.GetPerson(id);

            if (person.TeamId == null)
            {
                ModelState.AddModelError("team", "Current person does not have a team");
                Log.Warning($"User with UserId: {id} does not have a team");
                return(BadRequest(ModelState));
            }
            string teamName = teamService.GetTeamNameById(person.TeamId.Value);

            var teamOfCurrentManager = mapper.Map <IEnumerable <PersonDTO>, IEnumerable <PersonViewModel> >(personService.GetTeam(id));

            var teamModel = new TeamViewModel
            {
                TeamName = (teamName != null) ? teamName : string.Empty,
                Team     = teamOfCurrentManager.ToList()
            };

            Log.Information($"Team with Id: {person.TeamId.Value} was been found for the user with UserId: {id}");
            return(Ok(teamModel));
        }
Beispiel #25
0
        public void Add(TeamViewModel teamViewModel)
        {
            List <Team> list = _teamRepository.GetTeamPerson(teamViewModel.PersonId).Result.ToList();

            list.ForEach(m => m.Active = false);
            _teamRepository.UpdateRange(list);

            var config = _configuration.GetValue <string>("Config:AtletaBase64");

            if (teamViewModel.Symbol == "")
            {
                teamViewModel.Symbol = Divers.Base64ToImage(config, "TEAM");
            }
            else
            {
                teamViewModel.Symbol = Divers.Base64ToImage(teamViewModel.Symbol, "TEAM");
            }

            teamViewModel.Picture = "semimagem.png";


            _teamRepository.Add(_mapper.Map <Team>(teamViewModel));
        }
        public List <TeamViewModel> GetSummaryScoreTeams()
        {
            var attendees = _attendeeProvider.GetAttendees().GroupBy(x => x.voteTeamId).Where(x => x.Key != null).ToList();
            var teams     = GetTeams();

            var teamViewModels = new List <TeamViewModel>();

            foreach (var item in teams)
            {
                var attendeeGroupBy = attendees.Where(x => x.Key == item.id).FirstOrDefault();
                var amount          = attendeeGroupBy == null ? 0 : attendeeGroupBy.Count();
                var newModel        = new TeamViewModel()
                {
                    id       = item.id,
                    code     = item.code,
                    name     = item.name,
                    division = item.division,
                    amount   = amount
                };
                teamViewModels.Add(newModel);
            }
            return(teamViewModels.OrderByDescending(x => x.amount).ToList());
        }
Beispiel #27
0
        public async Task AddTeamAsync(TeamViewModel model)
        {
            var team = new UserTeam
            {
                TeamName   = model.TeamName,
                TeamLeadId = model.UserId
            };

            var addteam = await _db.UserTeams.AddAsync(team);

            if (addteam != null && team.TeamLeadId != null)
            {
                var teamlead = new TeamDetail
                {
                    TeamId     = team.Id,
                    RoleInTeam = "Team Lead",
                    UserId     = model.UserId,
                };
                await _db.TeamDetails.AddAsync(teamlead);
            }

            await _db.SaveChangesAsync();
        }
        public async Task <IActionResult> Edit(TeamViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (ModelState.IsValid)
                {
                    var path = model.LogoPath;

                    if (model.LogoFile != null)
                    {
                        path = await _imageHelper.UploadImageAsync(model.LogoFile, "Teams");
                    }

                    TeamEntity team = _converterHelper.ToTeamEntity(model, path, false);
                    _context.Update(team);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }

            return(View(model));
        }
Beispiel #29
0
        public async Task <IActionResult> Edit(string identifier)
        {
            if (string.IsNullOrWhiteSpace(identifier))
            {
                return(NotFound());
            }

            var team = await _context.Teams.SingleAsync(t => t.TeamCode == identifier);

            if (team == null)
            {
                return(NotFound());
            }

            //Fetch participants explicitly
            await _context.Entry(team).Collection(t => t.Participants).LoadAsync();

            var teamViewModel = new TeamViewModel(team);

            ViewData["locations"] = FetchEventLocationSelectItemList();

            return(View(teamViewModel));
        }
        public async Task <ActionResult> TeamDetail(int teamId)
        {
            var team = await _dataService.GetFootballTeamAsync(teamId);

            if (team != null)
            {
                var model = new TeamViewModel
                {
                    Team        = team,
                    Countries   = await _dataService.GetCountryList(),
                    Action      = CommandAction.Edit,
                    TeamSummary = $"{team.Name} from {team.Country}"
                };

                return(View(model));
            }
            else
            {
                SetMessage("Team Not Found", $"Sorry we could NOT find a matching Team for TeamID:{teamId} !");

                return(RedirectToAction("Index"));
            }
        }
        public async Task <ActionResult> GetPlayDetail(string teamId, string playId, string playbookType)
        {
            try
            {
                var viewModel = new TeamViewModel();
                await viewModel.Load(teamId);

                var play = viewModel.Team.Plays.FirstOrDefault(x => x.Id == playId);
                play.RecommendedPlayList = JsonConvert.SerializeObject(play.RecommendedPlays);
                ViewData["TeamId"]       = teamId;
                ViewData["PlaybookType"] = playbookType;
                if (playbookType == "Offense")
                {
                    var defensePlaybooks = viewModel.Team.Playbooks.Where(x => x.PlaybookType.Name == "Defense" || x.PlaybookType.FriendlyName == "Defense").Select(x => x.Id).ToList();
                    ViewData["RecommendedPlays"] = viewModel.Team.Plays.Where(x => defensePlaybooks.Contains(x.PlaybookId)).ToList();
                }
                else if (playbookType == "Defense")
                {
                    var offensePlaybooks = viewModel.Team.Playbooks.Where(x => x.PlaybookType.Name == "Offense" || x.PlaybookType.FriendlyName == "Offense").Select(x => x.Id).ToList();
                    ViewData["RecommendedPlays"] = viewModel.Team.Plays.Where(x => offensePlaybooks.Contains(x.PlaybookId)).ToList();
                }
                else if (playbookType == "Special Team")
                {
                    var specialPlaybooks = viewModel.Team.Playbooks.Where(x => x.PlaybookType.Name == "Special Team" || x.PlaybookType.FriendlyName == "Special Team").Select(x => x.Id).ToList();
                    ViewData["RecommendedPlays"] = viewModel.Team.Plays.Where(x => specialPlaybooks.Contains(x.PlaybookId)).ToList();
                }
                else
                {
                    ViewData["RecommendedPlays"] = viewModel.Team.Plays.ToList();
                }
                return(PartialView("_AddPlayForm", play));
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Beispiel #32
0
        public async Task <IActionResult> Edit(int id, TeamViewModel teamViewModel)
        {
            if (id != teamViewModel.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    string path = teamViewModel.LogoPath;
                    if (teamViewModel.LogoFile != null)
                    {
                        path = await _imageHelper.UploadImageAsync(teamViewModel.LogoFile, "Teams");
                    }

                    TeamEntity teamEntity = _converterHelper.ToTeamEntity(teamViewModel, path, false);
                    _context.Update(teamEntity);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!_context.Teams.Any(e => e.Id == id))

                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(teamViewModel));
        }
Beispiel #33
0
        public ActionResult HomeEmpty()
        {
            var user = this.GetActiveUser(this.Request);

            if (user == null)
            {
                Response.Redirect("/");
            }
            else if (user.ActiveTeamId != null)
            {
                if (_teamService.GetTeam((int)user.ActiveTeamId) == null)
                {
                    // If active team id is somehow not a real team, correct this
                    var otherTeams = _teamService.GetTeams(user);
                    if (otherTeams.Count() > 0)
                    {
                        user.ActiveTeamId = otherTeams.First().Id;
                    }
                    else
                    {
                        user.ActiveTeamId = null;
                    }
                    _userService.UpdateUser(user);
                }

                if (user.ActiveTeamId != null)
                {
                    Response.Redirect("/teams/" + user.ActiveTeamId);
                }
            }

            var viewModel = new TeamViewModel {
                User = user
            };

            return(View("Home", viewModel));
        }
        public async Task <IActionResult> TeamMembersAsync(int teamId)
        {
            List <TeamMember> members = await GetAllTeamMembersAsync(teamId, new DisplayOptions { });

            if (members == null)
            {
                return(View("MembersError"));
            }

            var teams = await _manageTeamsService.GetMyTeamsAsync();

            var team = teams.FirstOrDefault(x => x.Id == teamId);

            if (team == null)
            {
                return(View("ErrorNotMember"));
            }

            if (await _accessCheckService.IsOwnerAsync(teamId))
            {
                ViewBag.AddVision = "visible";
            }
            else
            {
                ViewBag.AddVision = "collapse";
            }
            var teamViewModel = new TeamViewModel()
            {
                Id = team.Id, TeamName = team.TeamName, Owner = team.Owner, TeamMembers = new List <TeamMemberViewModel>()
            };

            members.ForEach(t => teamViewModel.TeamMembers.Add(new TeamMemberViewModel()
            {
                MemberId = t.MemberId, Member = t.Member
            }));
            return(View(teamViewModel));
        }
Beispiel #35
0
        public async Task <IActionResult> Analytics()
        {
            var teams = await _context.Teams
                        .Include(team => team.Participants)
                        .Where(x => x.CreatedOn.Year == DateTime.Now.Year)
                        .ToListAsync();

            var analytics = new TeamAnalyticsViewModel
            {
                TotalTeams        = teams.Count,
                TotalParticipants = teams.Sum(x => x.Participants.Count),
                TeamsByTheme      = teams.GroupBy(x => x.Theme)
                                    .OrderBy(y => y.Key)
                                    .Select(teamGroup => (teamGroup.Key, teamGroup.Count(),
                                                          teamGroup.Select(x => x.TeamName).ToList())).ToList(),
                TeamsByLocation = teams.GroupBy(x => x.Location)
                                  .OrderBy(y => y.Key)
                                  .Select(teamGroup => (teamGroup.Key, teamGroup.Count(),
                                                        teamGroup.Select(z => z.TeamName).ToList())).ToList(),
                AllParticipants  = teams.SelectMany(x => x.Participants.Select(y => TeamViewModel.SerializeParticipant(y))).ToList(),
                AllTeams         = teams.Select(x => TeamViewModel.SerializeTeam(x)).ToList(),
                TeamRequirements = teams.Select(x => (x.TeamName, x.ITRequirements, x.OtherRequirements)).ToList()
            };

            //Count selected themes eagerly, we are adding not chosen ones to same list
            analytics.ThemesSelectedCount = analytics.TeamsByTheme.Count;

            //Append themes not chosen by any teams
            var themesNotChosen = Enum.GetNames(typeof(Theme)).Except(analytics.TeamsByTheme.Select(x => x.Theme.ToString()));

            foreach (var themeNotChosen in themesNotChosen)
            {
                analytics.TeamsByTheme.Add((Theme: Enum.Parse <Theme>(themeNotChosen), TeamCount: 0, TeamList: null));
            }

            return(View(analytics));
        }
        public ActionResult Edit(TeamViewModel viewmodel, HttpPostedFileBase avatar)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    Team team = _teamDb.Find(viewmodel.ID);
                    if (team == null) return HttpNotFound();

                    team.Name = viewmodel.Name;

                    if (!_teamDb.Update(team))
                    {
                        //log error...
                        ModelState.AddModelError("", "An error occurred updating the use information");
                        return View(viewmodel);
                    }

                    //if an image has been provided then upload it
                    if (avatar != null && avatar.ContentLength > 0)
                    {
                        try
                        {
                            //delete the current avatar image
                            TeamAvatarImage currentImage = new TeamAvatarImage(Server, team.AvatarName);
                            System.IO.File.Delete(currentImage.AbsolutePath);
                        }
                        catch (CustomExceptionBase e)
                        {//safe error message for user
                            ModelState.AddModelError("", e.Message);
                            return View(viewmodel);
                        }
                        catch (Exception e)
                        {
                            //log error
                            ModelState.AddModelError("", "An error has occurred on the server.");
                            return View(viewmodel);
                        }

                        AvatarImage image = AvatarUploader.UploadFile2(Server, avatar, team.ID, AvatarTypeEnum.Team);

                        team.AvatarName = image.Name;
                        _teamDb.Update(team);

                    }

                    return RedirectToAction("Details", new { id = team.ID });
                }
                catch (CustomExceptionBase e)
                {
                    ModelState.AddModelError("", e.Message);
                }
                catch (Exception e)
                {
                    //log exception
                    //return error message to user
                    ModelState.AddModelError("", "Exception occured on the server");
                }

            }

            return View(viewmodel);
        }
Beispiel #37
0
 private TeamViewModel CreateTeamViewModel(Team team)
 {
     var model = new TeamViewModel();
       model.Id = team.Id;
       model.Name = team.Name;
       model.Players = team.Players.Select(p => new PlayerViewModel() { Id = p.Id, Name = p.FullName }).ToList();
       var completedMatchesQuery = from meet in team.Division.Meets
                           from match in meet.Matches
                           where meet.Teams.Contains(team) && match.IsComplete
                           select match;
       model.CanDelete = !completedMatchesQuery.Any();
       return model;
 }
Beispiel #38
0
 // GET: Team
 public ActionResult Index(int id)
 {
     var model = new TeamViewModel();
     using (ApplicationDbContext context = new ApplicationDbContext())
     {
         var team = context.Teams.Find(id);
         model.TeamId = id;
         model.RosterPlayersToAdd = new SelectList(team.RosterPlayers.Select(p => p.Player).ToList(), "Id", "LexicalName").ToList();
         model.RosterPlayers = team.RosterPlayers.Select(p => new PlayerInterval(p)).OrderBy(p => p, new PlayerIntervalComparer()).ToList();
         model.AvailablePlayers = AvailablePlayers(team.PoolId);
         model.Intervals = new SelectList(context.IntervalsByPoolSeason(team.PoolId, 2), "Id", "Name").ToList();
         //model.PlayerIntervals = GetPlayerIntervals(id, context.IntervalsByPoolSeason(team.PoolId, 1).First().Id).ToList();
         model.SelectedIntervalId = GetCurrentInterval();
         model.CanSubmit = GetCanSubmit(model.TeamId, model.SelectedIntervalId);
         model.SelectedStartTime = GetIntervalStartTime(model.SelectedIntervalId).ToString();
     }
     return View(model);
 }
 public ActionResult EditProperties(TeamViewModel model)
 {
     return PartialView("_team", model);
 }
        public ActionResult Edit(TeamViewModel model)
        {
            if (ModelState.IsValid)
            {
                BOTeam businessObject = _teamService.GetById(model.ID);
                Mapper.Map<TeamViewModel, BOTeam>(model, businessObject);

                _teamService.Save(businessObject);

                return RedirectToAction("Index");
            }

            return View(model);
        }
        public ActionResult Delete(TeamViewModel viewmodel)
        {
            try
            {
                var team = _teamDb.Find(viewmodel.ID);
                if (team == null) return HttpNotFound();

                //if there is a current image then delete it
                if (!String.IsNullOrEmpty(team.AvatarName))
                {
                    TeamAvatarImage image = new TeamAvatarImage(Server, team.AvatarName);
                    System.IO.File.Delete(image.AbsolutePath);
                }
            }
            catch (Exception e)
            {
                //log error...
                ModelState.AddModelError("", GenericErrorMessage);
                return View(viewmodel);
            }

            try
            {
                var playersOnTeam = _playerDb.FindAll().Where(x => x.TeamId == viewmodel.ID).ToList();

                playersOnTeam.ForEach(x =>
                    {
                        try
                        {
                            //delete this player from the database
                            _playerDb.Delete(x.ID);

                            //delete the players avatar
                            PlayerAvatarImage image = new PlayerAvatarImage(Server, x.AvatarName);
                            if(!String.IsNullOrEmpty(x.AvatarName))System.IO.File.Delete(image.AbsolutePath);
                        }
                        catch (Exception e)
                        {
                            //log error...
                        }
                    });//delete all players on the team first
                _teamDb.Delete(viewmodel.ID);
            }
            catch (Exception e)
            {
                //log error
                return Content("Error");//temp
            }

            return RedirectToAction("Index");
        }
        public ActionResult Details(int id)
        {
            var team = _teamDb.Find(id);
            if (team == null) return HttpNotFound();

            TeamAvatarImage image = new TeamAvatarImage(Server, team.AvatarName);//find out the correct path for the avatar (if there is one)
            TeamViewModel viewmodel = new TeamViewModel { ID = id, Name = team.Name };
            viewmodel.Avatar = image.Exists ? image.RelativePath : null;

            //build the list of players for this team to display
            viewmodel.PlayerList = _playerDb.FindAll().Where(x => x.TeamId == team.ID).Select(x => new PlayerViewModel { Name = x.Name, ID = x.ID }).ToList();

            return View(viewmodel);
        }
        public ActionResult Delete(int id)
        {
            var team = _teamDb.Find(id);
            if (team == null) return HttpNotFound();

            TeamAvatarImage image = new TeamAvatarImage(Server, team.AvatarName);

            TeamViewModel viewmodel = new TeamViewModel { ID = id, Name = team.Name };
            viewmodel.Avatar = image.Exists ? image.RelativePath : null;

            return View(viewmodel);
        }
Beispiel #44
0
        private void SetMakeBabiesMode()
        {
            IsAEnabled = true;
              IsBEnabled = true;
              IsVariantEnabled = false;
              IsMakeBabiesEnabled = true;
              ActiveTabIndex = 0;//teams A and B tab

              //if we haven't selected any genomes in A and B, select all from both
              var allSelectedGenomes = new List<Genome>();
              var teams = new TeamViewModel[] { TeamA, TeamB };
              foreach (var teamVM in teams)
              {
            //if we dont have a team in this vm or if that team has no genomes, then go to the next team.
            if (teamVM.Team == null || teamVM.Team.Genomes.Count == 0)
              continue;

            var selectedGenomes = from gItemVM in teamVM.Items
                              where ((GenomeItemViewModel)gItemVM).IsChecked
                              select ((GenomeItemViewModel)gItemVM);
            if (selectedGenomes.Count() == 0)
            {
              //this team has no selection
              foreach (var itemViewModel in teamVM.Items)
              {
            ((GenomeItemViewModel)itemViewModel).IsChecked = true;
              }
            }
              }
        }
Beispiel #45
0
        private bool CanMakeBabies()
        {
            if (TeamA.Team == null || TeamB.Team == null)
            return false;
              if (TeamA.Team.Genomes.Count == 0 || TeamB.Team.Genomes.Count == 0)
            return false;

              var teams = new TeamViewModel[] { TeamA, TeamB };
              foreach (var teamVM in teams)
              {
            var selectedGenomes = from gItemVM in teamVM.Items
                              where ((GenomeItemViewModel)gItemVM).IsChecked
                              select ((GenomeItemViewModel)gItemVM);
            if (selectedGenomes.Count() == 0)
            {
              return false;
            }
              }

              return true;
        }
Beispiel #46
0
 private void Select(TeamViewModel teamViewModel, SelectModes mode)
 {
     foreach (var screen in teamViewModel.Items)
       {
     var vm = (GenomeItemViewModel)screen;
     if (mode == SelectModes.All)
       vm.IsChecked = true;
     else if (mode == SelectModes.None)
       vm.IsChecked = false;
     else
       vm.IsChecked = !vm.IsChecked;
       }
 }
Beispiel #47
0
        private void PruneAandB()
        {
            var teams = new TeamViewModel[] { TeamA, TeamB };
              foreach (var teamVM in teams)
              {
            var selectedGenomeItemViewModels = from gItemVM in teamVM.Items
                                           where ((GenomeItemViewModel)gItemVM).IsChecked
                                           select ((GenomeItemViewModel)gItemVM);
            var itemsToRemove = new List<GenomeItemViewModel>();
            foreach (var selectedItem in selectedGenomeItemViewModels)
            {
              teamVM.Team.Prune(selectedItem.Genome); //model: remove the genome
              itemsToRemove.Add(selectedItem);        //viewmodel: add item to be removed from VM
            }

            foreach (var itemVM in itemsToRemove)
            {
              teamVM.Items.Remove(itemVM);            //viewmodel: remove that VM
            }
              }
        }
Beispiel #48
0
        private void HybridizeSelectedGenomes()
        {
            var allSelectedGenomes = new List<Genome>();
              var teams = new TeamViewModel[] { TeamA, TeamB };
              foreach (var teamVM in teams)
              {
            var selectedGenomes = from gItemVM in teamVM.Items
                              where ((GenomeItemViewModel)gItemVM).IsChecked
                              select ((GenomeItemViewModel)gItemVM).Genome;
            allSelectedGenomes.AddRange(selectedGenomes);
              }

              if (allSelectedGenomes.Count == 0)
              {
            //Variant = null;
            return;
              }

              var newTeam = new Team();
              for (int i = 0; i < allSelectedGenomes.Count; i++)
              {
            var genome = allSelectedGenomes[i];
            genome.Id = i + 1;
              }
              newTeam.Genomes.AddRange(allSelectedGenomes);
              Variant.Team = newTeam;
              if (string.IsNullOrEmpty(Variant.WorkingDir))
            Variant.WorkingDir = TeamA.WorkingDir;
              var nameContribTeamA = TeamA.TeamFileName;
              var nameContribTeamB = TeamB.TeamFileName;
              if (!string.IsNullOrEmpty(TeamA.SaveName))
            nameContribTeamA = TeamA.SaveName;
              if (!string.IsNullOrEmpty(TeamB.SaveName))
            nameContribTeamB = TeamB.SaveName;

              Variant.SaveName = nameContribTeamA + "_" + nameContribTeamB + "_mix_" +
                         new Random().Next(0, 1000).ToString() +
                         "." + Properties.Resources.DefaultFileExtension;
        }
Beispiel #49
0
 private IEnumerable<GenomeItemViewModel> GetSelectedItems(TeamViewModel teamVM)
 {
     return from item in teamVM.Items
      where ((GenomeItemViewModel)item).IsChecked
      select (GenomeItemViewModel)item;
 }
Beispiel #50
0
        private void DuplicateSelectedGenomes()
        {
            var teams = new TeamViewModel[] { TeamA, TeamB };
              foreach (var teamVM in teams)
              {
            var selectedGenomeItemViewModels = from gItemVM in teamVM.Items
                                           where ((GenomeItemViewModel)gItemVM).IsChecked
                                           select ((GenomeItemViewModel)gItemVM);
            var itemsToAdd = new List<GenomeItemViewModel>();

            foreach (var selectedItem in selectedGenomeItemViewModels)
            {
              //model
              var duplicate = teamVM.Team.DuplicateGenome(selectedItem.Genome); //model: duplicate the genome model
              teamVM.Team.Genomes.Add(duplicate);

              //viewmodel
              GenomeItemViewModel genomeItemVM = new GenomeItemViewModel();
              genomeItemVM.Genome = duplicate;
              itemsToAdd.Add(genomeItemVM);
            }

            foreach (var itemVM in itemsToAdd)
            {
              //add viewmodels
              teamVM.Items.Add(itemVM);
            }
              }
        }