Example #1
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/html";
                string action = context.Request["action"];

                if (action == "view")
                {
                    uint    ID      = Convert.ToUInt32(context.Request["pid"]);
                    Problem problem = ProblemService.SelectByProblemID(ID);
                    var     Data    = new { problem = problem };
                    string  html    = CommonHelper.RenderHtml("problemView.html", Data);
                    context.Response.Write(html);
                }
                else
                {
                    context.Response.Redirect("index.ashx", false);
                }
            }
            catch (Exception e)
            {
                LogService.Insert(0, e);
                context.Response.Redirect("index.ashx", false);
            }
        }
Example #2
0
        private ClientCardViewModel GetClientCard(User user, Specialist specialist)
        {
            var result = new ClientCardViewModel
            {
                ID            = user.ID,
                User          = new UserViewModel(user),
                ProblemsCount = ProblemService.GetUserProblemsCount(user),
            };

            var sessions = SessionService.GetAll()
                           .Where(x => x.Problem.User == user && x.Specialist == specialist)
                           .OrderByDescending(x => x.Date)
                           .ToList();

            var reviews = new List <ReviewViewModel>();

            sessions.ForEach(session =>
            {
                var review = ReviewService.GetSessionReview(session);
                reviews.Add(new ReviewViewModel(review));
            });

            result.Sessions     = sessions.Select(x => GetSpecialistSession(x)).ToList();
            result.AverageScore = (reviews.Sum(x => x.Score) / reviews.Count);
            result.Paid         = sessions.Where(x => x.Status == SessionStatus.Success).Sum(x => x.Reward);
            result.RefundsCount = sessions.Where(x => x.Status == SessionStatus.Refund).ToList().Count;

            return(result);
        }
        protected override void ProcessRecord()
        {
            var      problems = ProblemService.GetProblems(typeof(Problems.DiscoveryProblem).Assembly);
            IProblem problem  = null;

            var pr = new ProblemResult
            {
                Number = Number,
            };

            if (problems.TryGetValue(Number, out problem))
            {
                try
                {
                    var sw     = Stopwatch.StartNew();
                    var answer = problem.Execute();
                    sw.Stop();
                    pr.Answer   = answer;
                    pr.Duration = sw.ElapsedMilliseconds;
                }
                catch (ProblemIncompleteException)
                {
                    pr.Answer = $"Problem {problem.Number} is incomplete";
                }
            }
            else
            {
                pr.Answer = $"Problem not found";
            }

            WriteObject(pr);
            //base.ProcessRecord();
        }
Example #4
0
        public IActionResult GetProblem(long id)
        {
            if (User.Identity.Name == null)
            {
                return(Ok());
            }

            var user = UserService.Get(long.Parse(User.Identity.Name));

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

            var problem = ProblemService.Get(id);

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

            return(Ok(new DataResponse <ProblemViewModel>
            {
                Data = new ProblemViewModel(problem)
            }));
        }
Example #5
0
        public IActionResult CreateProblem([FromBody] CreateProblemRequest request)
        {
            var user = UserService.Get(long.Parse(User.Identity.Name));

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

            var problem = new Problem
            {
                User        = user,
                ProblemText = request.ProblemText
            };

            ProblemService.Create(problem);

            return(Ok(new DataResponse <ProblemViewModel>
            {
                Data = new ProblemViewModel(problem)
            }));
        }
Example #6
0
        private SuperadminCustomerCard GetSuperadminCustomerCard(User user)
        {
            var problems = ProblemService.GetUserProblems(user);
            var sessions = SessionService.GetUserSessions(user)
                           .Select(session => GetSpecialistSession(session))
                           .ToList();

            return(new SuperadminCustomerCard
            {
                UserID = user.ID,
                FullName = $"{user.FirstName} {user.LastName}",
                PhoneNumber = user.PhoneNumber,
                Role = user.Role,
                Sessions = sessions,
                ProblemsCount = problems.Count,

                SpendOrEarned = sessions
                                .Where(session => session.SessionStatus == SessionStatus.Success)
                                .ToList()
                                .Sum(session => session.Reward),

                RefundsCount = sessions
                               .Where(session => session.SessionStatus == SessionStatus.Refund)
                               .ToList()
                               .Count
            });
        }
Example #7
0
        public IActionResult GetAvailableProblems()
        {
            if (User.Identity.Name == null)
            {
                return(Ok());
            }

            var user = UserService.Get(long.Parse(User.Identity.Name));

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

            var problems = ProblemService.GetAll()
                           .Where(x => x.User == user)
                           .ToList()
                           .Where(x => !IsProblemInWork(x))
                           .OrderByDescending(x => x.CreatedDate)
                           .Select(x => new ProblemViewModel(x))
                           .ToList();

            return(Ok(new DataResponse <List <ProblemViewModel> >
            {
                Data = problems
            }));
        }
Example #8
0
    static void Main(string[] args)
    {
        var solvableProblems = ProblemService.GetProblems(typeof(Problems.DiscoveryProblem).Assembly);

        var problemToRun = 97;

        RunProblems(solvableProblems, problemToRun);
    }
Example #9
0
        public IActionResult GetSession(long id, long sessionID)
        {
            var user = UserService.Get(long.Parse(User.Identity.Name));

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

            var problem = ProblemService.Get(id);

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

            if (problem.User != user)
            {
                return(BadRequest(new ResponseModel
                {
                    Success = false,
                    Message = "Доступ запрещен"
                }));
            }

            var session = SessionService.Get(sessionID);

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

            if (session.Problem != problem)
            {
                return(BadRequest(new ResponseModel
                {
                    Success = false,
                    Message = "Доступ запрещен"
                }));
            }

            return(Ok(new DataResponse <SessionViewModel>
            {
                Data = GetFullSession(session)
            }));
        }
