예제 #1
0
        public void DownloadResourceActionWhenPracticingWhenFileHasNoContentAndUserIsRegisteredForContestShouldThrowAnException()
        {
            var contest = this.CreateAndSaveContest("testContest", this.InactiveContestOptions, this.ActiveContestWithPasswordOptions);
            var problem = new Problem
            {
                Name = "test problem"
            };

            var resource = new ProblemResource
            {
                File          = new byte[0],
                FileExtension = "txt"
            };

            problem.Resources.Add(resource);
            contest.Problems.Add(problem);
            contest.Participants.Add(new Participant(contest.Id, this.FakeUserProfile.Id, this.IsPractice));
            this.EmptyOjsData.SaveChanges();

            try
            {
                var result = this.CompeteController.DownloadResource(resource.Id, this.IsPractice) as FileContentResult;
                Assert.Fail("Expected an exception when trying to download a resource with 0 file length.");
            }
            catch (HttpException ex)
            {
                Assert.AreEqual((int)HttpStatusCode.Forbidden, ex.GetHttpCode());
            }
        }
예제 #2
0
        public void DownloadResourceActionWhenPracticeAndUserNotLoggedInShouldRegirectToLoginPage()
        {
            var contest = this.CreateAndSaveContest("testContest", this.InactiveContestOptions, this.ActiveContestWithPasswordOptions);
            var problem = new Problem
            {
                Name = "test problem"
            };

            var resource = new ProblemResource
            {
                File          = new byte[1],
                FileExtension = "test"
            };

            problem.Resources.Add(resource);
            contest.Problems.Add(problem);
            this.EmptyOjsData.SaveChanges();

            var controller = new CompeteController(this.EmptyOjsData, null);
            var result     = controller.DownloadResource(resource.Id, this.IsPractice) as RedirectToRouteResult;

            Assert.AreEqual("Register", result.RouteValues["action"]);
            Assert.AreEqual(this.IsPractice, result.RouteValues["official"]);
            Assert.AreEqual(contest.Id, result.RouteValues["id"]);
        }
예제 #3
0
        public void DownloadResourceActionWhenPracticingButPracticeNotAllowedShouldThrowException()
        {
            var contest = this.CreateAndSaveContest("testContest", this.InactiveContestOptions, this.InactiveContestOptions);
            var problem = new Problem
            {
                Name = "test problem"
            };

            var resource = new ProblemResource
            {
                File          = new byte[1],
                FileExtension = "test"
            };

            problem.Resources.Add(resource);
            contest.Problems.Add(problem);
            this.EmptyOjsData.SaveChanges();

            try
            {
                var result = this.CompeteController.DownloadResource(resource.Id, this.IsPractice) as RedirectToRouteResult;
                Assert.Fail("Expected an exception when a user is trying to download a resource for a contest that cannot be practiced.");
            }
            catch (HttpException ex)
            {
                Assert.AreEqual((int)HttpStatusCode.Forbidden, ex.GetHttpCode());
            }
        }
예제 #4
0
        public void DownloadResourceActionWhenCompetingResourceIsAvailableAndUserIsRegisteredForCompeteShouldReturnResource()
        {
            var contest = this.CreateAndSaveContest("testContest", this.ActiveContestWithPasswordOptions, this.InactiveContestOptions);
            var problem = new Problem
            {
                Name = "test problem"
            };

            var resource = new ProblemResource
            {
                File = new byte[]
                {
                    (byte)this.RandomGenerator.Next(0, byte.MaxValue),
                    (byte)this.RandomGenerator.Next(0, byte.MaxValue)
                },
                Name          = "resourceName",
                FileExtension = "test"
            };

            problem.Resources.Add(resource);
            contest.Problems.Add(problem);
            contest.Participants.Add(new Participant(contest.Id, this.FakeUserProfile.Id, this.IsCompete));
            this.EmptyOjsData.SaveChanges();

            var result           = this.CompeteController.DownloadResource(resource.Id, this.IsCompete) as FileContentResult;
            var expectedFileName = string.Format("{0}_{1}.{2}", problem.Name, resource.Name, resource.FileExtension);

            Assert.AreEqual(expectedFileName, result.FileDownloadName);
            Assert.IsTrue(resource.File.SequenceEqual(result.FileContents));
        }
