Inheritance: System.Web.UI.Page
Exemple #1
0
        public IActionResult Put(string id, [FromBody] Submissions value)
        {
            var submission = Respository.UpdateItemAsync(id, value);

            return(Ok(submission.Result));
        }
        /// <summary>
        /// Adds a submission to the given assignment for the given student
        /// The submission should use the current time as its DateTime
        /// You can get the current time with DateTime.Now
        /// The score of the submission should start as 0 until a Professor grades it
        /// If a Student submits to an assignment again, it should replace the submission contents
        /// and the submission time (the score should remain the same).
        /// </summary>
        /// <param name="subject">The course subject abbreviation</param>
        /// <param name="num">The course number</param>
        /// <param name="season">The season part of the semester for the class the assignment belongs to</param>
        /// <param name="year">The year part of the semester for the class the assignment belongs to</param>
        /// <param name="category">The name of the assignment category in the class</param>
        /// <param name="asgname">The new assignment name</param>
        /// <param name="uid">The student submitting the assignment</param>
        /// <param name="contents">The text contents of the student's submission</param>
        /// <returns>A JSON object containing {success = true/false}</returns>
        public IActionResult SubmitAssignmentText(string subject, int num, string season, int year,
                                                  string category, string asgname, string uid, string contents)
        {
            // get the assignment id
            var query =
                from enrollment in db.Enrolled
                where enrollment.UId == uid
                from c in db.Classes
                where c.CId == enrollment.CId &&
                c.Catalog.Listing == subject &&
                Int32.Parse(c.Catalog.Number) == num &&
                c.SemesterSeason == season &&
                c.SemesterYear == year
                from assCat in db.AssignmentCategories
                where assCat.CId == c.CId &&
                assCat.Name == category
                from assignment in db.Assignments
                where assignment.AcId == assCat.AcId &&
                assignment.Name == asgname
                select assignment;

            var assignmentInfo = query.FirstOrDefault();

            if (assignmentInfo == null)
            {
                return(Json(new { success = false }));
            }

            // check to see if this is a re-submission
            var resubmissionQuery =
                from submission in db.Submissions
                where submission.UId == uid &&
                submission.AId == assignmentInfo.AId
                select submission;

            var resubmission = resubmissionQuery.FirstOrDefault();

            if (resubmission != null)
            {
                // there is already a submission for this assignment -> update the existing one
                resubmission.Content = contents;
                resubmission.Time    = DateTime.Now;
                int rowsAffected = db.SaveChanges();
                return(Json(new { success = rowsAffected > 0 }));
            }
            else
            {
                // there is no previous submission -> create a new one

                var newSubmission = new Submissions {
                    UId     = uid,
                    AId     = assignmentInfo.AId,
                    Time    = DateTime.Now,
                    Content = contents,
                    Score   = 0
                };
                db.Submissions.Add(newSubmission);
                int rowsAffected = db.SaveChanges();

                return(Json(new { success = rowsAffected > 0 }));
            }
        }