Example #10
0
        public IActionResult GetProblemAssets(long problemID)
        {
            var user = UserService.Get(long.Parse(User.Identity.Name));

            if (user == 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 != user)
            {
                return(BadRequest(new ResponseModel
                {
                    Success = false,
                    Message = "Доступ запрещен"
                }));
            }

            var images = ProblemImageService.GetProblemImages(problem)
                         .Select(x => new ProblemImageViewModel(x))
                         .ToList();

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

            var sessions = SessionService.GetUserSessions(user)
                           .Where(x => x.Problem == problem)
                           .Select(x => GetFullSession(x))
                           .ToList();

            return(Ok(new DataResponse <ClientProblemAssetsViewModel>
            {
                Data = new ClientProblemAssetsViewModel
                {
                    Problem = new ProblemViewModel(problem),
                    Images = images,
                    Resources = resources,
                    Sessions = sessions
                }
            }));
        }
        public IActionResult SignUp([FromBody] SignUpRequest request)
        {
            var user = UserService.FindByPhoneNumber(request.PhoneNumber);

            if (user != null)
            {
                return(BadRequest(new ResponseModel
                {
                    Success = false,
                    Message = "Номер телефона уже используется"
                }));
            }

            user = UserService.FindByEmail(request.Email);
            if (user != null)
            {
                return(BadRequest(new ResponseModel
                {
                    Success = false,
                    Message = "Email уже используется"
                }));
            }

            user = new User
            {
                FirstName    = request.FirstName,
                LastName     = request.LastName,
                PhoneNumber  = request.PhoneNumber,
                Email        = request.Email,
                Role         = UserRole.Client,
                RegisteredAt = DateTime.UtcNow
            };

            UserService.Create(user);

            UserWalletService.Create(new UserWallet
            {
                User    = user,
                Balance = 0
            });

            ProblemService.Create(new Problem
            {
                User        = user,
                ProblemText = request.Problem
            });

            var session = UserSessionService.CreateSession(user);

            SmscHelper.SendSms(user.PhoneNumber, $"Код для входа: {session.AuthCode}");

            return(Ok(new SignInResponse
            {
                UserID = user.ID
            }));
        }
Example #12
0
        public IActionResult ChangeSessionSpecialist([FromBody] CreateSessionRequest request, long id, long sessionID)
        {
            var user = UserService.Get(long.Parse(User.Identity.Name));

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

            var problem = ProblemService.Get(id);

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

            var session = SessionService.Get(sessionID);

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

            var specialist = SpecialistService.Get(request.SpecialistID);

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

            session.Specialist = specialist;
            session.Reward     = specialist.Price;
            session.Status     = SessionStatus.New;

            SessionService.Update(session);

            return(Ok(new ResponseModel()));
        }
Example #13
0
        public ProblemServiceTests()
        {
            var optionsBuilder = new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString());
            var context        = new SqlContext(optionsBuilder.Options);

            var problemLibraryAssembly = Assembly.Load("ProblemLibrary");

            _fileDataService = new FileDataService(context);
            _problemService  = new ProblemService(context, _fileDataService);
            _authorService   = new AuthorService(context);
        }
        //private ProblemService _problemService;

        //private IterationSystemService _iterationSystemService;

        /// <summary>
        /// Window constructor, receiving vertices collection
        /// </summary>
        /// <param name="vertices"></param>
        public TriangulationData(VertexCollection vertices, List <Triangle> triangles, Boundary boundary)
        {
            InitializeComponent();
            // this._problemService = new ProblemService(vertices, triangles, boundary);
            DataContext          = this;
            this.vertices        = vertices;
            this.triangles       = triangles;
            dataGrid.ItemsSource = this.vertices;
            problemService       = new ProblemService(this.vertices, this.triangles, new Boundary((0, 0), (2, 0), (2, 2), (0, 2)));
            MatrixService        = new MatrixService(vertices, triangles);
            InitData();
        }
Example #15
0
        public IActionResult CreateReview([FromBody] CreateReviewRequest request, long id, long sessionID)
        {
            var user = UserService.Get(long.Parse(User.Identity.Name));

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

            var problem = ProblemService.Get(id);

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

            var session = SessionService.Get(sessionID);

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

            var specialist = SpecialistService.Get(session.Specialist.ID);

            session.Specialist = specialist;

            SessionService.Update(session);

            var review = new Review
            {
                Session = session,
                Text    = request.ReviewText,
                Score   = request.Score
            };

            ReviewService.Create(review);

            return(Ok(new ResponseModel()));
        }
        public CategoryServiceTests()
        {
            var optionsBuilder = new DbContextOptionsBuilder().UseInMemoryDatabase(Guid.NewGuid().ToString());

            _context = new SqlContext(optionsBuilder.Options);
            var fileDataService = new FileDataService(_context);

            _categoryService = new CategoryService(_context);
            _problemService  = new ProblemService(_context, fileDataService);
            _quizService     = new QuizService(_context);
            _exerciseService = new ExerciseService(_context);
            _authorService   = new AuthorService(_context);
        }
        public async Task <PostFileResponse> PostFile(string guid, IFormFile file, CancellationToken token)
        {
            if (string.IsNullOrEmpty(guid))
            {
                throw new WebArgumentException(nameof(PostFile), nameof(guid), guid);
            }

            if (file.Length > Configuration.FileSize)
            {
                return(PostFileResponse.FileSizeError);
            }

            var solutionSet = await SolutionService.FetchSolutionSet(guid, token);

            if (solutionSet == null)
            {
                return(PostFileResponse.IdentificationError);
            }

            var problemSet = await ProblemService.FetchProblemAsync(solutionSet.ProblemId, token);

            if (problemSet == null)
            {
                return(PostFileResponse.ProblemIdentificationError);
            }

            if (file.Length > problemSet.SolutionSize)
            {
                return(PostFileResponse.FileSizeError);
            }

            using (var writer = new FileStream(Path.Combine(Configuration.FileLocation, file.FileName), FileMode.CreateNew))
            {
                await file.CopyToAsync(writer, token);

                await writer.FlushAsync(token);
            }

            var result = await SolutionService.FinalizeSolutionSet(guid, token);

            if (result == SolutionServiceResult.Full)
            {
                return(PostFileResponse.Full);
            }
            if (result == SolutionServiceResult.Incomplete || result == SolutionServiceResult.StartOver)
            {
                return(PostFileResponse.Failure);
            }

            return(PostFileResponse.Success);
        }