예제 #5
0
        public ActionResult Create(int id, ProblemResourceViewModel resource)
        {
            if (resource == null)
            {
                this.TempData.AddDangerMessage(Resource.Invalid_resource);
                return(this.RedirectToAction("Resource", "Problems", new { id }));
            }

            if (!this.CheckIfUserHasProblemPermissions(id))
            {
                return(this.RedirectToContestsAdminPanelWithNoPrivilegesMessage());
            }

            if (resource.Type == ProblemResourceType.Link && string.IsNullOrEmpty(resource.RawLink))
            {
                this.ModelState.AddModelError("Link", Resource.Link_not_empty);
            }
            else if (resource.Type != ProblemResourceType.Link && (resource.File == null || resource.File.ContentLength == 0))
            {
                this.ModelState.AddModelError("File", Resource.File_required);
            }

            if (this.ModelState.IsValid)
            {
                var problem = this.Data.Problems
                              .All()
                              .FirstOrDefault(x => x.Id == id);

                if (problem == null)
                {
                    this.TempData.AddDangerMessage(Resource.Problem_not_found);
                    return(this.RedirectToAction(GlobalConstants.Index, "Problems"));
                }

                var newResource = new ProblemResource
                {
                    Name    = resource.Name,
                    Type    = resource.Type,
                    OrderBy = resource.OrderBy,
                };

                if (resource.Type == ProblemResourceType.Link)
                {
                    newResource.Link = resource.RawLink;
                }
                else
                {
                    newResource.File          = resource.File.InputStream.ToByteArray();
                    newResource.FileExtension = resource.FileExtension;
                }

                problem.Resources.Add(newResource);
                this.Data.SaveChanges();

                return(this.RedirectToAction("Resource", "Problems", new { id }));
            }

            resource.AllTypes = EnumConverter.GetSelectListItems <ProblemResourceType>();
            return(this.View(resource));
        }
예제 #6
0
        public ActionResult Create(int id, ProblemResourceViewModel resource)
        {
            if (resource == null)
            {
                TempData["DangerMessage"] = "Ресурсът е невалиден";
                return(RedirectToAction("Resource", "Problems", new { id = id }));
            }

            if (resource.Type == ProblemResourceType.Video && string.IsNullOrEmpty(resource.Link))
            {
                ModelState.AddModelError("Link", "Линкът не може да бъде празен");
            }
            else if (resource.Type != ProblemResourceType.Video && (resource.File == null || resource.File.ContentLength == 0))
            {
                ModelState.AddModelError("File", "Файлът е задължителен");
            }

            if (ModelState.IsValid)
            {
                var problem = this.Data.Problems
                              .All()
                              .FirstOrDefault(x => x.Id == id);

                if (problem == null)
                {
                    TempData["DangerMessage"] = "Задачата не е намерена";
                    return(RedirectToAction("Index", "Problems"));
                }

                var newResource = new ProblemResource
                {
                    Name    = resource.Name,
                    Type    = resource.Type,
                    OrderBy = resource.OrderBy,
                };

                if (resource.Type == ProblemResourceType.Video)
                {
                    newResource.Link = resource.Link;
                }
                else
                {
                    newResource.File          = resource.File.InputStream.ToByteArray();
                    newResource.FileExtension = resource.FileExtension;
                }

                problem.Resources.Add(newResource);
                this.Data.SaveChanges();

                return(RedirectToAction("Resource", "Problems", new { id = id }));
            }

            resource.AllTypes = this.GetAllResourceTypes();
            return(View(resource));
        }
        public bool IsTaskExist(string name, ProblemResource resource)
        {
            var task = GetAll().FirstOrDefault(x =>
                                               x.Resource == resource &&
                                               x.Title == name);

            if (task == null)
            {
                return(false);
            }

            return(true);
        }