Exemple #3
0
        public IActionResult Post([FromBody] Submissions value)
        {
            var submission = Respository.CreateItemAsync(value).Result;

            return(Ok(submission));
        }
 public SubmitCommand(Submissions subda, HttpPostedFile upfile, int asstID, int prinID)
 {
     m_upfile = upfile; m_asstID = asstID; m_prinID = prinID; m_subda = subda;
 }
        public async Task <IActionResult> OnPostAsync(int puzzleId)
        {
            if (!this.Event.IsAnswerSubmissionActive)
            {
                return(RedirectToPage("/Submissions/Index", new { puzzleid = puzzleId }));
            }

            await SetupContext(puzzleId);

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            // Don't allow submissions after the answer has been found.
            if (PuzzleState.SolvedTime != null)
            {
                return(Page());
            }

            // Create submission and add it to list
            Submission submission = new Submission
            {
                SubmissionText = SubmissionText,
                TimeSubmitted  = DateTime.UtcNow,
                Puzzle         = PuzzleState.Puzzle,
                Team           = PuzzleState.Team,
                Submitter      = LoggedInUser,
            };

            submission.Response = await _context.Responses.Where(
                r => r.Puzzle.ID == puzzleId &&
                submission.SubmissionText == r.SubmittedText)
                                  .FirstOrDefaultAsync();

            Submissions.Add(submission);

            // Update puzzle state if submission was correct
            if (submission.Response != null && submission.Response.IsSolution)
            {
                await PuzzleStateHelper.SetSolveStateAsync(_context,
                                                           Event,
                                                           submission.Puzzle,
                                                           submission.Team,
                                                           submission.TimeSubmitted);
            }
            else if (submission.Response == null)
            {
                // We also determine if the puzzle should be set to email-only mode.
                if (IsPuzzleSubmissionLimitReached(
                        Event,
                        Submissions,
                        PuzzleState))
                {
                    await PuzzleStateHelper.SetEmailOnlyModeAsync(_context,
                                                                  Event,
                                                                  submission.Puzzle,
                                                                  submission.Team,
                                                                  true);

                    var authors = await _context.PuzzleAuthors.Where((pa) => pa.Puzzle == submission.Puzzle).Select((pa) => pa.Author.Email).ToListAsync();

                    MailHelper.Singleton.SendPlaintextBcc(authors,
                                                          $"{Event.Name}: Team {submission.Team.Name} is in email mode for {submission.Puzzle.Name}",
                                                          "");
                }
                else
                {
                    // If the submission was incorrect and not a partial solution,
                    // we will do the lockout computations now.
                    DateTime?lockoutExpiryTime = ComputeLockoutExpiryTime(
                        Event,
                        Submissions,
                        PuzzleState);

                    if (lockoutExpiryTime != null)
                    {
                        await PuzzleStateHelper.SetLockoutExpiryTimeAsync(_context,
                                                                          Event,
                                                                          submission.Puzzle,
                                                                          submission.Team,
                                                                          lockoutExpiryTime);
                    }
                }
            }

            _context.Submissions.Add(submission);
            await _context.SaveChangesAsync();

            return(RedirectToPage(
                       "/Submissions/Index",
                       new { puzzleid = puzzleId }));
        }
        // GET: Admin
        public ActionResult Index(int?sid)
        {
            UserAuth user = new UserAuth();

            ViewBag.server = System.Environment.MachineName;

            user = AuthorizeUser(User.Identity.Name.ToString());

            if (!user.authorizedAdmin)
            {
                return(RedirectToAction("Unauthorized", "Home"));
            }

            UserProfile_Conf uid = db.UserProfile_Conf.SingleOrDefault(x => x.NTUserName == User.Identity.Name.ToString());

            ViewBag.UserProfileID = uid.UserProfileID;
            ViewBag.admin         = user.authorizedAdmin;
            // web.config debug setting
            ViewBag.debug = HttpContext.IsDebuggingEnabled;

            // Check if there are "Pending Fixes" before allowing them to submit again
            if (sid != 0)
            {
                Submissions submitedRec = entitiesdb.Submissions.Find(sid);
                //Submissions submitedRec = entitiesdb.Submissions
                //                            .Where(x => x.Status == "Pending Fixes")
                //                            .OrderByDescending(x => x.ID)
                //                            .Select(x => x).FirstOrDefault();
                if (submitedRec != null)
                {
                    return(RedirectToAction("SubmissionStatusGet", "StopsSubmission", new { sid = submitedRec.ID, endDate = submitedRec.EndDate }));
                }
            }

            Submissions dateRec = entitiesdb.Submissions
                                  .OrderByDescending(x => x.EndDate)
                                  .Select(x => x).FirstOrDefault();

            if (dateRec != null)
            {
                startDate = Convert.ToDateTime(dateRec.EndDate).AddDays(1);
            }
            else
            {
                string InitStrtSubDate = ConfigurationManager.AppSettings["InitStrtSubDate"];
                startDate = Convert.ToDateTime(InitStrtSubDate);
            }
            //List<Stop> Stops = db.Stop
            //        .Where(x => x.Status.Trim() != "success").ToList();
            //ExtractJNode eJson;
            //foreach (Stop st in Stops)
            //{
            //    //extract date from JsonStop
            //    JObject JsonStopO;
            //    JsonStopO = JObject.Parse(st.JsonStop);
            //    eJson = new ExtractJNode("date", JsonStopO);
            //    startDate = Convert.ToDateTime(eJson.traverseNode());

            //    // Only stops after July 1st 2018 should be submitted
            //    //if (startDate >= Convert.ToDateTime("2018-07-01"))
            //    if (startDate >= Convert.ToDateTime("2018-04-17"))
            //    {
            //        break;
            //    }
            //}
            Submissions submission = new Submissions();

            if (startDate.ToString() == "1/1/0001 12:00:00 AM")
            {
                ModelState.AddModelError(string.Empty, "There are no records to submit");
            }
            else
            {
                submission.StartDate = startDate;
                ViewBag.StartDate    = startDate.ToString();
                if (TempData["CustomError"] != null)
                {
                    ModelState.AddModelError(string.Empty, TempData["CustomError"].ToString());
                }
            }
            submission.subList = entitiesdb.Submissions
                                 .OrderByDescending(x => x.StartDate)
                                 .ThenByDescending(y => y.DateSubmitted).ToList();

            return(View(submission));
        }