Example #18
0
        public IActionResult CreateProblemSession([FromBody] CreateSessionRequest request, long id)
        {
            var user = UserService.Get(long.Parse(User.Identity.Name));

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

            var problem = ProblemService.Get(id);

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

            var specialist = SpecialistService.Get(request.SpecialistID);

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

            var session = new Session
            {
                Specialist = specialist,
                Problem    = problem,
                Reward     = specialist.Price,
                Status     = SessionStatus.New,
                Date       = DateTime.UtcNow
            };

            SessionService.Create(session);

            return(Ok(new CreateSessionResponse
            {
                SessionID = session.ID
            }));
        }
Example #19
0
        public IActionResult GetProblemSessions(long id)
        {
            var user = UserService.Get(long.Parse(User.Identity.Name));

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

            var problem = ProblemService.Get(id);

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

            if (problem.User != user)
            {
                return(BadRequest(new ResponseModel
                {
                    Success = false,
                    Message = "Доступ запрещен"
                }));
            }

            var sessions = SessionService.GetAll()
                           .Where(x => x.Problem == problem)
                           .OrderByDescending(x => x.Date)
                           .Select(x => GetFullSession(x))
                           .ToList();

            return(Ok(new DataResponse <List <SessionViewModel> >
            {
                Data = sessions
            }));
        }
Example #20
0
        public IActionResult GetCustomer(long userID)
        {
            var user = UserService.Get(userID);

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

            var problems = ProblemService.GetUserProblems(user);
            var sessions = SessionService.GetUserSessions(user)
                           .Select(session => GetSpecialistSession(session))
                           .ToList();

            return(Ok(new DataResponse <SuperadminCustomerCard>
            {
                Data = new SuperadminCustomerCard
                {
                    UserID = user.ID,
                    FullName = $"{user.FirstName} {user.LastName}",
                    PhoneNumber = user.PhoneNumber,
                    Role = user.Role,
                    Sessions = sessions,
                    ProblemsCount = problems.Count,

                    SpendOrEarned = sessions
                                    .Where(session => session.SessionStatus == SessionStatus.Success)
                                    .ToList()
                                    .Sum(session => session.Reward),

                    RefundsCount = sessions
                                   .Where(session => session.SessionStatus == SessionStatus.Refund)
                                   .ToList()
                                   .Count
                }
            }));
        }
        public async Task <RequestProblemSubmission> RequestSolutionSubmission(SolutionSubmission submission, CancellationToken token)
        {
            if (submission == null)
            {
                throw new WebArgumentException(nameof(submission), nameof(RequestProblemSubmission), null);
            }
            var guid = Guid.NewGuid().ToString();
            var path = Path.Combine(Configuration.FileLocation, guid);

            if (!await ProblemService.Exists(submission.ProblemId, token))
            {
                return new RequestProblemSubmission
                       {
                           Result = SolutionServiceResult.StartOver
                       }
            }
            ;
            var solution = new Solution
            {
                Id           = guid,
                ProblemId    = submission.ProblemId,
                TimeStamp    = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds,
                FileLocation = path,
                User         = User.Identity.Name,
                SolutionType = submission.SolutionType
            };
            var result = await SolutionService.AddSolutionSet(guid, solution, token);

            var requestResult = new RequestProblemSubmission {
                Result = result
            };

            if (result == SolutionServiceResult.Success)
            {
                requestResult.Guid = guid;
            }
            return(requestResult);
        }
Example #22
0
        public static bool AddProblem(Problem problem, string pattern_a, string pattern_img, string URL)
        {
            if (problem.Title.Length <= 0)
            {
                return(false);
            }

            problem.Description  = Link(problem.Description, pattern_a, URL);
            problem.Description  = Link(problem.Description, pattern_img, URL);
            problem.Input        = Link(problem.Input, pattern_a, URL);
            problem.Input        = Link(problem.Input, pattern_img, URL);
            problem.Output       = Link(problem.Output, pattern_a, URL);
            problem.Output       = Link(problem.Output, pattern_img, URL);
            problem.SampleInput  = Link(problem.SampleInput, pattern_a, URL);
            problem.SampleInput  = Link(problem.SampleInput, pattern_img, URL);
            problem.SampleOutput = Link(problem.SampleOutput, pattern_a, URL);
            problem.SampleOutput = Link(problem.SampleOutput, pattern_img, URL);
            problem.Hint         = Link(problem.Hint, pattern_a, URL);
            problem.Hint         = Link(problem.Hint, pattern_img, URL);

            ProblemService.Insert(problem);
            return(true);
        }
Example #23
0
 public SubmissionsController(SubmissionService submissionService, ProblemService problemService)
 {
     _submissionService = submissionService;
     _problemService    = problemService;
 }
