public void SubmitSerial_OnlyTwoSubmissionsPerSerialAllowed() { // Arrange TestDBCleanup(); HomeController controller = new HomeController(); SubmissionModel submissionModel = new SubmissionModel { FirstName = "Test", LastName = "Test", EmailAddress = "*****@*****.**", SerialNumber = Guid.Parse("11111111-1111-1111-1111-111111111111"), IsOldEnough = true }; // Act string result1 = new JavaScriptSerializer().Serialize(controller.SubmitSerial(submissionModel).Data); string result2 = new JavaScriptSerializer().Serialize(controller.SubmitSerial(submissionModel).Data); string result3 = new JavaScriptSerializer().Serialize(controller.SubmitSerial(submissionModel).Data); //Assert Assert.AreEqual("\"Submission Successful!\"", result1); Assert.AreEqual("\"Submission Successful!\"", result2); Assert.AreEqual("\"This Serial Number has already been redeemed twice.\"", result3); TestDBCleanup(); }
public SubmissionDTO Map(SubmissionModel submissionModel) { if (submissionModel == null) { return(null); } var student = _iStudentService.GetByUsername(submissionModel.Student.Username); var Assignment = _iAssignmentService.GetById(submissionModel.Assignment.Id); var studentDTO = _iStudentMapper.Map(submissionModel.Student); var assignDTO = _iAssignmentMapper.Map(submissionModel.Assignment); return(new SubmissionDTO { Id = submissionModel.Id, StudentId = studentDTO.Id, Student = studentDTO, AssignmentId = assignDTO.Id, Assignment = assignDTO, Link = submissionModel.Link, Remark = submissionModel.Remark, Grade = submissionModel.Grade }); }
public IActionResult SendEmail(SubmissionModel model) { if (!ModelState.IsValid || string.IsNullOrEmpty(model.Recipient)) { return(BadRequest()); } var mailHelper = new MailHelper(_smtpClient); var subject = "Digital Portfolio - Contact form"; var body = new StringBuilder(); body.Append(string.Format($"<p><strong>Name: </strong>{model.Name}</p>")); body.Append(string.Format($"<p><strong>Email: </strong>{model.Email}</p>")); body.Append(string.Format("</hr>")); body.Append(string.Format("<p><strong>Meddelande:</strong></p>")); body.Append(string.Format($"<p>{model.Message}</p>")); var success = mailHelper.SendMail(subject, body.ToString(), "*****@*****.**", model.Recipient); if (success) { return(Ok()); } else { return(StatusCode(500)); } }
public async Task <object> Add(SubmissionInputModel submissionInputModel) { var assignmentModel = await _context.Assignment.FindAsync(submissionInputModel.AssignmentId); if (assignmentModel == null) { return("bad request"); } var model = new SubmissionModel { AssignmentId = submissionInputModel.AssignmentId, StudentId = submissionInputModel.StudentId, Link = submissionInputModel.Link, Comment = submissionInputModel.Comment, Grade = 0, SubmissionDate = DateTime.Now }; _context.Submission.Add(model); try { await _context.SaveChangesAsync(); } catch (Exception) { return("bad request"); } return(model); }
internal Submission(Api api, SubmissionModel model) { Api = api; AssignmentId = model.AssignmentId; Assignment = model.Assignment.ConvertIfNotNull(m => new Assignment(api, m)); Course = model.Course.ConvertIfNotNull(c => new Course(api, c)); Attempt = model.Attempt; Body = model.Body; Grade = model.Grade; GradeMatchesCurrentSubmission = model.GradeMatchesCurrentSubmission; HtmlUrl = model.HtmlUrl; PreviewUrl = model.PreviewUrl; Score = model.Score; SubmissionComments = model.SubmissionComments.ConvertIfNotNull(ie => ie.Select(m => new SubmissionComment(api, m))); SubmissionType = model.SubmissionType; SubmittedAt = model.SubmittedAt; Url = model.Url; UserId = model.UserId; GraderId = model.GraderId; GradedAt = model.GradedAt; User = model.User.ConvertIfNotNull(m => new User(api, m)); Late = model.Late; AssignmentVisible = model.AssignmentVisible; Excused = model.Excused; Missing = model.Missing; LatePolicyStatus = model.LatePolicyStatus; PointsDeducted = model.PointsDeducted; SecondsLate = model.SecondsLate; WorkflowState = model.WorkflowState; ExtraAttempts = model.ExtraAttempts; AnonymousId = model.AnonymousId; }
public async Task <ActionResult> SubmissionEdit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } SubmissionModel SubmissionToUpdate = null; if (ModelState.IsValid) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(Baseurl); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string auth = Session["UserEmail"].ToString() + ":" + Session["UserPassword"]; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", auth); HttpRequestMessage Req = new HttpRequestMessage(HttpMethod.Get, Baseurl + "api/Submission/" + id); var response = await client.GetAsync(Req.RequestUri); var jsonString = await response.Content.ReadAsStringAsync(); SubmissionToUpdate = JsonConvert.DeserializeObject <SubmissionModel>(jsonString); } } if (TryUpdateModel(SubmissionToUpdate, "", new string[] { "Grade" })) { try { using (var client = new HttpClient()) { client.BaseAddress = new Uri(Baseurl); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); string auth = Session["UserEmail"].ToString() + ":" + Session["UserPassword"]; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", auth); HttpRequestMessage Req = new HttpRequestMessage(HttpMethod.Put, Baseurl + "api/Submission"); Req.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(SubmissionToUpdate), Encoding.ASCII, "application/json"); var response = await client.PutAsync(Req.RequestUri, Req.Content); if (response.IsSuccessStatusCode) { return(RedirectToAction("SubmissionsIndex")); } else { ModelState.AddModelError("", "Unable to save changes. Try again"); } } } catch (DataException /* dex */) { //Log the error (uncomment dex variable name and add a line here to write a log. ModelState.AddModelError("", "Unable to save changes. Try again"); } } return(View(SubmissionToUpdate)); }
public ActionResult ViewSubmission(int SubmissionID) { DBController db = new DBController(); DataTable dt = db.GetSubmissionByID(SubmissionID); string UserName = Session["UserName"].ToString(); List <SubmissionModel> Submissions = new List <SubmissionModel>(); for (int i = 0; i < dt.Rows.Count; ++i) { SubmissionModel Submission = new SubmissionModel(); Submission.SubmissionID = Convert.ToInt32(dt.Rows[i]["SubmissionID"]); DataTable ContestantName = db.SelectUserNameByID(Convert.ToInt32(dt.Rows[i]["ContestantID"])); ViewBag.ContestantName = UserName; Submission.SubmissionVerdict = Convert.ToString(dt.Rows[i]["SubmissionVerdict"]); Submission.SubmissionMemory = Convert.ToInt32(dt.Rows[i]["SubmissionMemory"]); Submission.SubmissionDate = Convert.ToDateTime(dt.Rows[i]["SubmissionDate"]); Submission.SubmissionTime = Convert.ToInt32(dt.Rows[i]["SubmissionTime"]); Submission.SubmissionLang = Convert.ToString(dt.Rows[i]["SubmissionLang"]); Submission.ProblemID = Convert.ToString(dt.Rows[i]["ProblemID"]); ViewBag.ProblemName = db.GetProblemNameByID(Submission.ProblemID); Submissions.Add(Submission); } return(View(Submissions)); }
public static string CreateSubmission(string firstName, string lastName, string emailAddress, Guid serialNumber) { if (!CheckSerialNumberExists(serialNumber)) { return("That is not a valid Serial Number."); } else if (!CheckSerialNumberSubmissionCount(serialNumber)) { return("This Serial Number has already been redeemed twice."); } SubmissionModel submissionData = new SubmissionModel { FirstName = firstName, LastName = lastName, EmailAddress = emailAddress, SerialNumber = serialNumber }; string sqlQuery = @"INSERT INTO dbo.Submission (FirstName, LastName, EmailAddress, SerialNumber) VALUES (@FirstName, @LastName, @EmailAddress, @SerialNumber);"; int rowsInserted = DBDataAccess.SaveData <SubmissionModel>(sqlQuery, submissionData); return(rowsInserted == 1 ? "Submission Successful!" : "There seems to be a problem, try submitting again."); }
public ActionResult Index(SubmissionModel model) { if (ModelState.IsValid) { var uploadPath = Server.MapPath("~/App_Data/Uploads"); string uploadedFilePath = Path.Combine(uploadPath, model.FileName); Image img = Image.FromFile(uploadedFilePath); var photo = new Photo { Title = model.Title, Description = model.Description, FileName = model.FileName, Width = img.Width, Height = img.Height, UserId = CurrentUser.Id }; var photoId = _photoManager.CreatePhoto(photo); _tagManager.CreateTag(model.Tags, photoId); return(RedirectToAction("MyPhotos", "Gallery")); } return(View(model)); }
public ActionResult Search(SearchModel model) { string query = "Select Name , Gender, salary , DepartmentName from tblEmployee1 join tblDepartment on tblEmployee1.DepartmentId = tblDepartment.ID where tblEmployee1.ID = " + model.ID; var list = new List <SubmissionModel>(); if (null != model.ID) { using (SqlConnection sqlcon = new SqlConnection(connectionString)) { sqlcon.Open(); SqlCommand command = new SqlCommand(query, sqlcon); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { var ele = new SubmissionModel { Name = reader[0].ToString(), Gender = reader[1].ToString(), Salary = Convert.ToInt32(reader[2]), Department = reader[3].ToString() }; list.Add(ele); } } } if (list.Count == 0) { ViewBag.Message = string.Format("Sorry, We Don't have any record of this ID : {0}", model.ID); } return(View("_SearchView", list)); }
private SubmissionsModel GetSubmissionsModel(IEnumerable <string> validationMessages = null) { return(new SubmissionsModel(repository.All().Select(x => SubmissionModel.BuildFromSubmission(x))) { ValidationMessages = validationMessages }); }
public ActionResult Details(string id) { if (id == null) { return(RedirectToAction("Submission", "Home")); } string query = "select tblEmployee1.ID , Name , Gender, DepartmentName, salary from tblEmployee1 JOIN tblDepartment on tblEmployee1.DepartmentId = tblDepartment.ID where tblEmployee.ID = " + id; var model = new SubmissionModel(); var list = new SubmissionModel(); using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand Commnad = new SqlCommand(query, connection); SqlDataReader dr = Commnad.ExecuteReader(); while (dr.Read()) { var ele = new SubmissionModel { ID = Convert.ToInt16(dr[0]), Name = dr[1].ToString(), Gender = dr[2].ToString(), Department = dr[3].ToString(), Salary = Convert.ToInt32(dr[4]) }; list = ele; } } return(View("_SearchView", list)); }
public void SubmitActionWhenParticipantSendsAValidSubmitShouldReturnJson() { var contest = this.CreateAndSaveContest("test contest", this.ActiveContestNoPasswordOptions, this.ActiveContestNoPasswordOptions); var problem = new Problem { Name = "test problem" }; var submissionType = new SubmissionType { Name = "test submission type" }; contest.Problems.Add(problem); contest.SubmissionTypes.Add(submissionType); contest.Participants.Add(new Participant(contest.Id, this.FakeUserProfile.Id, this.IsCompete)); this.EmptyOjsData.SaveChanges(); var submission = new SubmissionModel { Content = "test content", ProblemId = problem.Id, SubmissionTypeId = submissionType.Id }; var result = this.CompeteController.Submit(submission, this.IsCompete) as JsonResult; var receivedContestId = (int)result.Data; Assert.AreEqual(receivedContestId, contest.Id); }
public ActionResult Submission(SubmissionModel model) { if (!ModelState.IsValid) { return(RedirectToAction("NewEmployee", "Home")); } string query = "Insert into tblEmployee1(ID, Name, Gender, Salary, DepartmentId )" + "Values (@ID , @Name, @Gender, @Salary, @DepartmentId)"; using (SqlConnection con = new SqlConnection(connectionString)) { using (SqlCommand cmd = new SqlCommand(query, con)) { cmd.Parameters.AddWithValue("@ID", model.ID); cmd.Parameters.AddWithValue("@Name", model.Name); cmd.Parameters.AddWithValue("@Gender", model.Gender); cmd.Parameters.AddWithValue("@Salary", model.Salary); cmd.Parameters.AddWithValue("@DepartmentId", Convert.ToInt32(model.Department)); try { con.Open(); cmd.ExecuteNonQuery(); } catch (Exception ex) { return(RedirectToAction("Index", ex.Message)); } } } return(RedirectToAction("Submission", "Home")); }
public void SubmitActionWhenUserIsNotRegisteredToParticipateShouldThrowException() { var contest = this.CreateAndSaveContest("someContest", this.ActiveContestNoPasswordOptions, this.ActiveContestNoPasswordOptions); var problem = new Problem { Name = "test problem" }; var submissionType = new SubmissionType { Name = "test submission type" }; contest.Problems.Add(problem); contest.SubmissionTypes.Add(submissionType); this.EmptyOjsData.SaveChanges(); var submission = new SubmissionModel { Content = "test submission", ProblemId = problem.Id, SubmissionTypeId = submissionType.Id }; try { var result = this.CompeteController.Submit(submission, this.IsCompete); Assert.Fail("An exception was expected when a user is trying to submit for a contest that he isn't registered for."); } catch (HttpException ex) { Assert.AreEqual((int)HttpStatusCode.Unauthorized, ex.GetHttpCode()); } }
public SubmissionModel Map(SubmissionAPIModel submissionAPIModel) { if (submissionAPIModel == null) { return(null); } var studentModel = _iStudentAPIMapper.Map(submissionAPIModel.Student); var assignModel = _iAssignmentAPIMapper.Map(submissionAPIModel.Assignment); var att = new SubmissionModel(); att.Assignment = assignModel; att.Grade = submissionAPIModel.Grade; att.Link = submissionAPIModel.Link; att.Remark = submissionAPIModel.Remark; att.Student = studentModel; return(att); //return new SubmissionModel //{ // SubmissionStatus = Submission, // Student = studentModel, // Assignment = labModel //}; //SubmissionModel SubmissionModel = new SubmissionModel(Submission, studentModel, labModel); //return SubmissionModel; }
public IActionResult Create(SubmissionModel model) { // Authenticate users if (!this.User.IsAuthenticated) { return(this.RedirectToLogin()); } // Validate model if (!this.IsValidModel(model)) { this.ShowError(SubmissionError); return(this.View()); } // Random processing with 70% chance for failure var randomValue = this.random.Next(0, 100); // Create in db this.submissionService.Create( model.Code, model.ContestId, this.Profile.Id, randomValue > 70 ? BuildType.Success : BuildType.Failed); return(this.RedirectToSubmissions()); }
public IActionResult Create(SubmissionModel model) { if (!this.User.IsAuthenticated) { return(this.RedirectToLogin()); } if (!this.IsValidModel(model)) { this.ShowError(ErrorConstants.SubmissionCodeError); return(this.View()); } BuildResultType type = BuildResultType.BuildFailed; Random random = new Random(); int randomType = random.Next(0, 101); if (randomType > 70) { type = BuildResultType.BuildSuccess; } this.submissionService.Create(model.Code, model.Contest, this.Profile.Id, type); return(this.Redirect("/submissions/all")); }
public void AddSubmission(SubmissionModel submission) { var assignment = assignmentRepository.GetById(submission.Assignment.Id); if (assignment.DueDate < DateTime.Now) { throw new Exception("Deadline has passed for this assignment"); } if (assignment == null) { throw new Exception("the assignmwnt does not exist"); } if (userRepository.GetById(submission.Student.Id) == null) { throw new Exception("the student does not exist"); } var newSubmission = Mapper.Map <SubmissionDto>(submission); newSubmission.StudentId = submission.Student.Id; newSubmission.AssignmentId = submission.Assignment.Id; var existing = submissionRepository.GetSpecificSubmission(newSubmission.Student, newSubmission.Assignment); if (existing != null) { throw new Exception("Assignment already submited"); } submissionRepository.Add(newSubmission); submissionRepository.Save(); }
public void AddSubmission(SubmissionModel SubmissionModel) { var submission = _iSubmissionMapper.Map(SubmissionModel); submission.Grade = 0; _iSubmissionRepository.Add(submission); _iSubmissionRepository.SaveChanges(); }
public static SubmissionModel Trim(this SubmissionModel submission) { if (submission == null) { return(null); } submission.Assignment = submission.Assignment.Trim(); submission.Student = submission.Student.Trim(); return(submission); }
public SubmissionTableEntity Add(string urlKey, string oauthRefreshToken, SubmissionModel model) { _table.CreateIfNotExists(); var submission = new SubmissionTableEntity(urlKey, oauthRefreshToken, model); var insertOperation = TableOperation.Insert(submission); _table.Execute(insertOperation); return(submission); }
public SubmissionModelAPI Map(SubmissionModel sub) { return(new SubmissionModelAPI() { AssignmentID = sub.AssignmentID, StudentID = sub.StudentID, GitLink = sub.GitLink, Grade = sub.Grade, Notes = sub.Notes }); }
public void DeleteSubmission(SubmissionModel submission) { var existimg = submissionRepository.GetById(submission.Id); if (existimg == null) { throw new Exception("the submission does not exist"); } submissionRepository.Delete(existimg); submissionRepository.Save(); }
public JsonResult SubmitSerial(SubmissionModel submissionModel) { if (ModelState.IsValid) { string creationMessage = CreateSubmission(submissionModel.FirstName, submissionModel.LastName, submissionModel.EmailAddress, submissionModel.SerialNumber); return(Json(creationMessage)); } return(Json("Invalid form input.")); }
public async void update(SubmissionModel sm) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(Baseurl); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpRequestMessage Req = new HttpRequestMessage(HttpMethod.Put, Baseurl + "api/Submission/Edit"); Req.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(sm), Encoding.ASCII, "application/json"); var Res = await client.PutAsync(Req.RequestUri, Req.Content); } }
public ActionResult Submit(SubmissionModel participantSubmission, bool official) { var problem = this.Data.Problems.All().FirstOrDefault(x => x.Id == participantSubmission.ProblemId); if (problem == null) { throw new HttpException((int)HttpStatusCode.Unauthorized, Resource.ContestsGeneral.Problem_not_found); } if (official && !this.ValidateContestIp(this.Request.UserHostAddress, problem.ContestId)) { return(this.RedirectToAction("NewContestIp", new { id = problem.ContestId })); } var participant = this.Data.Participants.GetWithContest(problem.ContestId, this.UserProfile.Id, official); if (participant == null) { throw new HttpException((int)HttpStatusCode.Unauthorized, Resource.ContestsGeneral.User_is_not_registered_for_exam); } this.ValidateContest(participant.Contest, official); ValidateSubmissionType(participantSubmission.SubmissionTypeId, participant.Contest); if (this.Data.Submissions.HasSubmissionTimeLimitPassedForParticipant(participant.Id, participant.Contest.LimitBetweenSubmissions)) { throw new HttpException((int)HttpStatusCode.ServiceUnavailable, Resource.ContestsGeneral.Submission_was_sent_too_soon); } if (problem.SourceCodeSizeLimit < participantSubmission.Content.Length) { throw new HttpException((int)HttpStatusCode.BadRequest, Resource.ContestsGeneral.Submission_too_long); } if (!this.ModelState.IsValid) { throw new HttpException((int)HttpStatusCode.BadRequest, Resource.ContestsGeneral.Invalid_request); } this.Data.Submissions.Add(new Submission { ContentAsString = participantSubmission.Content, ProblemId = participantSubmission.ProblemId, SubmissionTypeId = participantSubmission.SubmissionTypeId, ParticipantId = participant.Id, IpAddress = this.Request.UserHostAddress, }); this.Data.SaveChanges(); return(this.Json(participantSubmission.ProblemId)); }
public SubmissionModel map(Submission submission) { if (submission == null) { return(null); } var newSubmission = new SubmissionModel() { ID = submission.ID, AssignmentID = submission.AssignmentID, GitLink = submission.GitLink, Grade = submission.Grade, Note = submission.Note, StudentID = submission.StudentID }; return(newSubmission); }
public ActionResult SubmissionUpdate(SubmissionModel model, bool print) { int submissionid = Int32.Parse(Request["submissionid"]); int formid = Int32.Parse(Request["formid"]); //get form fields (isforadminonly == true) var formfields = _formService.GetFormFieldsNoPaging(formid).Where(f => f.IsForAdminOnly == true).ToList(); //get fields values from request foreach (var field in formfields) { string fieldvalue = Request["field" + field.Id]; int valueid = Int32.Parse(Request["valueid_" + field.Id]); if (valueid > 0) { //update field value var submissionvalue = _formService.GetSubmissionFieldValue(submissionid, field.Id); submissionvalue.FieldValue = fieldvalue; _formService.UpdateFieldValue(submissionvalue); } else { //insert field value var submissionvalue = new FormSubmissionsValuesRecord(); submissionvalue.FieldValue = fieldvalue; submissionvalue.FormFieldId = field.Id; submissionvalue.SubmissionId = submissionid; _formService.SaveFieldValue(submissionvalue); } } if (print) { var filepath = _printFormService.CreateFormPdf(submissionid); var filename = Path.GetFileName(filepath); byte[] filedata = System.IO.File.ReadAllBytes(filepath); string contentType = MimeMapping.GetMimeMapping(filepath); var cd = new System.Net.Mime.ContentDisposition { FileName = filename, Inline = true, }; Response.Headers.Add("Content-Disposition", cd.ToString()); return(File(filedata, contentType)); } return(View("Submissions")); }
public async Task WhenPostIsCalledThenSubmissionIsCalledWithCorrectModel() { var model = _fixture.Create <ProfileDto>(); SubmissionModel submissionModel = null; await _submission .SubmitAsync(Arg.Do <SubmissionModel>(m => submissionModel = m)); await _profileController.Post(model); submissionModel .Should() .BeEquivalentTo(model); }