Exemple #7
0
        public async Task <IActionResult> OnGetAsync()
        {
            var username = HttpContext.Session.GetString("_username");
            var usertype = HttpContext.Session.GetString("_usertype");
            var access   = new Access(username, "Student");

            if (access.IsLogin())
            {
                if (access.IsAuthorize(usertype))
                {
                    Student = await _context.Student
                              .Where(s => s.DateDeleted == null)
                              .FirstOrDefaultAsync(s => s.AssignedId == username);

                    SubmissionType = await _context.SubmissionType
                                     .Where(s => s.DateDeleted == null)
                                     .Where(s => s.BatchId == Student.BatchId)
                                     .Where(s => s.StartDate <= DateTime.Now)
                                     .Where(s => s.GraceDate >= DateTime.Now)
                                     .FirstOrDefaultAsync();

                    // check if submitted
                    HasSubmit = false;

                    if (Student.ProjectId != null)
                    {
                        Project = await _context.Project
                                  .Where(p => p.DateDeleted == null)
                                  .FirstOrDefaultAsync(p => p.ProjectId == Student.ProjectId);

                        Submissions = await _context.Submission
                                      .Where(s => s.DateDeleted == null)
                                      .Where(w => w.ProjectId == Project.ProjectId)
                                      .Include(w => w.Project)
                                      .ToListAsync();

                        if (Submissions.Count() > 0 && SubmissionType != null)
                        {
                            foreach (var submission in Submissions)
                            {
                                if (submission.SubmissionTypeId == SubmissionType.SubmissionTypeId)
                                {
                                    HasSubmit = true;
                                    break;
                                }
                            }
                        }
                    }

                    return(Page());
                }
                else
                {
                    ErrorMessage = "Access Denied";
                    return(RedirectToPage($"/{usertype}/Index"));
                }
            }
            else
            {
                ErrorMessage = "Login Required";
                return(RedirectToPage("/Account/Login"));
            }
        }
        public ActionResult SubmissionStatusGet(int?sid, DateTime?endDate)
        {
            UserAuth user = new UserAuth();

            ViewBag.server = System.Environment.MachineName;

            user = AuthorizeUser(User.Identity.Name.ToString());

            if (!user.authorizedAdmin)
            {
                return(RedirectToAction("Unauthorized", "Home"));
            }

            UserProfile_Conf uid = db.UserProfile_Conf.SingleOrDefault(x => x.NTUserName == User.Identity.Name.ToString());

            ViewBag.UserProfileID = uid.UserProfileID;
            ViewBag.admin         = user.authorizedAdmin;

            // web.config debug setting
            ViewBag.debug = HttpContext.IsDebuggingEnabled;

            Submissions submission = entitiesdb.Submissions.Find(sid);

            if (endDate == null)
            {
                endDate = submission.EndDate;
            }
            ViewBag.submissionEndDate = endDate;

            if (endDate < submission.StartDate || endDate > DateTime.Now)
            {
                TempData["CustomError"] = "Invalid Date Range";
                return(RedirectToAction("Index", "StopsSubmission", sid));
            }
            else
            {
                submission.statusMsgs = entitiesdb.StatusMessage_JSON_vw
                                        .Where(x => x.submissionID == sid && x.StopStatus != "success" && x.StopStatus != "postSubRedact")
                                        .ToList();
                submission.subList = entitiesdb.Submissions
                                     .Where(x => x.StartDate == submission.StartDate &&
                                            x.EndDate == submission.EndDate).ToList();
            }
            bool        fixedFlag = false;
            List <Stop> Stops     = db.Stop.Where(x => x.SubmissionsID == submission.ID && x.Status != "success" && x.JsonSubmissions != null && x.JsonSubmissions.Substring(x.JsonSubmissions.Length - 15).IndexOf("true") != -1).ToList();

            if (Stops.Count != 0)
            {
                fixedFlag = true;
            }


            int stopsCount = entitiesdb.StopOfficerIDDateTime_JSON_vw.ToList()
                             .Join(db.Stop,
                                   j => j.ID,
                                   s => s.ID,
                                   (j, s) => new { StopOfficerIDDateTime_JSON_vw = j, Stop = s })
                             .Where(x => submission.StartDate <= Convert.ToDateTime(x.StopOfficerIDDateTime_JSON_vw.stopDate) && Convert.ToDateTime(x.StopOfficerIDDateTime_JSON_vw.stopDate) <= endDate).Count();

            ViewBag.fixedFlag  = fixedFlag;
            ViewBag.totalStops = stopsCount;

            return(View(submission));
        }
        public async Task <ActionResult> SubmissionStats(Submissions submission, int?sid, DateTime startDate, DateTime?endDate)
        {
            UserAuth user = new UserAuth();

            user = AuthorizeUser(User.Identity.Name.ToString());

            if (!user.authorizedAdmin)
            {
                return(RedirectToAction("Unauthorized", "Home"));
            }

            if (ModelState.IsValid)
            {
                UserProfile_Conf uid = db.UserProfile_Conf.SingleOrDefault(x => x.NTUserName == User.Identity.Name.ToString());
                ViewBag.UserProfileID = uid.UserProfileID;
                ViewBag.admin         = user.authorizedAdmin;

                // web.config debug setting
                ViewBag.debug             = HttpContext.IsDebuggingEnabled;
                ViewBag.submissionEndDate = endDate;
                DOJSubmitController dOJSubmit = new DOJSubmitController();

                //Make sure the connection to DOJ url is available
                //DOJSubmitController.connectionStatus connectStat = dOJSubmit.HTTP_Connection();
                //if (!connectStat.connected)
                //{
                //    TempData["CustomError"] = connectStat.error;
                //    return RedirectToAction("Index", "StopsSubmission", sid);
                //}

                bool connected = dOJSubmit.HTTP_Connection2();
                if (!connected)
                {
                    TempData["CustomError"] = "Can not connect to DOJ endpoint\r\n";
                    return(RedirectToAction("Index", "StopsSubmission", sid));
                }
                // If submission record in this date range is In Progress do not allow another submission
                Submissions submissionInProgress = entitiesdb.Submissions
                                                   .Where(x => x.StartDate == startDate && x.EndDate == endDate && x.Status == "In Progress")
                                                   .FirstOrDefault();

                if (submissionInProgress != null)
                {
                    TempData["CustomError"] = "A submission in this date range is already 'In Progress'";
                    return(RedirectToAction("Index", "StopsSubmission", sid));
                }

                if (sid != 0)
                {
                    Submissions submissionOld = entitiesdb.Submissions.Find(sid);
                    if (submissionOld.TotalHTTPErrors == 0 || submissionOld.TotalHTTPErrors == null)
                    {
                        submission = submissionOld;
                    }
                }
                submission.StartDate = startDate;
                if (endDate < submission.StartDate || endDate > DateTime.Now)
                {
                    TempData["CustomError"] = "Invalid Date Range";
                    return(RedirectToAction("Index", "StopsSubmission", sid));
                }
                else
                {
                    bool        fixedFlag = false;
                    List <Stop> Stops     = db.Stop.Where(x => x.SubmissionsID == submission.ID && x.JsonSubmissions != null && x.JsonSubmissions.Substring(x.JsonSubmissions.Length - 15).IndexOf("true") != -1).ToList();

                    if (Stops.Count != 0)
                    {
                        fixedFlag = true;
                    }

                    ViewBag.fixedFlag = fixedFlag;

                    // Change the status of the current submission record, with edited Stops, to "resumbit",
                    // and create a new submission record to Resubmit all the fixed records again
                    if (Stops.Count != 0)
                    {
                        submission.Status = "Resubmit";
                        if (ModelState.IsValid)
                        {
                            entitiesdb.Entry(submission).State = EntityState.Modified;
                            await entitiesdb.SaveChangesAsync();
                        }
                        Submissions newSubmission = new Submissions();
                        newSubmission.StartDate = submission.StartDate;
                        submission = newSubmission;
                    }
                    submission.Status        = "In Progress";
                    submission.DateSubmitted = DateTime.Now;
                    submission.EndDate       = endDate;

                    var state = await dOJSubmit.GetStops(submission);

                    entitiesdb.Entry(submission).State = state;

                    if (submission.TotalProcessed == submission.TotalSuccess)
                    {
                        submission.Status = "Finished";
                    }
                    else
                    {
                        submission.Status     = "Pending Fixes";
                        submission.statusMsgs = entitiesdb.StatusMessage_JSON_vw
                                                .Where(x => x.submissionID == submission.ID && x.StopStatus != "success" && x.StopStatus != "postSubRedact")
                                                .ToList();
                        submission.subList = entitiesdb.Submissions.ToList();
                    }
                    //If ModelState.IsValid is not True this might
                    //cause submission to stay in 'In Progress' status
                    //
                    if (ModelState.IsValid)
                    {
                        //state = entitiesdb.Entry(submission).State;
                        //entitiesdb.Entry(submission).State = EntityState.Modified;
                        entitiesdb.SaveChanges();
                        ViewBag.submissionID = submission.ID;
                    }
                }
            }
            else
            {
                TempData["CustomError"] = "End Date is required.";
            }


            return(RedirectToAction("Index", "StopsSubmission", submission.ID));
        }
        //***************************************************************
        //Name: FindSubmission()
        //Purpose: This method takes the assignment name as a parameter.It should
        //         return the Submission with the given assignment name.If it is
        //         not found then return null.
        //Input Type: string asn - assignment name
        //Output Type: Submission - returns submission object or null
        //***************************************************************
        public Submission FindSubmission(string asn)
        {
            Submission result = Submissions.Find(x => x.AssignmentName == asn);

            return(result);
        }
