public EditChallengeViewModel Save(EditChallengeViewModel model)
        {
            Contract.NotNull <ArgumentNullException>(model);

            ValidateChallenge(model);

            Challenge challenge;

            if (model.IsNew)
            {
                challenge = new Challenge
                {
                    TimeCreated = DateTime.Now
                };
            }
            else
            {
                challenge = unitOfWork.Get <Challenge>(model.Id.GetValueOrDefault());
            }

            MapModelToChallenge(challenge, model);

            unitOfWork.InsertOrUpdate(challenge);
            unitOfWork.Commit();

            return(mapper.Map <EditChallengeViewModel>(challenge));
        }
        public void Map(Challenge challenge, EditChallengeViewModel model)
        {
            challenge.SolutionSourceCode = model.SourceCode;

            foreach (var removedTestCase in challenge.TestCases.ToList())
            {
                unitOfWork.Delete(removedTestCase);
            }

            foreach (var testCase in model.TestCases)
            {
                var testCaseEntity = new TestCase
                {
                    Id       = testCase.Id,
                    IsPublic = testCase.IsPublic
                };

                var parameters = new List <CodeParameter>();
                parameters.AddRange(testCase.InputParameters.Select(p => new CodeParameter
                {
                    Type  = CodeParameterType.Input,
                    Value = p
                }));
                parameters.AddRange(testCase.OutputParameters.Select(p => new CodeParameter
                {
                    Type  = CodeParameterType.Output,
                    Value = p
                }));
                testCaseEntity.CodeParameters = parameters;

                challenge.TestCases.Add(testCaseEntity);
            }
        }
Example #3
0
        public JsonResult SaveChallenge([FromBody] EditChallengeViewModel challenge)
        {
            challenge.AuthorId = userManager.Value.GetUserId(User).ToGuid();

            var model = challengesService.SaveChallenge(challenge);

            return(Json(model));
        }
        private void ValidateTestCase(EditChallengeViewModel model, TestCaseViewModel testCase)
        {
            var executionRequest = codeExecutionRequestBuilder.Build((Section)model.Section, model.SourceCode,
                                                                     testCase.InputParameters);

            var executionResult = codeExecutor.Execute(executionRequest);

            Contract.Assert <InvalidOperationException>(executionResult.IsValid, executionResult.ErrorMessage);
            Contract.Assert <InvalidOperationException>(executionResult.Output.SequenceEqual(testCase.OutputParameters), string.Join(", ", executionResult.Output));
        }
 private void ValidateChallenge(EditChallengeViewModel model)
 {
     if (model.ChallengeType == ChallengeType.CodeAnswered)
     {
         foreach (var testCase in model.TestCases)
         {
             ValidateTestCase(model, testCase);
         }
     }
 }
 private void MapCommonProperties(Challenge challenge, EditChallengeViewModel model)
 {
     challenge.AuthorId      = model.AuthorId;
     challenge.ChallengeType = (Data.Challenges.Enums.ChallengeType)model.ChallengeType;
     challenge.PreviewText   = model.PreviewText;
     challenge.Condition     = model.Condition;
     challenge.Difficulty    = model.Difficulty;
     challenge.Language      = model.Language;
     challenge.Section       = (Section)model.Section;
     challenge.Title         = model.Title;
     MapTags(challenge, model);
 }
        private void MapTags(Challenge challenge, EditChallengeViewModel model)
        {
            var removedTags = challenge.Tags.Where(tag => !model.Tags.Any(x => x.Equals(tag.Value)));

            foreach (var removedTag in removedTags)
            {
                tagService.Untag(challenge, removedTag.Value);
            }

            foreach (var tag in model.Tags)
            {
                tagService.Tag(challenge, tag);
            }
        }
        public IActionResult EditTask(int id)
        {
            var task = _context.Challenges.FirstOrDefault(m => m.Id == id);

            if (task == null)
            {
                return(BadRequest($"Task mit der id {id} kann nicht gefunden werden."));
            }
            var viewModel = new EditChallengeViewModel();

            viewModel.Id            = task.Id;
            viewModel.ChallengeText = task.ChallengeText;
            viewModel.Solution      = task.Solution;
            viewModel.LevelNumber   = task.LevelNumber;

            return(View(viewModel));
        }
        public IActionResult SaveEditedTask(EditChallengeViewModel viewModel)
        {
            if (viewModel is null)
            {
                throw new ArgumentNullException(nameof(viewModel));
            }
            var changedLevel    = _context.Levels.FirstOrDefault(m => m.LevelNumber == viewModel.LevelNumber);
            var challangeFromDb = _context.Challenges.FirstOrDefault(m => m.Id == viewModel.Id);

            challangeFromDb.Id            = viewModel.Id;
            challangeFromDb.LevelId       = changedLevel.Id;
            challangeFromDb.ChallengeText = viewModel.ChallengeText;
            challangeFromDb.Solution      = viewModel.Solution;

            _context.SaveChanges();

            return(RedirectToAction(nameof(ShowTasks)));
        }
 public EditChallengeViewModel SaveChallenge(EditChallengeViewModel challenge)
 {
     return(saveChallengeHandler.Value.Save(challenge));
 }
 public void Map(Challenge challenge, EditChallengeViewModel model)
 {
     throw new System.NotImplementedException();
 }
        private void MapModelToChallenge(Challenge challenge, EditChallengeViewModel model)
        {
            MapCommonProperties(challenge, model);

            challengeMappers[model.ChallengeType].Map(challenge, model);
        }