예제 #8
0
 public ProblemResourceViewModel(ProblemResource resource, IEnumerable <ProblemResourceTask> tasks)
 {
     if (resource != null)
     {
         ID             = resource.ID;
         Session        = new SessionViewModel(resource.Session);
         Title          = resource.Title;
         Emotion        = resource.Emotion;
         Location       = resource.Location;
         Characteristic = resource.Characteristic;
         Influence      = resource.Influence;
         LikeScore      = resource.LikeScore;
         Tasks          = tasks.Select(x => new ProblemResourceTaskViewModel(x)).ToList();
     }
 }
예제 #9
0
 public ProblemResourceViewModel(ProblemResource resource)
 {
     if (resource != null)
     {
         ID             = resource.ID;
         Session        = new SessionViewModel(resource.Session);
         Title          = resource.Title;
         Emotion        = resource.Emotion;
         Location       = resource.Location;
         Characteristic = resource.Characteristic;
         Influence      = resource.Influence;
         LikeScore      = resource.LikeScore;
         Tasks          = new List <ProblemResourceTaskViewModel>();
     }
 }
예제 #10
0
        public void DownloadTaskLinkShouldNavigateProperly()
        {
            var contest = new Contest {
                Name = "1337",
            };
            var problem = new Problem {
                Contest = contest, Name = "1337", OldId = 1337
            };
            var resource = new ProblemResource {
                Problem = problem, Type = ProblemResourceType.ProblemDescription
            };

            this.EmptyOjsData.Resources.Add(resource);
            this.EmptyOjsData.SaveChanges();

            this.VerifyUrlRedirection("~/Contest/DownloadTask/1337", string.Format("/Contests/Practice/DownloadResource/{0}", resource.Id));
        }
        public ProblemResourceTask CreateUpdateTask(CreateUpdateProblemResourceTask request, ProblemResource resource = null)
        {
            if (request.ID == 0)
            {
                return(CreateTask(request, resource));
            }

            return(UpdateTask(request));
        }
        public ProblemResourceTask CreateTask(CreateUpdateProblemResourceTask request, ProblemResource resource)
        {
            if (request.ID != 0)
            {
                return(null);
            }

            if (IsTaskExist(request.Title, resource))
            {
                return(null);
            }

            var entity = new ProblemResourceTask
            {
                Resource = resource,
                Title    = request.Title,
                IsDone   = request.IsDone
            };

            Create(entity);

            return(entity);
        }
 public List <ProblemResourceTask> GetResourceTasks(ProblemResource resource)
 {
     return(GetAll().Where(x => x.Resource == resource).ToList());
 }