Example #24
0
 public ProblemController()
 {
     _problemService = new ProblemService();
 }
        public void Run(string from, string to)
        {
            list1.Items.Clear();
            int ojid = comboBox1.SelectedIndex;

            if (ojid < 0 || ojid >= ojs.Count)
            {
                MessageBox.Show("OJ Choose Error");
            }

            Regex regex = new Regex(ojs[ojid].PatternProblemID);
            Match mf    = regex.Match(from);
            Match mt    = regex.Match(to);

            if (mf.Success == false || mt.Success == false)
            {
                MessageBox.Show("Format the Problem ID");
                return;
            }

            int fromid = Convert.ToInt32(mf.Groups[1].ToString());
            int toid   = Convert.ToInt32(mt.Groups[1].ToString());

            for (int i = fromid; i <= toid; ++i)
            {
                OJ      oj = ojs[ojid];
                Problem p  = ProblemService.SelectByOJProblemID((uint)ojid + 1, i.ToString());
                if (p.ProblemID == 0)
                {
                    try
                    {
                        string status;
                        bool   result = false;
                        switch (ojid)
                        {
                        case 0:
                            result = OJCrawl.HDU(i);
                            break;

                        case 1:
                            result = OJCrawl.NBU(i);
                            break;

                        case 2:
                            result = OJCrawl.POJ(i);
                            break;

                        case 3:
                            result = OJCrawl.ZOJ(i);
                            break;

                        default:
                            break;
                        }
                        status = result ? "ok" : "failed";
                        UpdateStatus(oj.OJName + " " + i + " " + status);
                    }
                    catch (Exception e)
                    {
                        LogService.Insert(1, e);
                    }
                }
                else
                {
                    UpdateStatus(oj.OJName + " " + i + " " + "existing");
                }
            }
        }
 public ProblemController()
 {
     _problemService = new ProblemService();
 }
