public IHttpActionResult ContestRegistration(int contest_id, [FromBody] ContestRegistrationFormData registration_form_data) { if (RequestUtility.IsPreFlightRequest(Request)) { return(Ok()); } try{ // todo replace user id 2 with the user sending the request contest_repository.RegisterUserForContest(contest_id, 2, registration_form_data); return(Ok()); } catch (ObjectNotFoundException e) { return(NotFound()); } catch (InvalidOperationException e) { return(InternalServerError(e)); } }
public Contestant RegisterUserForContest(int contest_id, int user_id, ContestRegistrationFormData data) { Contest contest = context.Contests.Include(x => x.Contestants).FirstOrDefault(x => x.Id == contest_id); var user = context.Users.Find(user_id); if (contest == null) { throw new ObjectNotFoundException("Contest with specified id not found"); } if (user == null) { throw new ObjectNotFoundException("User with specified id not found"); } // if user is already registered for this contest if (contest.Contestants.Count(x => x.User == user) > 0) { throw new InvalidOperationException("User is already registered for contest"); } if (!contest.IsPublic && contest.Password != data.Password) { throw new InvalidOperationException("Wrong password for registation"); } if (contest.StartDate < DateTime.Now) { throw new InvalidOperationException("Contest registration time has ended"); } Trace.WriteLine(contest.Contestants.Count); var contestant = new Contestant(user); contest.Contestants.Add(contestant); context.SaveChanges(); return(contestant); }