Example #13
0
        public async Task <IActionResult> UpdateChallenge(EditChallengeViewModel inputModel)
        {
            // We only care about updating the challenge values
            var challenge = new ACMT.ChallengeDetails
            {
                Description = inputModel.Description,
                Id          = inputModel.Id,
                Name        = inputModel.Name,
                IsPublic    = inputModel.IsPublic,
                Questions   = inputModel.ChallengeQuestions == null ? new List <ACMQ.QuestionLite>() :
                              inputModel.ChallengeQuestions?
                              .Select(p => new ACMQ.QuestionLite()
                {
                    AssociatedQuestionId = p.AssociatedQuestionId,
                    Description          = p.Description,
                    Difficulty           = p.Difficulty,
                    Id             = p.Id,
                    Index          = p.Index,
                    Name           = p.Name,
                    NextQuestionId = p.NextQuestionId
                }).ToList(),
                AzureServiceCategory = inputModel.AzureServiceCategory,
                WelcomeMessage       = inputModel.WelcomeMessage,
                Duration             = inputModel.Duration,
                PrereqLinks          = inputModel.PrereqLinks
            };

            var updateResult = await challengeProvider.AddItemAsync(challenge);

            // Check the IsPublic property. Depending on the change, we need to add or remove the challenge from the aggregate
            if (inputModel.IsPublic != inputModel.OldIsPublic)
            {
                // We only have one, so just get via the Partition search
                var aggregatesReponse = await aggregateProvider.GetItemAsync("00000000-0000-0000-0000-000000000000");

                if (aggregatesReponse.Item1.Success)
                {
                    var agg =
                        aggregatesReponse.Item2 ??
                        new ACMA.Aggregate()
                    {
                        Id = "00000000-0000-0000-0000-000000000000",
                        ChallengeTotals = new ACMA.ChallengeAggregateTotals()
                        {
                            TotalPublic = 0
                        }
                    };

                    agg.ChallengeTotals.TotalPublic += inputModel.IsPublic ? 1 : agg.ChallengeTotals.TotalPublic > 0 ? -1 : 0;
                    await aggregateProvider.AddItemAsync(agg);
                }
                else
                {
                    // Doesn't exists
                    var agg = new ACMA.Aggregate()
                    {
                        Id = "00000000-0000-0000-0000-000000000000",
                        ChallengeTotals = new ACMA.ChallengeAggregateTotals()
                        {
                            TotalPublic = 0
                        }
                    };

                    agg.ChallengeTotals.TotalPublic += inputModel.IsPublic ? 1 : agg.ChallengeTotals.TotalPublic > 0 ? -1 : 0;
                    await aggregateProvider.AddItemAsync(agg);
                }
            }

            if (updateResult.Success)
            {
                return(Ok());
            }
            else
            {
                return(StatusCode(500));
            }
        }