Example #27
0
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/html";
                string     action = context.Request["action"];
                HttpCookie cookie = context.Request.Cookies["GUID"];
                if (cookie == null)
                {
                    context.Response.Write("<script>alert('Log in First');window.location.href='index.ashx'</script>");
                    return;
                }
                uint uid = CookieService.SelectByGUID(cookie.Value);
                if (uid == 0)
                {
                    context.Response.Write("<script>alert('Log in First');window.location.href='index.ashx'</script>");
                    return;
                }
                #region

                /*
                 * ajax
                 * */
                if (action == "check")
                {
                    context.Response.ContentType = "text/plain";
                    uint cid = (uint)Convert.ToUInt32(context.Request["cid"]);
                    if (ContestUserService.Select(cid, uid))
                    {
                        context.Response.Write("ok");
                    }
                    else
                    {
                        context.Response.Write("no");
                    }
                }
                #endregion

                #region

                /*
                 * ajax
                 * */
                else if (action == "checkcpsd")
                {
                    context.Response.ContentType = "text/plain";
                    uint    cid     = (uint)Convert.ToUInt32(context.Request["cid"]);
                    Contest contest = ContestService.SelectByID(cid);
                    if (contest.Type == "private" && ContestUserService.Select(cid, uid) == false)
                    {
                        string pp = (string)context.Request["psd"];
                        if (pp == contest.Password)
                        {
                            ContestUserService.Insert(cid, uid);
                            context.Response.Write("ok");
                        }
                        else
                        {
                            context.Response.Write("no");
                        }
                    }
                    else
                    {
                        context.Response.Write("ok");
                    }
                    return;
                }
                #endregion

                #region
                else if (action == "view")
                {
                    uint    cid     = (uint)Convert.ToUInt32(context.Request["cid"]);
                    Contest contest = ContestService.SelectByID(cid);
                    if (contest.Type == "private" && ContestUserService.Select(cid, uid) == false)
                    {
                        context.Response.Write("<script>alert('No Permission')</script>");
                        return;
                    }
                    List <ContestProblem> contestproblems;
                    if (contest.Status == "Pending")
                    {
                        contestproblems = new List <ContestProblem>();
                    }
                    else
                    {
                        contestproblems = ContestProblemService.SelectByContestID(cid);
                    }
                    List <Solution> solsAsc  = SolutionService.SelectByContestIDAsc(cid);
                    List <Solution> solsDesc = new List <Solution>(solsAsc);
                    solsDesc.Reverse(0, solsAsc.Count);

                    /*
                     * OverView
                     * */
                    foreach (ContestProblem contestproblem in contestproblems)
                    {
                        List <Solution> msols = SolutionService.SelectByUserContestProblem(uid, contestproblem.ContestProblemID);
                        if (msols.Count == 0)
                        {
                            contestproblem.Status = "";
                            continue;
                        }
                        contestproblem.Status = "No";
                        foreach (Solution solution in msols)
                        {
                            if (solution.IsAccepted)
                            {
                                contestproblem.Status = "Yes";
                                break;
                            }
                        }
                    }

                    /*
                     * RankList
                     * */
                    List <User> us = new List <User>();
                    foreach (Solution sol in solsAsc)
                    {
                        sol.IsVisible = (sol.UserID == uid);
                        bool ok = false;
                        foreach (User u in us)
                        {
                            if (sol.UserID == u.UserID)
                            {
                                ok = true;
                                break;
                            }
                        }
                        if (ok == false)
                        {
                            User user = new User();
                            user.UserID   = sol.UserID;
                            user.Username = sol.Username;
                            user.Nickname = sol.Nickname;
                            for (int i = 0; i < contestproblems.Count; ++i)
                            {
                                user.Items.Add(new Item());
                            }
                            us.Add(user);
                        }
                    }
                    foreach (Solution sol in solsAsc)
                    {
                        foreach (User u in us)
                        {
                            if (sol.UserID == u.UserID)
                            {
                                uint id = (uint)sol.OrderID - 'A';
                                if (u.Items[(int)id].IsSolved == false)
                                {
                                    if (sol.IsAccepted)
                                    {
                                        u.Items[(int)id].IsSolved = true;
                                        u.Items[(int)id].Time     = sol.SubmitTime - contest.StartTime;
                                    }
                                    else if (sol.IsJudged)
                                    {
                                        u.Items[(int)id].Penalty++;
                                    }
                                }
                                break;
                            }
                        }
                    }

                    foreach (User u in us)
                    {
                        foreach (Item item in u.Items)
                        {
                            if (item.IsSolved == true)
                            {
                                u.ProsSolved++;
                                u.Timer += item.Time.Add(new TimeSpan(0, (int)(20 * item.Penalty), 0));
                            }
                        }
                    }

                    for (int i = 0; i < contestproblems.Count; ++i)
                    {
                        TimeSpan FB = new TimeSpan(1000, 0, 0);
                        foreach (User u in us)
                        {
                            if (u.Items[i].Time < FB && u.Items[i].Time != TimeSpan.Zero)
                            {
                                FB = u.Items[i].Time;
                            }
                        }
                        foreach (User u in us)
                        {
                            if (u.Items[i].Time == FB)
                            {
                                u.Items[i].IsFirst = true;
                            }
                        }
                    }
                    us.Sort();
                    for (int i = 0; i < us.Count; ++i)
                    {
                        us[i].Rank = (uint)i + 1;
                    }
                    var    Data = new { problems = contestproblems, contest = contest, solutions = solsDesc, users = us, ctime = (DateTime.UtcNow - DateTime.Parse("1970-1-1")).TotalMilliseconds };
                    string html = CommonHelper.RenderHtml("contestView.html", Data);
                    context.Response.Write(html);
                }
                #endregion

                #region
                else if (action == "add")
                {
                    List <OJ> OJs     = OJService.SelectAll();
                    Contest   contest = new Contest();
                    var       Data    = new
                    {
                        OJs    = OJs,
                        edit   = false,
                        Title  = "",
                        Time   = "",
                        Length = new TimeSpan(5, 0, 0),
                        Dec    = "",
                        Psd    = ""
                    };
                    string html = CommonHelper.RenderHtml("contestAdd.html", Data);
                    context.Response.Write(html);
                }
                #endregion

                #region
                else if (action == "csearch")
                {
                    string mtitle   = context.Request["mtitle"].ToString();
                    string mcreator = context.Request["mcreator"].ToString();
                    string mstatus  = context.Request["mstatus"].ToString();
                    string mtype    = context.Request["mtype"].ToString();
                    if (mtitle == "" && mcreator == "" && mstatus == "" && mtype == "")
                    {
                        context.Response.Redirect("ContestDo.ashx?action=list", false);
                    }
                    uint Page;
                    uint IsLast = 0;
                    uint npp    = 20;
                    if (context.Request["Page"] == null)
                    {
                        Page = 1;
                    }
                    else
                    {
                        Page = Convert.ToUInt32(context.Request["Page"]);
                    }
                    uint num  = ContestService.CountByPara(mtitle, mcreator, mstatus, mtype);
                    uint last = Math.Max(1, (num % npp == 0 ? num / npp : num / npp + 1));
                    if (Page == 0 || Page >= last)
                    {
                        Page = last;
                    }
                    if (Page == last)
                    {
                        IsLast = 1;
                    }
                    List <Contest> contests = ContestService.SelectPartByPara(mtitle, mcreator, mstatus, mtype, Page, npp);
                    var            Data     = new
                    {
                        contests = contests,
                        mlist    = false,
                        Page     = Page,
                        IsLast   = IsLast,
                        mTitle   = mtitle,
                        mCreator = mcreator,
                        mStatus  = mstatus,
                        mType    = mtype,
                        csearch  = true
                    };
                    string html = CommonHelper.RenderHtml("contestList.html", Data);
                    context.Response.Write(html);
                }
                #endregion

                #region
                else if (action == "list")
                {
                    uint Page;
                    uint IsLast = 0;
                    uint npp    = 20;
                    if (context.Request["Page"] == null)
                    {
                        Page = 1;
                    }
                    else
                    {
                        Page = Convert.ToUInt32(context.Request["Page"]);
                    }
                    uint num  = ContestService.CountAll();
                    uint last = Math.Max(1, (num % npp == 0 ? num / npp : num / npp + 1));
                    if (Page == 0 || Page >= last)
                    {
                        Page = last;
                    }
                    if (Page == last)
                    {
                        IsLast = 1;
                    }
                    List <Contest> contests = ContestService.SelectPart(Page, npp);
                    var            Data     = new
                    {
                        contests = contests,
                        mlist    = false,
                        Page     = Page,
                        IsLast   = IsLast,
                        mTitle   = "",
                        mCreator = "",
                        mStatus  = "",
                        mType    = "",
                        csearch  = false
                    };
                    string html = CommonHelper.RenderHtml("contestList.html", Data);
                    context.Response.Write(html);
                }
                #endregion

                #region
                else if (action == "mlist")
                {
                    uint Page;
                    uint IsLast = 0;
                    uint npp    = 20;
                    if (context.Request["Page"] == null)
                    {
                        Page = 1;
                    }
                    else
                    {
                        Page = Convert.ToUInt32(context.Request["Page"]);
                    }
                    uint num  = ContestService.CountByUID(uid);
                    uint last = Math.Max(1, (num % npp == 0 ? num / npp : num / npp + 1));
                    if (Page == 0 || Page >= last)
                    {
                        Page = last;
                    }
                    if (Page == last)
                    {
                        IsLast = 1;
                    }

                    List <Contest> contests = ContestService.SelectPartByUID(Page, npp, uid);
                    var            Data     = new { contests = contests, mlist = true, Page = Page, IsLast = IsLast };
                    string         html     = CommonHelper.RenderHtml("contestList.html", Data);
                    context.Response.Write(html);
                }
                #endregion

                #region
                else if (action == "getptitle")
                {
                    /*
                     * ajax
                     * */
                    context.Response.ContentType = "text/plain";
                    uint    oid     = (uint)Convert.ToUInt64(context.Request["oid"]);
                    string  pid     = context.Request["pid"].ToString();
                    Problem problem = ProblemService.SelectByOJProblemID(oid, pid);
                    if (problem.ProblemID == 0)
                    {
                        context.Response.Write("no");
                    }
                    else
                    {
                        JavaScriptSerializer jss = new JavaScriptSerializer();
                        string json = jss.Serialize(problem);
                        context.Response.Write(json);
                    }
                }
                #endregion

                #region
                else if (action == "addnew")
                {
                    string ctitle = (string)context.Request["ctitle"];
                    string stime  = (string)context.Request["stime"];
                    string tlen   = (string)context.Request["tlen"];
                    string psd    = (string)context.Request["psd"];
                    string dcl    = (string)context.Request["dcl"];
                    string pid    = (string)context.Request["pid"];
                    string ptitle = (string)context.Request["ptitle"];
                    for (int i = 0; i < psd.Length; ++i)
                    {
                        if (IsValidChar(psd[i]) == false)
                        {
                            return;
                        }
                    }
                    if (ctitle.Length > 80 || psd.Length > 24 || dcl.Length > 400)
                    {
                        return;
                    }

                    string   p_stime   = @"(\d\d):(\d\d):(\d\d) (\d\d)/(\d\d)/(\d\d\d\d)";
                    Regex    r_stime   = new Regex(p_stime);
                    Match    match     = r_stime.Match(stime);
                    int      hh        = Convert.ToInt32(match.Groups[1].ToString());
                    int      mm        = Convert.ToInt32(match.Groups[2].ToString());
                    int      ss        = Convert.ToInt32(match.Groups[3].ToString());
                    int      MM        = Convert.ToInt32(match.Groups[4].ToString());
                    int      dd        = Convert.ToInt32(match.Groups[5].ToString());
                    int      yyyy      = Convert.ToInt32(match.Groups[6].ToString());
                    DateTime StartTime = new DateTime(yyyy, MM, dd, hh, mm, ss);
                    string[] strs      = tlen.Split(':');
                    if (Convert.ToInt32(strs[0]) > 999 || Convert.ToInt32(strs[1]) > 23 ||
                        Convert.ToInt32(strs[2]) > 59 || Convert.ToInt32(strs[3]) > 59)
                    {
                        return;
                    }
                    if (Convert.ToInt32(strs[0]) <= 0 && Convert.ToInt32(strs[1]) <= 0 &&
                        Convert.ToInt32(strs[2]) <= 0 && Convert.ToInt32(strs[3]) <= 0)
                    {
                        return;
                    }


                    DateTime EndTime = StartTime.AddDays(Convert.ToInt32(strs[0])).AddHours(Convert.ToInt32(strs[1]))
                                       .AddMinutes(Convert.ToInt32(strs[2])).AddSeconds(Convert.ToInt32(strs[3]));

                    string[] pros      = pid.Split("`".ToCharArray());
                    string[] protitles = ptitle.Split("`".ToCharArray());
                    if (pros.Length > 15 || pros.Length <= 0 || protitles.Length > 15 ||
                        protitles.Length <= 0 || pros.Length != protitles.Length)
                    {
                        return;
                    }
                    foreach (string title in protitles)
                    {
                        if (title.Length <= 0 || title.Length > 80)
                        {
                            return;
                        }
                    }
                    Contest contest = new Contest();
                    contest.Title       = ctitle;
                    contest.Type        = psd.Length > 0 ? "private" : "public";
                    contest.Password    = psd;
                    contest.UserID      = uid;
                    contest.StartTime   = StartTime;
                    contest.EndTime     = EndTime;
                    contest.Declaration = dcl;
                    contest.ProsNum     = (uint)pros.Length;

                    uint cid = ContestService.Insert(contest);
                    ContestUserService.Insert(cid, uid);
                    List <ContestProblem> conpros = new List <ContestProblem>();
                    for (int i = 0; i < pros.Length; ++i)
                    {
                        ContestProblem conpro = new ContestProblem();
                        conpro.ContestID = cid;
                        conpro.ProblemID = Convert.ToUInt32(pros[i]);
                        conpro.Title     = protitles[i];
                        conpro.Accepted  = 0;
                        conpro.Submit    = 0;
                        conpro.OrderID   = (char)(i + 'A');
                        conpros.Add(conpro);
                    }
                    ContestProblemService.Insert(conpros);
                    context.Response.Redirect("ContestDo.ashx?action=mlist", false);
                    return;
                }
                #endregion

                #region
                else if (action == "editold")
                {
                    string ctitle = (string)context.Request["ctitle"];
                    string stime  = (string)context.Request["stime"];
                    string tlen   = (string)context.Request["tlen"];
                    string psd    = (string)context.Request["psd"];
                    string dcl    = (string)context.Request["dcl"];
                    string pid    = (string)context.Request["pid"];
                    string ptitle = (string)context.Request["ptitle"];
                    for (int i = 0; i < psd.Length; ++i)
                    {
                        if (IsValidChar(psd[i]) == false)
                        {
                            return;
                        }
                    }
                    if (ctitle.Length > 80 || psd.Length > 24 || dcl.Length > 400)
                    {
                        return;
                    }

                    string   p_stime   = @"(\d\d):(\d\d):(\d\d) (\d\d)/(\d\d)/(\d\d\d\d)";
                    Regex    r_stime   = new Regex(p_stime);
                    Match    match     = r_stime.Match(stime);
                    int      hh        = Convert.ToInt32(match.Groups[1].ToString());
                    int      mm        = Convert.ToInt32(match.Groups[2].ToString());
                    int      ss        = Convert.ToInt32(match.Groups[3].ToString());
                    int      MM        = Convert.ToInt32(match.Groups[4].ToString());
                    int      dd        = Convert.ToInt32(match.Groups[5].ToString());
                    int      yyyy      = Convert.ToInt32(match.Groups[6].ToString());
                    DateTime StartTime = new DateTime(yyyy, MM, dd, hh, mm, ss);
                    string[] strs      = tlen.Split(':');
                    if (Convert.ToInt32(strs[0]) > 999 || Convert.ToInt32(strs[1]) > 23 ||
                        Convert.ToInt32(strs[2]) > 59 || Convert.ToInt32(strs[3]) > 59)
                    {
                        return;
                    }
                    if (Convert.ToInt32(strs[0]) <= 0 && Convert.ToInt32(strs[1]) <= 0 &&
                        Convert.ToInt32(strs[2]) <= 0 && Convert.ToInt32(strs[3]) <= 0)
                    {
                        return;
                    }


                    DateTime EndTime = StartTime.AddDays(Convert.ToInt32(strs[0])).AddHours(Convert.ToInt32(strs[1]))
                                       .AddMinutes(Convert.ToInt32(strs[2])).AddSeconds(Convert.ToInt32(strs[3]));

                    string[] pros      = pid.Split("`".ToCharArray());
                    string[] protitles = ptitle.Split("`".ToCharArray());
                    if (pros.Length > 15 || pros.Length <= 0 || protitles.Length > 15 ||
                        protitles.Length <= 0 || pros.Length != protitles.Length)
                    {
                        return;
                    }
                    foreach (string title in protitles)
                    {
                        if (title.Length <= 0 || title.Length > 80)
                        {
                            return;
                        }
                    }
                    Contest contest = new Contest();
                    contest.Title       = ctitle;
                    contest.Type        = psd.Length > 0 ? "private" : "public";
                    contest.Password    = psd;
                    contest.UserID      = uid;
                    contest.StartTime   = StartTime;
                    contest.EndTime     = EndTime;
                    contest.Declaration = dcl;
                    contest.ProsNum     = (uint)pros.Length;

                    uint cid = Convert.ToUInt32(context.Request["cid"]);
                    contest.ContestID = cid;
                    ContestService.Update(contest);
                    ContestProblemService.DeleteByContestID(contest.ContestID);

                    List <ContestProblem> conpros = new List <ContestProblem>();
                    for (int i = 0; i < pros.Length; ++i)
                    {
                        ContestProblem conpro = new ContestProblem();
                        conpro.ContestID = cid;
                        conpro.ProblemID = Convert.ToUInt32(pros[i]);
                        conpro.Title     = protitles[i];
                        conpro.Accepted  = 0;
                        conpro.Submit    = 0;
                        conpro.OrderID   = (char)(i + 'A');
                        conpros.Add(conpro);
                    }
                    ContestProblemService.Insert(conpros);
                    context.Response.Redirect("ContestDo.ashx?action=mlist", false);
                }
                #endregion

                #region

                /*
                 * ajax
                 * */
                else if (action == "getcompilers")
                {
                    context.Response.ContentType = "text/plain";
                    uint            oid       = (uint)Convert.ToUInt64(context.Request["oid"]);
                    List <Compiler> compilers = CompilerService.SelectByOJ(oid);
                    string          ret       = "";
                    for (int i = 0; i < compilers.Count; ++i)
                    {
                        if (i > 0)
                        {
                            ret += "|";
                        }
                        ret += compilers[i].CompilerID + "&" + compilers[i].Name;
                    }
                    context.Response.Write(ret);
                }
                #endregion

                #region
                else if (action == "submit")
                {
                    uint    conid   = Convert.ToUInt32(context.Request["cid"]);
                    Contest contest = ContestService.SelectByID(conid);
                    if (contest.EndTime <= DateTime.Now || contest.StartTime >= DateTime.Now)
                    {
                        context.Response.Write("<script>alert('Contest is not Running');window.location.href='ContestDo.ashx?action=view&cid=" + conid + "'</script>");
                        return;
                    }
                    string pid  = (string)context.Request["pselect"];
                    uint   cid  = Convert.ToUInt32(context.Request["cselect"]);
                    string code = (string)context.Request["code"];

                    if (code.Length < 50 || code.Length > 65536)
                    {
                        context.Response.Write("<script>alert('The Code is Too Short or Too Long');window.location.href='ContestDo.ashx?action=view&cid=" + conid + "#submit'</script>");
                        return;
                    }

                    string[] strs     = pid.Split('&');
                    Solution solution = new Solution();
                    solution.ContestProblemID = Convert.ToUInt32(strs[0]);
                    solution.CompilerID       = cid;
                    solution.SourceCode       = code;
                    solution.IsJudged         = false;
                    solution.SubmitTime       = DateTime.Now;
                    solution.UserID           = Convert.ToUInt32(uid);
                    SolutionService.Insert(solution);
                    ContestProblemService.UpdateSubmit(solution.ContestProblemID);
                    Problem problem = ContestProblemService.SelectByContestProblemID(solution.ContestProblemID);
                    ProblemService.UpdateSubmit(problem.ProblemID);

                    context.Response.Redirect("ContestDo.ashx?action=view&cid=" + conid + "#status", false);
                }
                #endregion

                #region

                /*
                 * ajax
                 * */
                else if (action == "code")
                {
                    context.Response.ContentType = "text/plain";
                    uint     id       = Convert.ToUInt32(context.Request["sid"]);
                    Solution solution = SolutionService.SelectBySolutionID(id);
                    if (solution.SolutionID == 0)
                    {
                        context.Response.Write("no");
                    }
                    else
                    {
                        context.Response.Write(solution.SourceCode);
                    }
                }
                #endregion

                #region
                else if (action == "edit")
                {
                    uint    cid     = (uint)Convert.ToUInt32(context.Request["cid"]);
                    Contest contest = ContestService.SelectByID(cid);
                    if (DateTime.Now >= contest.StartTime)
                    {
                        context.Response.Write("<script>alert('Contest is Running');window.location.href='ContestDo.ashx?action=mlist'</script>");
                        return;
                    }
                    if (contest.UserID != uid)
                    {
                        return;
                    }
                    else
                    {
                        List <ContestProblem> conpros = ContestProblemService.SelectByContestID(cid);
                        foreach (ContestProblem conpro in conpros)
                        {
                            conpro.Description     = conpro.Input = conpro.Output =
                                conpro.SampleInput = conpro.SampleOutput = conpro.Hint = null;
                        }
                        List <OJ> OJs    = OJService.SelectAll();
                        TimeSpan  Length = contest.EndTime - contest.StartTime;
                        var       Data   = new
                        {
                            OJs    = OJs,
                            edit   = true,
                            pros   = conpros,
                            ID     = contest.ContestID,
                            Title  = contest.Title,
                            Time   = contest.StartTime.ToString("HH:mm:ss MM/dd/yyyy"),
                            Length = contest.EndTime - contest.StartTime,
                            Dec    = contest.Declaration,
                            Psd    = contest.Password
                        };
                        string html = CommonHelper.RenderHtml("contestAdd.html", Data);
                        context.Response.Write(html);
                    }
                }
                #endregion

                #region
                else
                {
                    context.Response.Redirect("index.ashx", false);
                }
                #endregion
            }
            catch (Exception e)
            {
                LogService.Insert(0, e);
                context.Response.Redirect("index.ashx", false);
            }
        }