Exemple #11
0
        public async Task <ActionResult> Submit([Bind(Include = "Id,Votes,Name,Date,Type,Linkdescription,Title,Rank,MessageContent,Subverse")] Message submission)
        {
            // abort if model state is invalid
            if (!ModelState.IsValid)
            {
                return(View());
            }

            // save temp values for the view in case submission fails
            ViewBag.selectedSubverse = submission.Subverse;
            ViewBag.message          = submission.MessageContent;
            ViewBag.title            = submission.Title;
            ViewBag.linkDescription  = submission.Linkdescription;

            // grab server timestamp and modify submission timestamp to have posting time instead of "started writing submission" time
            submission.Date = DateTime.Now;

            // check if user is banned
            if (UserHelper.IsUserGloballyBanned(User.Identity.Name) || UserHelper.IsUserBannedFromSubverse(User.Identity.Name, submission.Subverse))
            {
                ViewBag.SelectedSubverse = submission.Subverse;
                return(View("~/Views/Home/Comments.cshtml", submission));
            }

            // check if subverse exists
            var targetSubverse = _db.Subverses.Find(submission.Subverse.Trim());

            if (targetSubverse == null || submission.Subverse.Equals("all", StringComparison.OrdinalIgnoreCase))
            {
                ModelState.AddModelError(string.Empty, "Sorry, The subverse you are trying to post to does not exist.");
                return(View("Submit"));
            }

            //wrap captcha check in anon method as following method is in non UI dll
            var captchaCheck = new Func <HttpRequestBase, Task <bool> >(request => {
                return(ReCaptchaUtility.Validate(request));
            });

            // check if this submission is valid and good to go
            var preProcessCheckResult = await Submissions.PreAddSubmissionCheck(submission, Request, User.Identity.Name, targetSubverse, captchaCheck);

            if (preProcessCheckResult != null)
            {
                ModelState.AddModelError(string.Empty, preProcessCheckResult);
                return(View("Submit"));
            }

            // submission is a link post
            if (submission.Type == 2 && submission.MessageContent != null && submission.Linkdescription != null)
            {
                // check if same link was submitted before and deny submission
                var existingSubmission = _db.Messages.FirstOrDefault(s => s.MessageContent.Equals(submission.MessageContent, StringComparison.OrdinalIgnoreCase) && s.Subverse.Equals(submission.Subverse, StringComparison.OrdinalIgnoreCase));

                // submission is a repost, discard it and inform the user
                if (existingSubmission != null)
                {
                    ModelState.AddModelError(string.Empty, "Sorry, this link has already been submitted by someone else.");

                    // todo: offer the option to repost after informing the user about it
                    return(RedirectToRoute(
                               "SubverseComments",
                               new
                    {
                        controller = "Comment",
                        action = "Comments",
                        id = existingSubmission.Id,
                        subversetoshow = existingSubmission.Subverse
                    }
                               ));
                }

                // process new link submission
                var addLinkSubmissionResult = await Submissions.AddNewSubmission(submission, targetSubverse, User.Identity.Name);

                if (addLinkSubmissionResult != null)
                {
                    ModelState.AddModelError(string.Empty, addLinkSubmissionResult);
                    return(View("Submit"));
                }
            }
            // submission is a message type submission
            else if (submission.Type == 1 && submission.Title != null)
            {
                // process new message type submission
                var addMessageSubmissionResult = await Submissions.AddNewSubmission(submission, targetSubverse, User.Identity.Name);

                if (addMessageSubmissionResult != null)
                {
                    ModelState.AddModelError(string.Empty, addMessageSubmissionResult);
                    return(View("Submit"));
                }
            }

            // redirect to comments section of newly posted submission
            return(RedirectToRoute(
                       "SubverseComments",
                       new
            {
                controller = "Comment",
                action = "Comments",
                id = submission.Id,
                subversetoshow = submission.Subverse
            }
                       ));
        }