Example #14
0
        public async Task <IActionResult> AddAssignedQuestion(EditChallengeViewModel inputModel)
        {
            if (ModelState.IsValid)
            {
                // Translate the view model to our backend model
                var assignedQuestion = new ACMQ.AssignedQuestion
                {
                    Answers = inputModel.QuestionToAdd.Answers
                              .Select(p => new ACMQ.AssignedQuestion.AnswerList
                    {
                        AnswerParameters = p.AnswerParameters?.Select(a => new ACMQ.AssignedQuestion.AnswerParameterItem()
                        {
                            ErrorMessage = a.ErrorMessage, Key = a.Key, Value = a.Value ?? (inputModel.QuestionToAdd.QuestionType == "MultiChoice" ? "false" : "")
                        }).ToList(),
                        AssociatedQuestionId = p.AssociatedQuestionId,
                        ResponseType         = p.ResponseType
                    }
                                      ).ToList(),
                    QuestionType         = inputModel.QuestionToAdd.QuestionType,
                    AssociatedQuestionId = inputModel.QuestionToAdd.AssociatedQuestionId,
                    Description          = inputModel.QuestionToAdd.Description,
                    Difficulty           = inputModel.QuestionToAdd.Difficulty,
                    Name                  = inputModel.QuestionToAdd.Name,
                    QuestionId            = string.IsNullOrWhiteSpace(inputModel.QuestionToAdd.Id) ? Guid.NewGuid().ToString() : inputModel.QuestionToAdd.Id,
                    TargettedAzureService = inputModel.QuestionToAdd.TargettedAzureService,
                    Text                  = inputModel.QuestionToAdd.Text,
                    TextParameters        = inputModel.QuestionToAdd.TextParameters?.ToDictionary(p => p.Key, p => p.Value) ?? new Dictionary <string, string>(),
                    ChallengeId           = inputModel.QuestionToAdd.ChallengeId,
                    Uris                  = inputModel.QuestionToAdd.Uris?
                                            .Select(p => new ACMQ.AssignedQuestion.UriList
                    {
                        CallType                  = p.CallType,
                        Id                        = p.Id,
                        Uri                       = p.Uri,
                        UriParameters             = p.UriParameters?.ToDictionary(q => q.Key, q => q.Value) ?? new Dictionary <string, string>(),
                        RequiresContributorAccess = p.RequiresContributorAccess
                    }
                                                    ).ToList(),
                    Justification = inputModel.QuestionToAdd.Justification,
                    UsefulLinks   = inputModel.QuestionToAdd.UsefulLinks ?? new List <string>()
                };

                List <ACMQ.QuestionLite> challengeQuestions = null;
                if (inputModel.ChallengeQuestions != null)
                {
                    challengeQuestions = inputModel.ChallengeQuestions
                                         .Select(p => new ACMQ.QuestionLite
                    {
                        Description          = p.Description,
                        Difficulty           = p.Difficulty,
                        Id                   = p.Id,
                        Index                = p.Index,
                        Name                 = p.Name,
                        AssociatedQuestionId = p.AssociatedQuestionId,
                        NextQuestionId       = p.NextQuestionId
                    }).ToList();
                }
                else
                {
                    challengeQuestions = new List <ACMQ.QuestionLite>();
                }

                // Get the existing challenge details
                var challenge = new ACMT.ChallengeDetails()
                {
                    Description          = inputModel.Description,
                    Id                   = inputModel.Id,
                    Name                 = inputModel.Name,
                    Questions            = challengeQuestions,
                    AzureServiceCategory = inputModel.AzureServiceCategory,
                    WelcomeMessage       = inputModel.WelcomeMessage,
                    Duration             = inputModel.Duration,
                    PrereqLinks          = inputModel.PrereqLinks
                };

                // Check if this is an update to an existing challenge question
                if (challenge.Questions.Exists(p => p.Id == assignedQuestion.QuestionId))
                {
                    // We only need to update the assigned question, not the challenge
                    var updateQuestionResult = await assignedQuestionProvider.AddItemAsync(assignedQuestion);

                    if (!updateQuestionResult.Success)
                    {
                        return(StatusCode(500));
                    }
                }
                else
                {
                    // Create a new Challenge Question
                    var newChallengeQuestion = new ACMQ.QuestionLite
                    {
                        Name                 = assignedQuestion.Name,
                        Description          = assignedQuestion.Description,
                        Difficulty           = assignedQuestion.Difficulty,
                        Id                   = assignedQuestion.QuestionId,
                        AssociatedQuestionId = assignedQuestion.AssociatedQuestionId,
                        Index                = challenge.Questions.Count()
                    };
                    // Assign the next question value of the last question in the challenge to this one
                    if (challenge.Questions.Count > 0)
                    {
                        challenge.Questions[challenge.Questions.Count - 1].NextQuestionId = assignedQuestion.QuestionId;
                    }
                    challenge.Questions.Add(newChallengeQuestion);

                    // Get the global parameters for the challenge
                    var globalParamsResponse = await challengeParameterProvider.GetItemAsync(assignedQuestion.ChallengeId);

                    var globalParams = globalParamsResponse.Item2;

                    // Check if the parameter is global and it exists in the global parameters list
                    // If yes, increment the count. If no, add it
                    foreach (var parameter in assignedQuestion.TextParameters.ToList())
                    {
                        if (parameter.Key.StartsWith("Global."))
                        {
                            var globalParameter = globalParams?.Parameters?.Where(p => p.Key == parameter.Key.Replace("Global.", "")).FirstOrDefault();

                            if (globalParameter == null)
                            {
                                if (globalParams == null)
                                {
                                    globalParams = new ACMP.GlobalChallengeParameters()
                                    {
                                        ChallengeId = assignedQuestion.ChallengeId, Parameters = new List <ACMP.GlobalChallengeParameters.ParameterDefinition>()
                                    };
                                }
                                else if (globalParams.Parameters == null)
                                {
                                    globalParams.Parameters = new List <ACMP.GlobalChallengeParameters.ParameterDefinition>();
                                }

                                globalParams.Parameters.Add(new ACMP.GlobalChallengeParameters.ParameterDefinition
                                {
                                    Key   = parameter.Key.Replace("Global.", ""),
                                    Value = parameter.Value,
                                    AssignedToQuestion = 1
                                });
                            }
                            else
                            {
                                globalParameter.AssignedToQuestion += 1;
                            }
                        }
                    }

                    await challengeParameterProvider.AddItemAsync(globalParams);

                    var addQuestionResult = await assignedQuestionProvider.AddItemAsync(assignedQuestion);

                    if (addQuestionResult.Success)
                    {
                        var updateChallengeResult = await challengeProvider.AddItemAsync(challenge);

                        if (!updateChallengeResult.Success)
                        {
                            await assignedQuestionProvider.DeleteItemAsync(assignedQuestion.QuestionId);

                            return(StatusCode(500));
                        }
                    }
                }
            }

            return(RedirectToAction("Edit", new
            {
                challengeId = inputModel.QuestionToAdd.ChallengeId
            }));
        }
        public IHttpActionResult Edit(int id, EditChallengeViewModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                var challenge = this.data.Challenges.Find(id);

                if (challenge != null && challenge.CreatorId == this.CurrentUser.Id)
                {
                    Mapper.Map<EditChallengeViewModel, Challenge>(model, challenge);

                    this.data.Challenges.Update(challenge);
                    this.data.SaveChanges();

                    return this.Ok(model);
                }
            }

            return this.BadRequest("Couldn't edit challenge.");
        }
        public IHttpActionResult Edit(int id)
        {
            var challenge = this.data.Challenges.Find(id);

            if (challenge == null || challenge.CreatorId != this.CurrentUser.Id)
            {
                return this.BadRequest("Not your challenge to edit.");
            }

            var model = new EditChallengeViewModel()
            {
                Title = challenge.Title,
                Description = challenge.Description,
                Difficulty = challenge.Difficulty,
                ImageUrl = challenge.ImageUrl,
                DaysToComplete = challenge.DaysToComplete
            };

            return this.Ok(model);
        }