예제 #14
0
        public void Copy(OjsDbContext context, TelerikContestSystemEntities oldDb)
        {
            context.Configuration.AutoDetectChangesEnabled = false;
            foreach (var task in oldDb.Tasks.OrderBy(x => x.Id).Include(x => x.Contest1).ToList())
            {
                var contest = context.Contests.FirstOrDefault(x => x.OldId == task.Contest);
                var problem = new Problem
                {
                    OldId             = task.Id,
                    Contest           = contest,
                    Name              = task.Name,
                    MaximumPoints     = (short)task.MaxPoints,
                    TimeLimit         = task.TimeLimit,
                    MemoryLimit       = task.MemoryLimit,
                    OrderBy           = 0,
                    ShowResults       = task.Contest1.ShowResults,
                    CreatedOn         = task.AddedOn,
                    PreserveCreatedOn = true,
                };

                if (task.DescriptionLink != null || (task.Description != null && task.Description.Length != 0))
                {
                    var resource = new ProblemResource
                    {
                        CreatedOn         = task.AddedOn,
                        PreserveCreatedOn = true,
                        Name = string.Format("Условие на задачата"),
                        Type = ProblemResourceType.ProblemDescription,
                    };

                    if (task.DescriptionLink != null)
                    {
                        if (task.Id == 368)
                        {
                            task.DescriptionLink =
                                "http://downloads.academy.telerik.com/svn/oop/Lectures/9.%20Exam%20Preparation/DocumentSystem-Skeleton.rar";
                        }

                        if (task.Id == 369)
                        {
                            task.DescriptionLink =
                                "http://downloads.academy.telerik.com/svn/oop/Lectures/9.%20Exam%20Preparation/AcademyGeometry-Skeleton.zip";
                        }

                        var web  = new WebClient();
                        var data = web.DownloadData(task.DescriptionLink);
                        resource.File          = data;
                        resource.FileExtension = task.DescriptionLink.GetFileExtension();
                    }
                    else
                    {
                        resource.File          = task.Description;
                        resource.FileExtension = task.DescriptionFormat;
                    }

                    problem.Resources.Add(resource);
                }

                switch (task.Checker1.Name)
                {
                case "Exact":
                    problem.Checker = context.Checkers.FirstOrDefault(x => x.Name == "Exact");
                    break;

                case "Trim":
                    problem.Checker = context.Checkers.FirstOrDefault(x => x.Name == "Trim");
                    break;

                case "Sort":
                    problem.Checker = context.Checkers.FirstOrDefault(x => x.Name == "Sort lines");
                    break;

                default:
                    problem.Checker = null;
                    break;
                }

                context.Problems.Add(problem);
            }

            context.SaveChanges();
            context.Configuration.AutoDetectChangesEnabled = true;
        }
예제 #15
0
        private ProblemResourceViewModel GetFullProblemResource(ProblemResource resource)
        {
            var tasks = ProblemResourceTaskService.GetResourceTasks(resource);

            return(new ProblemResourceViewModel(resource, tasks));
        }
예제 #16
0
        public IActionResult CreateClientProblemResource([FromBody] CreateUpdateProblemResourceRequest request, long clientID, long problemID)
        {
            var user = UserService.Get(long.Parse(User.Identity.Name));

            if (user == null)
            {
                return(NotFound(new ResponseModel
                {
                    Success = false,
                    Message = "Пользователь не найден"
                }));
            }

            var specialist = SpecialistService.GetSpecialistFromUser(user);

            if (specialist == null)
            {
                return(NotFound(new ResponseModel
                {
                    Success = false,
                    Message = "Специалист не найден"
                }));
            }

            var client = UserService.Get(clientID);

            if (client == null)
            {
                return(NotFound(new ResponseModel
                {
                    Success = false,
                    Message = "Клиент не найден"
                }));
            }

            var problem = ProblemService.Get(problemID);

            if (problem == null)
            {
                return(NotFound(new ResponseModel
                {
                    Success = false,
                    Message = "Проблема не найдена"
                }));
            }

            if (problem.User != client)
            {
                return(BadRequest(new ResponseModel
                {
                    Success = false,
                    Message = "Ошибка доступа"
                }));
            }

            var session = SessionService.GetCurrentSession(problem);

            if (session == null)
            {
                return(NotFound(new ResponseModel
                {
                    Success = false,
                    Message = "Активная сессия не найдена"
                }));
            }

            if (session.Problem != problem)
            {
                return(BadRequest(new ResponseModel
                {
                    Success = false,
                    Message = "Ошибка доступа"
                }));
            }

            var resource = new ProblemResource
            {
                Session        = session,
                Title          = request.Title,
                Emotion        = request.Emotion,
                Location       = request.Location,
                Characteristic = request.Characteristic,
                Influence      = request.Influence,
                LikeScore      = request.LikeScore
            };

            ProblemResourceService.Create(resource);

            request.Tasks.ForEach(task => ProblemResourceTaskService.CreateTask(task, resource));

            var resources = ProblemResourceService.GetProblemResources(problem)
                            .Select(x => GetFullProblemResource(x))
                            .ToList();

            return(Ok(new DataResponse <List <ProblemResourceViewModel> >
            {
                Data = resources
            }));
        }