Exemple #12
0
        /// <summary>
        /// Recreate the file permissions table
        /// </summary>
        public void RecoverBaseFilePermissions()
        {
            //Get all submissions
            Components.Submission.SubmissionList subs = new Submissions(m_ident).GetAll();
            Assignments asstda   = new Assignments(m_ident);
            Courses     courseda = new Courses(m_ident);

            CFilePermission.FilePermissionList full;

            foreach (Components.Submission sub in subs)
            {
                CFile subdir   = GetFile(sub.LocationID);
                int   courseID = asstda.GetInfo(sub.AsstID).CourseID;

                //Give staff access
                CourseRole.CourseRoleList staff = courseda.GetTypedRoles(courseID, true, null);
                foreach (CourseRole role in staff)
                {
                    full = CFilePermission.CreateFullAccess(role.PrincipalID);
                    SetPermissionsInt(subdir, full);
                }

                //Give sub principal access
                full = CFilePermission.CreateOprFullAccess(sub.PrincipalID);
                SetPermissionsInt(subdir, full);
            }

            //Do content
            Course.CourseList courses = courseda.GetAll();
            foreach (Course course in courses)
            {
                CFile cont = GetFile(course.ContentID);

                //Give staff access
                CourseRole.CourseRoleList staff = courseda.GetTypedRoles(course.ID, true, null);
                foreach (CourseRole role in staff)
                {
                    full = CFilePermission.CreateFullAccess(role.PrincipalID);
                    SetPermissionsInt(cont, full);
                }
                //Give students read access
                CourseRole.CourseRoleList stu = courseda.GetTypedRoles(course.ID, false, null);
                foreach (CourseRole role in stu)
                {
                    full = new CFilePermission.FilePermissionList();
                    full.Add(new CFilePermission(role.PrincipalID, FileAction.READ, true));
                    SetPermissionsInt(cont, full);
                }

                //Give staff  and stuaccess to asst content
                Assignment.AssignmentList assts = courseda.GetAssignments(course.ID);
                foreach (Assignment asst in assts)
                {
                    CFile acont = GetFile(asst.ContentID);
                    foreach (CourseRole role in staff)
                    {
                        full = CFilePermission.CreateFullAccess(role.PrincipalID);
                        SetPermissionsInt(acont, full);
                    }
                    foreach (CourseRole role in stu)
                    {
                        full = new CFilePermission.FilePermissionList();
                        full.Add(new CFilePermission(role.PrincipalID, FileAction.READ, true));
                        SetPermissionsInt(acont, full);
                    }
                }
            }
        }