Example #28
0
 public ProblemsController(ProblemService problemService)
 {
     _problemService = problemService;
 }
Example #29
0
 public HomeController(ProblemService problemService)
 {
     _problemService = problemService;
 }
Example #30
0
        public IActionResult CloseSession(long id, long sessionID)
        {
            var user = UserService.Get(long.Parse(User.Identity.Name));

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

            var problem = ProblemService.Get(id);

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

            var session = SessionService.Get(sessionID);

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

            var wallet = UserWalletService.GetUserWallet(user);

            if (wallet == null)
            {
                return(NotFound(new ResponseModel
                {
                    Success = false,
                    Message = "Кошелек не найден"
                }));
            }

            var specialistWallet = UserWalletService.GetUserWallet(session.Specialist.User);

            if (specialistWallet == null)
            {
                return(NotFound(new ResponseModel
                {
                    Success = false,
                    Message = "Кошелек не найден"
                }));
            }

            if (!session.IsSpecialistClose)
            {
                return(BadRequest(new ResponseModel
                {
                    Success = false,
                    Message = "Сессию не завершил специалист"
                }));
            }

            wallet.Balance -= session.Reward;
            UserWalletService.Update(wallet);

            specialistWallet.Balance += session.Reward;
            UserWalletService.Update(specialistWallet);

            session.IsClientClose   = true;
            session.ClientCloseDate = DateTime.UtcNow;
            session.Status          = SessionStatus.Success;
            SessionService.Update(session);

            var clientActiveSessions = SessionService.GetActiveSessions(session.Problem.User);

            NotificationsService.SendUpdateToUser(
                session.Problem.User.ID,
                SocketMessageType.BalanceUpdate,
                new UserWalletViewModel(wallet, clientActiveSessions.Sum(x => x.Reward)));

            NotificationsService.SendUpdateToUser(
                session.Specialist.ID,
                SocketMessageType.BalanceUpdate,
                new UserWalletViewModel(specialistWallet, 0));

            return(Ok(new ResponseModel()));
        }
Example #31
0
        public IActionResult StartSession(long id, long sessionID)
        {
            var user = UserService.Get(long.Parse(User.Identity.Name));

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

            var problem = ProblemService.Get(id);

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

            var session = SessionService.Get(sessionID);

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

            if (session.Specialist == null)
            {
                return(Ok(new ResponseModel
                {
                    Success = false,
                    Message = "Не выбран специалист"
                }));
            }

            var wallet = UserWalletService.GetUserWallet(user);

            if (wallet == null)
            {
                return(NotFound(new ResponseModel
                {
                    Success = false,
                    Message = "Кошелек не найден"
                }));
            }

            var activeSessions = SessionService.GetActiveSessions(user);
            var lockedBalance  = activeSessions.Sum(x => x.Reward);

            if ((wallet.Balance - lockedBalance) < session.Reward)
            {
                return(Ok(new ResponseModel
                {
                    Success = false,
                    Message = "Недостаточно средств"
                }));
            }

            session.Status = SessionStatus.Started;
            session.Date   = DateTime.UtcNow;

            SessionService.Update(session);

            return(Ok(new ResponseModel()));
        }