Exemple #13
0
        public async Task <IActionResult> OnPostAsync(int puzzleId, string submissionText)
        {
            if (String.IsNullOrWhiteSpace(submissionText))
            {
                ModelState.AddModelError("submissionText", "Your answer cannot be empty");
            }

            SubmissionText = submissionText;
            if (!this.Event.IsAnswerSubmissionActive)
            {
                return(Page());
            }

            await SetupContext(puzzleId);

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            // Don't allow submissions after the answer has been found.
            if (PuzzleState.SolvedTime != null)
            {
                return(Page());
            }

            // Don't accept posted submissions when a puzzle is causing lockout
            if (PuzzlesCausingGlobalLockout.Count != 0 && !PuzzlesCausingGlobalLockout.Contains(Puzzle))
            {
                return(Page());
            }

            // Soft enforcement of duplicates to give a friendly message in most cases
            DuplicateSubmission = (from sub in Submissions
                                   where sub.SubmissionText == ServerCore.DataModel.Response.FormatSubmission(submissionText)
                                   select sub).Any();

            if (DuplicateSubmission)
            {
                return(Page());
            }

            // Create submission and add it to list
            Submission submission = new Submission
            {
                SubmissionText = submissionText,
                TimeSubmitted  = DateTime.UtcNow,
                Puzzle         = PuzzleState.Puzzle,
                Team           = PuzzleState.Team,
                Submitter      = LoggedInUser,
            };

            submission.Response = await _context.Responses.Where(
                r => r.Puzzle.ID == puzzleId &&
                submission.SubmissionText == r.SubmittedText)
                                  .FirstOrDefaultAsync();

            Submissions.Add(submission);

            // Update puzzle state if submission was correct
            if (submission.Response != null && submission.Response.IsSolution)
            {
                await PuzzleStateHelper.SetSolveStateAsync(_context,
                                                           Event,
                                                           submission.Puzzle,
                                                           submission.Team,
                                                           submission.TimeSubmitted);

                AnswerToken = submission.SubmissionText;
            }
            else if (submission.Response == null)
            {
                // We also determine if the puzzle should be set to email-only mode.
                if (IsPuzzleSubmissionLimitReached(
                        Event,
                        Submissions,
                        PuzzleState))
                {
                    await PuzzleStateHelper.SetEmailOnlyModeAsync(_context,
                                                                  Event,
                                                                  submission.Puzzle,
                                                                  submission.Team,
                                                                  true);

                    var authors = await _context.PuzzleAuthors.Where((pa) => pa.Puzzle == submission.Puzzle).Select((pa) => pa.Author.Email).ToListAsync();

                    MailHelper.Singleton.SendPlaintextBcc(authors,
                                                          $"{Event.Name}: Team {submission.Team.Name} is in email mode for {submission.Puzzle.Name}",
                                                          "");
                }
                else
                {
                    // If the submission was incorrect and not a partial solution,
                    // we will do the lockout computations now.
                    DateTime?lockoutExpiryTime = ComputeLockoutExpiryTime(
                        Event,
                        Submissions,
                        PuzzleState);

                    if (lockoutExpiryTime != null)
                    {
                        await PuzzleStateHelper.SetLockoutExpiryTimeAsync(_context,
                                                                          Event,
                                                                          submission.Puzzle,
                                                                          submission.Team,
                                                                          lockoutExpiryTime);
                    }
                }
            }

            _context.Submissions.Add(submission);
            await _context.SaveChangesAsync();

            SubmissionViews.Add(new SubmissionView()
            {
                Submission    = submission,
                Response      = submission.Response,
                SubmitterName = LoggedInUser.Name
            });

            return(Page());
        }
Exemple #14
0
        public ActionResult Submit()
        {
            // Variables.
            var tempGuid = default(Guid);
            var keys     = Request.Form.AllKeys;
            var fileKeys = Request.Files.AllKeys;
            var formId   = Guid.Parse(Request["FormId"]);
            var pageId   = NumberUtility.AttemptParseInt(Request["PageId"]);
            IPublishedContent pageNode = pageId.HasValue ? Umbraco.Content(pageId.Value) : null;
            var pageUrl  = pageNode?.Url;
            var pageName = pageNode?.Name;


            // Get values.
            var values = keys
                         .Where(x => Guid.TryParse(x, out tempGuid))
                         .Select(x =>
            {
                var fieldValue = Request.Form.GetValues(x);
                return(new FieldSubmission
                {
                    FieldId = Guid.Parse(x),
                    FieldValues = fieldValue
                });
            })
                         .ToList();

            // Get file values.
            var fileValues = fileKeys
                             .Where(x => Guid.TryParse(x, out tempGuid))
                             .Select(x =>
            {
                // Variables.
                var fileValue = Request.Files.Get(x);


                // Extract file data: http://stackoverflow.com/a/16030326/2052963
                var reader   = new BinaryReader(fileValue.InputStream);
                var fileData = reader.ReadBytes((int)fileValue.InputStream.Length);
                var filename = fileValue.FileName;


                // Return file field submission.
                return(new FileFieldSubmission()
                {
                    FieldId = Guid.Parse(x),
                    FileData = fileData,
                    FileName = filename
                });
            })
                             .ToList();


            // Payload.
            var payload = new[]
            {
                new PayloadSubmission()
                {
                    Name  = "URL",
                    Value = pageUrl
                },
                new PayloadSubmission()
                {
                    Name  = "Page Name",
                    Value = pageName
                }
            }.Where(x => !string.IsNullOrWhiteSpace(x.Value));


            // Submit form.
            var context = new FormRequestContext()
            {
                CurrentPage    = pageNode,
                HttpContext    = HttpContext,
                Services       = Services,
                UmbracoContext = UmbracoContext,
                UmbracoHelper  = Umbraco
            };
            var options = new SubmissionOptions()
            {
                Validate = Config.EnableServerSideValidation
            };

            var result = new Submissions(Forms, Validations, Logger).SubmitForm(formId, values, fileValues, payload, options, context);

            // Return result.
            return(Json(new
            {
                Success = result.Success
            }));
        }