protected void Page_Load(object sender, EventArgs e)
 {
     if (Session["ContestID"] != null)
     {
         using (ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler())
         {
             ltlContestName.Text = pcdch.ContestSetting.GetById(Convert.ToInt64(Session["ContestID"].ToString())).Name;
         }
     }
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Admin"] == null)
            Response.Redirect("Default.aspx");
        if (Session["Admin"].ToString() != "Yes")
            Response.Redirect("Default.aspx");
        ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();

        rptSolutions.DataSource = pcdch.Solution.GetAll();
        rptSolutions.DataBind();
    }
 private void Edit(long id)
 {
     ViewState["mode"] = "Edit";
     ViewState["ID"] = id.ToString();
     ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
     ContestSetting pro = pcdch.ContestSetting.GetById(id);
     txtName.Text = pro.Name;
     txtArrangeBy.Text = pro.ArrangedBy;
     txtStartTime.Text = pro.StartTime.ToString();
     txtEndTime.Text = pro.EndTime.ToString();
     cbIsPrivate.Checked = pro.IsPrivate;
     mvProblem.ActiveViewIndex = 1;
 }
    protected void Button1_Click(object sender, EventArgs e)
    {
        ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();

        User user = pcdch.Users.GetByName("Admin");

        user.IPAddress = TextBox1.Text;

        pcdch.ProgrammingContestDatabase.SubmitChanges();

        Session["Admin"] = "NO";

        Response.Redirect("Default.aspx");
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
        string pass = pcdch.Users.GetByName("Admin").IPAddress;

        if (pass == txtPassword.Text)
        {
            Session["Admin"] = "Yes";
            Session.Timeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SESSION_TIMEOUT"]);
            Response.Redirect("JudgeStatus.aspx");
        }
        else
            ltlError.Text = "Wrong Password!!!";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Admin"] == null)
            Response.Redirect("Default.aspx");
        if (Session["Admin"].ToString() != "Yes")
            Response.Redirect("Default.aspx");

        if (!IsPostBack)
        {
            ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
            rptProblems.DataSource = pcdch.Users.GetAllWithOutAdmin();
            rptProblems.DataBind();
        }
    }
    private void ReJudge(long id)
    {
        ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
        Solution solution = pcdch.Solution.GetById(id);
        solution.Result = pcdch.Result.GetByName("Pending");
        solution.ResultId = pcdch.Result.GetByName("Pending").ID;

        string rejudge = "";
        string path = Server.MapPath("../Solution");
        path += "\\" + solution.UserId.ToString();
        path += "\\" + solution.ProblemId.ToString();
        path += "\\" + solution.ID.ToString();
        rejudge = path;
        path += "\\" + solution.FileName;

        Problem prob = pcdch.Problems.GetById(solution.ProblemId);

        string inputJudgeFile = Server.MapPath("../JudgeSolution");
        inputJudgeFile += "\\" + prob.ID.ToString() + "\\" + prob.InputFile;
        FileInfo rrr1 = new FileInfo(inputJudgeFile);

        pcdch.ProgrammingContestDatabase.SubmitChanges();

        if (rrr1.Exists)
        {
            FileInfo fi = new FileInfo(path);
            string contestInputFile = rejudge + "\\" + prob.InputFile;
            rrr1.CopyTo(contestInputFile, true);
            string contestOutputFile = rejudge + "\\" + prob.OutputFile;

            string outputJudgeFile = Server.MapPath("../JudgeSolution");
            outputJudgeFile += "\\" + prob.ID.ToString() + "\\" + prob.OutputFile;

            rrr1 = new FileInfo(outputJudgeFile);

            if (rrr1.Exists)
            {
                Judgement judge = new Judgement(path, contestOutputFile, contestInputFile, outputJudgeFile, solution.ID, prob.ID);

                JudgeManager.Instance.AddSolution(judge);
                //Thread thread = new Thread(judge.GoToJudgement);
                //thread.Start();
            }
        }
        Response.Redirect(HttpContext.Current.Request.Url.ToString());
    }
 protected void ddlSelectContest_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (ViewState["mode"].ToString() == "Add")
     {
         CheckBox1.Checked = false;
     }
     else if (ViewState["mode"].ToString() == "Edit")
     {
         long contestId = Convert.ToInt64(ddlSelectContest.SelectedValue);
         long userId = Convert.ToInt64(ViewState["ID"].ToString());
         ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
         if (pcdch.ContestPermission.GetByUserIdAndContestId(userId, contestId) == null)
             CheckBox1.Checked = false;
         else
             CheckBox1.Checked = true;
     }
 }
    private void Save()
    {
        if (ViewState["mode"].ToString() == "Add")
        {
            ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
            Data.User user = new Data.User();
            user.Name = txtName.Text;
            user.IPAddress = txtIPAddress.Text;
            pcdch.ProgrammingContestDatabase.Users.InsertOnSubmit(user);
            pcdch.ProgrammingContestDatabase.SubmitChanges();

            user = pcdch.Users.GetByName(txtName.Text);

            long contestId = Convert.ToInt64(ddlSelectContest.SelectedValue);

            if (CheckBox1.Checked == true)
            {
                if (pcdch.ContestPermission.GetByUserIdAndContestId(user.ID, contestId) == null)
                {
                    ContestPermission cp = new ContestPermission();
                    cp.ContestSetting = pcdch.ContestSetting.GetById(contestId);
                    cp.ContestId = contestId;
                    cp.User = user;
                    cp.UserId = user.ID;
                    pcdch.ProgrammingContestDatabase.ContestPermissions.InsertOnSubmit(cp);
                }
            }
            else
            {
                if (pcdch.ContestPermission.GetByUserIdAndContestId(user.ID, contestId) != null)
                {
                    ContestPermission cp = pcdch.ContestPermission.GetByUserIdAndContestId(user.ID, contestId);
                    pcdch.ProgrammingContestDatabase.ContestPermissions.DeleteOnSubmit(cp);
                }
            }

            pcdch.ProgrammingContestDatabase.SubmitChanges();
            rptProblems.DataSource = pcdch.Users.GetAllWithOutAdmin();
            rptProblems.DataBind();

        }
        else if (ViewState["mode"].ToString() == "Edit")
        {
            ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
            Data.User user = pcdch.Users.GetById(Convert.ToInt64(ViewState["ID"].ToString()));
            user.Name = txtName.Text;
            user.IPAddress = txtIPAddress.Text;
            pcdch.ProgrammingContestDatabase.SubmitChanges();

            user = pcdch.Users.GetByName(txtName.Text);

            long contestId = Convert.ToInt64(ddlSelectContest.SelectedValue);

            if (CheckBox1.Checked == true)
            {
                if (pcdch.ContestPermission.GetByUserIdAndContestId(user.ID, contestId) == null)
                {
                    ContestPermission cp = new ContestPermission();
                    cp.ContestSetting = pcdch.ContestSetting.GetById(contestId);
                    cp.ContestId = contestId;
                    cp.User = user;
                    cp.UserId = user.ID;
                    pcdch.ProgrammingContestDatabase.ContestPermissions.InsertOnSubmit(cp);
                }
            }
            else
            {
                if (pcdch.ContestPermission.GetByUserIdAndContestId(user.ID, contestId) != null)
                {
                    ContestPermission cp = pcdch.ContestPermission.GetByUserIdAndContestId(user.ID, contestId);
                    pcdch.ProgrammingContestDatabase.ContestPermissions.DeleteOnSubmit(cp);
                }
            }

            pcdch.ProgrammingContestDatabase.SubmitChanges();
            rptProblems.DataSource = pcdch.Users.GetAllWithOutAdmin();
            rptProblems.DataBind();
        }

        mvProblem.ActiveViewIndex = 0;
    }
    private Ranks GetYourRank(string userName, ProgrammingContestDataContextHandler pcdch)
    {
        long contestId = Convert.ToInt64(Session["ContestID"]);
        List<User> users = pcdch.Users.GetAll();
        List<Ranks> ranks = new List<Ranks>();
        long i = 1;
        long acceptId = pcdch.Result.GetByName("Accept").ID;
        long notTry = pcdch.Result.GetByName("Not Try").ID;

        foreach (User u in users)
            if (pcdch.ContestPermission.GetByUserIdAndContestId(u.ID, contestId) != null)
            {
                Ranks rank = new Ranks();
                rank.Name = u.Name;
                rank.Position = i;
                i++;
                rank.Solved = 0;
                List<Problem> pro1 = pcdch.Problems.GetByContestId(Convert.ToInt64(Session["ContestID"]));
                List<ProblemTry> ppp1 = new List<ProblemTry>();
                foreach (Problem p1 in pro1)
                {
                    ProblemTry pblm = new ProblemTry();
                    pblm.Name = p1.PNumber;
                    List<Solution> so = pcdch.Solution.GetByProblemIdAndUserId(p1.ID, u.ID);
                    pblm.NumberOfSubmission = 0;
                    pblm.ResultId = notTry;
                    if (so.Count != 0)
                    {
                        pblm.NumberOfSubmission = so.Count;
                        foreach (Solution s in so)
                        {
                            if (s.ResultId == acceptId)
                            {
                                if (pblm.ResultId != acceptId)
                                {
                                    pblm.ResultId = s.ResultId;
                                    if (rank.Solved == 0)
                                        rank.LastTimeOfAc = s.time;
                                    else if (rank.LastTimeOfAc < s.time)
                                        rank.LastTimeOfAc = s.time;
                                    rank.Solved++;
                                }
                            }
                            else if (pblm.ResultId != acceptId)
                            {
                                pblm.ResultId = s.ResultId;
                            }
                        }
                    }
                    ppp1.Add(pblm);
                }
                rank.Problem = ppp1;
                ranks.Add(rank);
            }

        Sort st = new Sort();

        ranks = st.RanksSort(ranks);

        foreach (Ranks ra21 in ranks)
            if (ra21.Name == userName)
            {
                return ra21;
            }

        return null;
    }
 private void Edit(long id)
 {
     ViewState["mode"] = "Edit";
     ViewState["ID"] = id.ToString();
     ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
     Problem pro = pcdch.Problems.GetById(id);
     txtNumber.Text = pro.PNumber;
     txtName.Text = pro.PName;
     fckEntryContent.Value = pro.Statement;
     txtTime.Text = pro.Time.ToString();
     txtInput.Text = pro.InputFile;
     txtOutput.Text = pro.OutputFile;
     LoadDdlForEdit(pcdch);
     ddlSelectContest.SelectedValue = pro.ContestID.ToString();
     mvProblem.ActiveViewIndex = 1;
 }
    private void LoadDdlForEdit(ProgrammingContestDataContextHandler pcdch)
    {
        ddlSelectContest.Items.Clear();
        List<ContestSetting> csAll = pcdch.ContestSetting.GetAll();

        long id = 1;

        foreach (ContestSetting cs in csAll)
        {
            ddlSelectContest.Items.Add(new ListItem(cs.Name, cs.ID.ToString()));
            id = cs.ID;
        }

        ddlSelectContest.SelectedValue = id.ToString();
    }
    private void Save()
    {
        if (ViewState["mode"].ToString() == "Add")
        {
            ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
            Problem pro = new Problem();
            pro.PNumber = txtNumber.Text;
            pro.PName = txtName.Text;
            pro.Statement = fckEntryContent.Value;
            pro.Time = Convert.ToInt64(txtTime.Text);
            pro.ContestSetting = pcdch.ContestSetting.GetById(Convert.ToInt64(ddlSelectContest.SelectedValue));
            pro.ContestID = Convert.ToInt64(ddlSelectContest.SelectedValue);

            if (fuInput.FileName != null && fuInput.FileName != "")
            {
                pro.InputFile = fuInput.FileName;

                string inputJudgeFile = Server.MapPath("../JudgeSolution");
                inputJudgeFile += "\\" + pro.ID.ToString();

                DirectoryInfo di = new DirectoryInfo(inputJudgeFile);

                if (!di.Exists)
                    di.Create();
                inputJudgeFile += "\\" + pro.InputFile;

                FileInfo fi = new FileInfo(inputJudgeFile);

                if (fi.Exists)
                    fi.Delete();

                fuInput.SaveAs(inputJudgeFile);

                FileInfo fiRead = new FileInfo(inputJudgeFile);
                string input = "";

                if (fiRead.Exists)
                    input = File.ReadAllText(inputJudgeFile);

                pro.Input = input;
            }
            else
                pro.InputFile = " ";

            if (fuOutput.FileName != null && fuOutput.FileName != "")
            {
                pro.OutputFile = fuOutput.FileName;

                string outputJudgeFile = Server.MapPath("../JudgeSolution");
                outputJudgeFile += "\\" + pro.ID.ToString();

                DirectoryInfo di = new DirectoryInfo(outputJudgeFile);

                if (!di.Exists)
                    di.Create();
                outputJudgeFile += "\\" + pro.OutputFile;

                FileInfo fi = new FileInfo(outputJudgeFile);

                if (fi.Exists)
                    fi.Delete();

                fuOutput.SaveAs(outputJudgeFile);

                FileInfo fiRead = new FileInfo(outputJudgeFile);
                string input = "";

                if (fiRead.Exists)
                    input = File.ReadAllText(outputJudgeFile);

                pro.Output = input;
            }
            else
                pro.OutputFile = " ";

            pcdch.ProgrammingContestDatabase.Problems.InsertOnSubmit(pro);
            pcdch.ProgrammingContestDatabase.SubmitChanges();
            rptProblems.DataSource = pcdch.Problems.GetAll();
            rptProblems.DataBind();

        }
        else if (ViewState["mode"].ToString() == "Edit")
        {
            ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
            Problem pro = pcdch.Problems.GetById(Convert.ToInt64(ViewState["ID"].ToString()));
            pro.PNumber = txtNumber.Text;
            pro.PName = txtName.Text;
            pro.Statement = fckEntryContent.Value;
            pro.Time = Convert.ToInt64(txtTime.Text);
            pro.ContestSetting = pcdch.ContestSetting.GetById(Convert.ToInt64(ddlSelectContest.SelectedValue));
            pro.ContestID = Convert.ToInt64(ddlSelectContest.SelectedValue);

            if (fuInput.FileName != null && fuInput.FileName != "")
            {
                pro.InputFile = fuInput.FileName;

                string inputJudgeFile = Server.MapPath("../JudgeSolution");
                inputJudgeFile += "\\" + pro.ID.ToString();

                DirectoryInfo di = new DirectoryInfo(inputJudgeFile);

                if (!di.Exists)
                    di.Create();
                inputJudgeFile += "\\" + pro.InputFile;

                FileInfo fi = new FileInfo(inputJudgeFile);

                if (fi.Exists)
                    fi.Delete();

                fuInput.SaveAs(inputJudgeFile);

                FileInfo fiRead = new FileInfo(inputJudgeFile);
                string input = "";

                if (fiRead.Exists)
                    input = File.ReadAllText(inputJudgeFile);

                pro.Input = input;
            }

            if (fuOutput.FileName != null && fuOutput.FileName != "")
            {
                pro.OutputFile = fuOutput.FileName;

                string outputJudgeFile = Server.MapPath("../JudgeSolution");
                outputJudgeFile += "\\" + pro.ID.ToString();

                DirectoryInfo di = new DirectoryInfo(outputJudgeFile);

                if (!di.Exists)
                    di.Create();
                outputJudgeFile += "\\" + pro.OutputFile;

                FileInfo fi = new FileInfo(outputJudgeFile);

                if (fi.Exists)
                    fi.Delete();

                fuOutput.SaveAs(outputJudgeFile);

                FileInfo fiRead = new FileInfo(outputJudgeFile);
                string input = "";

                if (fiRead.Exists)
                    input = File.ReadAllText(outputJudgeFile);

                pro.Output = input;
            }

            pcdch.ProgrammingContestDatabase.SubmitChanges();
            rptProblems.DataSource = pcdch.Problems.GetAll();
            rptProblems.DataBind();
        }

        mvProblem.ActiveViewIndex = 0;
    }
 private void Delete(long id)
 {
     ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
     Problem pa = pcdch.Problems.GetById(id);
     pcdch.ProgrammingContestDatabase.Problems.DeleteOnSubmit(pa);
     rptProblems.DataSource = pcdch.Problems.GetAll();
     rptProblems.DataBind();
 }
    private void Save()
    {
        if (ViewState["mode"].ToString() == "Add")
        {
            ContestSetting cs = new ContestSetting();
            cs.Name = txtName.Text;
            cs.ArrangedBy = txtArrangeBy.Text;
            cs.StartTime = Convert.ToDateTime(txtStartTime.Text);
            cs.EndTime = Convert.ToDateTime(txtEndTime.Text);
            cs.IsPrivate = cbIsPrivate.Checked;

            ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
            pcdch.ProgrammingContestDatabase.ContestSettings.InsertOnSubmit(cs);
            pcdch.ProgrammingContestDatabase.SubmitChanges();

            rptProblems.DataSource = pcdch.ContestSetting.GetAll();
            rptProblems.DataBind();

        }
        else if (ViewState["mode"].ToString() == "Edit")
        {
            ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
            ContestSetting cs = pcdch.ContestSetting.GetById(Convert.ToInt64(ViewState["ID"].ToString()));
            cs.Name = txtName.Text;
            cs.ArrangedBy = txtArrangeBy.Text;
            cs.StartTime = Convert.ToDateTime(txtStartTime.Text);
            cs.EndTime = Convert.ToDateTime(txtEndTime.Text);
            cs.IsPrivate = cbIsPrivate.Checked;

            pcdch.ProgrammingContestDatabase.SubmitChanges();

            rptProblems.DataSource = pcdch.ContestSetting.GetAll();
            rptProblems.DataBind();
        }

        mvProblem.ActiveViewIndex = 0;
    }
 protected void Page_Load(object sender, EventArgs e)
 {
     ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
     rptContest.DataSource = pcdch.ContestSetting.GetAll();
     rptContest.DataBind();
 }
 private void LoadProblem(long id, ProgrammingContestDataContextHandler pcdch)
 {
     Problem pr = pcdch.Problems.GetById(id);
     ltlProblemTitle.Text = "Problem " + pr.PNumber + "<br/>" + pr.PName + "<br/>" + "Time Limit: " + pr.Time + " sec<br />";
     ltlProblemStatement.Text = pr.Statement;
     ViewState["ProblemId"] = id.ToString();
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["ContestID"] == null)
            Response.Redirect("Default.aspx");
        ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
        List<Problem> problem = pcdch.Problems.GetByContestId(Convert.ToInt64(Session["ContestID"]));

        ContestSetting cs = pcdch.ContestSetting.GetById(Convert.ToInt64(Session["ContestID"]));

        if (DateTime.Now > cs.EndTime)
        {
            _isCodePublished = true;
        }
        else
            _isCodePublished = false;

        _acceptId = pcdch.Result.GetByName("Accept").ID;
        _allResult = pcdch.Result.GetAll();

        ltlProblemName.Text = "<td style=\"width:150px\"></td>";

        foreach (Problem p in problem)
        {
            ltlProblemName.Text += "<td style=\"width:150px\">" + p.PNumber + "</td>";
        }

        ltlProblemName.Text += "<td style=\"width:150px\">Total Solved</td>";

        long contestId = Convert.ToInt64(Session["ContestID"]);
        List<User> users = pcdch.Users.GetAll();
        List<Ranks> ranks = new List<Ranks>();
        long i = 1;
        long acceptId = pcdch.Result.GetByName("Accept").ID;
        long notTry = pcdch.Result.GetByName("Not Try").ID;
        foreach (User u in users)
            if (pcdch.ContestPermission.GetByUserIdAndContestId(u.ID, contestId) != null)
            {
                Ranks rank = new Ranks();
                rank.Name = u.Name;
                rank.Position = i;
                i++;
                rank.Solved = 0;
                List<Problem> pro1 = pcdch.Problems.GetByContestId(Convert.ToInt64(Session["ContestID"]));
                List<ProblemTry> ppp1 = new List<ProblemTry>();
                foreach (Problem p1 in pro1)
                {
                    ProblemTry pblm = new ProblemTry();
                    pblm.Name = p1.PNumber;
                    List<Solution> so = pcdch.Solution.GetByProblemIdAndUserId(p1.ID, u.ID);
                    pblm.NumberOfSubmission = 0;
                    pblm.ResultId = notTry;
                    if (so.Count != 0)
                    {
                        pblm.NumberOfSubmission = so.Count;
                        foreach (Solution s in so)
                        {
                            if (s.ResultId == acceptId)
                            {
                                if (pblm.ResultId != acceptId)
                                {
                                    pblm.ResultId = s.ResultId;
                                    pblm.RequireTime = s.RequireTime;

                                    if (s.SolutionFileName != null)
                                        pblm.SourceFilePath = s.SolutionFileName;

                                    if (rank.Solved == 0)
                                        rank.LastTimeOfAc = s.time;
                                    else if (rank.LastTimeOfAc < s.time)
                                        rank.LastTimeOfAc = s.time;
                                    rank.Solved++;
                                }
                                else if (s.SolutionFileName != null)
                                    pblm.SourceFilePath = s.SolutionFileName;
                            }
                            else if (pblm.ResultId != acceptId)
                            {
                                if (s.SolutionFileName != null)
                                    pblm.SourceFilePath = s.SolutionFileName;
                                pblm.ResultId = s.ResultId;
                            }
                        }
                    }
                    ppp1.Add(pblm);
                }
                rank.Problem = ppp1;
                ranks.Add(rank);
            }

        Sort st = new Sort();

        rptProblems.DataSource = st.RanksSort(ranks);
        rptProblems.DataBind();
    }
    private void Show(long id)
    {
        listbJudge.Items.Clear();
        listbSolver.Items.Clear();
        ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
        Solution sol = pcdch.Solution.GetById(id);
        Problem pro = pcdch.Problems.GetById(sol.ProblemId);

        string path = Server.MapPath("../Solution");
        path += "\\" + sol.UserId.ToString();
        path += "\\" + sol.ProblemId.ToString();
        path += "\\" + sol.ID.ToString();
        path += "\\" + pro.OutputFile;

        string outputJudgeFile = Server.MapPath("../JudgeSolution");
        outputJudgeFile += "\\" + pro.ID.ToString() + "\\" + pro.OutputFile;

        if (pro.Output == null || pro.Output == "")
        {
            FileInfo fiRead = new FileInfo(outputJudgeFile);
            string input = "";

            if (fiRead.Exists)
                input = File.ReadAllText(outputJudgeFile);

            pro.Output = input;
            pcdch.ProgrammingContestDatabase.SubmitChanges();
        }

        string[] judgeOutput = pro.Output.Split('\n');
        listbJudge.Items.Clear();

        for (int i = 0; i < judgeOutput.Length; i++)
        {
            listbJudge.Items.Add(new ListItem(judgeOutput[i], i.ToString()));
        }

        //StreamReader sr = new StreamReader(outputJudgeFile);
        //int i = 0;

        //while (sr.Peek() != -1)
        //{
        //    listbJudge.Items.Add(new ListItem(sr.ReadLine(), i.ToString()));
        //    i++;
        //}

        //sr.Close();

        if (sol.Output == null)
        {
            FileInfo fiRead = new FileInfo(path);
            string input = "";

            if (fiRead.Exists)
                input = File.ReadAllText(path);

            sol.Output = input;
            pcdch.ProgrammingContestDatabase.SubmitChanges();
        }

        string[] solutionOutput = sol.Output.Split('\n');
        listbSolver.Items.Clear();

        for (int i = 0; i < solutionOutput.Length; i++)
        {
            listbSolver.Items.Add(new ListItem(solutionOutput[i], i.ToString()));
        }

        //sr = new StreamReader(path);
        //i = 0;
        //while (sr.Peek() != -1)
        //{
        //    listbSolver.Items.Add(new ListItem(sr.ReadLine(), i.ToString()));
        //    i++;
        //}

        //sr.Close();

        if (listbJudge.Items.Count > 0)
            listbJudge.SelectedIndex = 0;

        if (listbSolver.Items.Count > 0)
            listbSolver.SelectedIndex = 0;

        mvStatus.ActiveViewIndex = 1;
    }
    private void RunningJudgeMent()
    {
        Thread thread = null;
        long limit = 0;
        long start = 0;
        while (true)
        {
            if (thread != null)
            {
                if (thread.IsAlive == false)
                {
                    thread = null;
                    allSolution.RemoveAt(0);
                }
                else if (limit < start)
                {
                    try
                    {
                        thread.Abort();
                    }
                    catch
                    { }

                    thread = null;

                    using (ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler())
                    {
                        Solution so = pcdch.Solution.GetById(allSolution[0].SoluTionID);
                        long resultId = pcdch.Result.GetByName("Crash").ID;
                        so.Result = pcdch.Result.GetByName("Crash");
                        so.ResultId = resultId;
                        pcdch.ProgrammingContestDatabase.SubmitChanges();
                    }

                    allSolution.RemoveAt(0);
                }
                else
                    start += 1000;
            }
            else if (allSolution.Count > 0)
            {
                start = 0;

                using (ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler())
                {
                    Problem problem = pcdch.Problems.GetById(allSolution[0].ProBlemsID);
                    limit = problem.Time * 1000 + 5 * 1000;
                }

                thread = new Thread(allSolution[0].GoToJudgement);
                thread.Start();
            }

            Thread.Sleep(1000);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["ContestID"] == null)
            Response.Redirect("Default.aspx");

        ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
        _acceptId = pcdch.Result.GetByName("Accept").ID;

        if (Session["User"] == null)
        {
            string ip = Request.Params["REMOTE_ADDR"].ToString();
            User user = pcdch.Users.GetByIPAddress(ip);

            if (user != null)
            {
                if (pcdch.ContestPermission.GetByUserIdAndContestId(user.ID, Convert.ToInt64(Session["ContestID"].ToString())) == null)
                    user = null;
            }

            if (user == null)
                divSubmit.Visible = false;
            else
            {
                Session["User"] = user.Name.ToString();
                Session.Timeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SESSION_TIMEOUT"]);
            }
        }
        else
        {
            User user = pcdch.Users.GetByName(Session["User"].ToString());

            if (pcdch.ContestPermission.GetByUserIdAndContestId(user.ID, Convert.ToInt64(Session["ContestID"].ToString())) == null)
            {
                user = null;
            }

            if (user == null)
            {
                Session["User"] = null;
                divSubmit.Visible = false;
            }
        }

        ContestSetting contestSetting = pcdch.ContestSetting.GetById(Convert.ToInt64(Session["ContestID"].ToString()));
        DateTime nowDateTime = DateTime.Now;

        if (contestSetting.IsPrivate == true)
        {
            if (Session["User"] == null)
                Response.Redirect("Rank.aspx");
        }

        if (nowDateTime >= contestSetting.StartTime && nowDateTime <= contestSetting.EndTime)
        { }
        else
            divSubmit.Visible = false;

        if (nowDateTime < contestSetting.StartTime)
            Response.Redirect("Rank.aspx");

        rptProblems.DataSource = pcdch.Problems.GetByContestId(Convert.ToInt64(Session["ContestID"].ToString()));
        rptProblems.DataBind();

        string problem = "";
        try
        {
            problem = Request.QueryString["problem"].Replace("'", string.Empty).Replace("\"", string.Empty);
        }
        catch (Exception)
        {
            problem = "";
        }

        long problemId = 0;

        if (problem != "")
            problemId = Convert.ToInt64(problem);
        else
        {
            if (pcdch.Problems.GetByContestId(Convert.ToInt64(Session["ContestID"].ToString())).Count != 0)
                problemId = pcdch.Problems.GetByContestId(Convert.ToInt64(Session["ContestID"].ToString()))[0].ID;
            else
                Response.Redirect("Rank.aspx");
        }

        LoadProblem(problemId, pcdch);

        if (Session["User"] != null)
        {
            long userId = pcdch.Users.GetByName(Session["User"].ToString()).ID;

            rptResults.DataSource = pcdch.Solution.GetByProblemIdAndUserId(problemId, userId);
            rptResults.DataBind();
            ltlUpper.Text = "Welcome " + Session["User"].ToString() + "<br/>";
            Ranks rank = GetYourRank(Session["User"].ToString(), pcdch);
            ltlUpper.Text += "Your rank : " + rank.Position + " and you solved : " + rank.Solved + " problem(s)<br />";
        }
        else
            ltlUpper.Text = "Welcome Guest" + "<br/>";
    }
    public void GoToJudgement()
    {
        long start = 0;

        try
        {
            Process p = new Process();

            ProcessStartInfo psI = new ProcessStartInfo(ExePath);
            psI.UseShellExecute = false;
            psI.RedirectStandardInput = true;
            psI.RedirectStandardOutput = true;
            psI.RedirectStandardError = true;
            psI.CreateNoWindow = true;
            p.StartInfo = psI;
            p.EnableRaisingEvents = true;
            p.Exited += new EventHandler(this.myProcess_Exited);
            p.Start();

            p.MaxWorkingSet = (IntPtr)(1024 * 1024 * 32);

            sw = p.StandardInput;
            sr = p.StandardOutput;
            err = p.StandardError;

            string input = "";
            long limit = 0;

            using (ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler())
            {
                Problem problem = pcdch.Problems.GetById(ProBlemsID);

                if (problem.Input == null || problem.Input == "")
                {
                    FileInfo fi = new FileInfo(InputFile);

                    if (fi.Exists)
                        input = File.ReadAllText(InputFile);
                    else
                        input = "";

                    problem.Input = input;
                    pcdch.ProgrammingContestDatabase.SubmitChanges();
                }
                else
                    input = problem.Input;

                limit = problem.Time * 1000;
            }

            sw.Write(input);
            sw.Close();

            int id = p.Id;

            eventHandled = false;

            const int SLEEP_AMOUNT = 100;

            while (!p.HasExited)
            {
                start += SLEEP_AMOUNT;
                if (start > limit)
                {
                    break;
                }
                Thread.Sleep(SLEEP_AMOUNT);
                p.Refresh();
            }

            if (start <= limit)
            {
                Thread.Sleep(1000);
                File.WriteAllText(OutputFile, output);

                using (ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler())
                {
                    Solution solution = pcdch.Solution.GetById(SoluTionID);
                    solution.Output = output;
                    pcdch.ProgrammingContestDatabase.SubmitChanges();
                }

                FileInfo fi1 = new FileInfo(OutputFile);

                using (ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler())
                {
                    Solution solution = pcdch.Solution.GetById(SoluTionID);

                    if (fi1.Exists)
                    {
                        bool result = FileCompare(OutputFile, JudgeOutputFile);

                        if (result == true)
                        {
                            long resultId = pcdch.Result.GetByName("Accept").ID;
                            solution.Result = pcdch.Result.GetByName("Accept");
                            solution.ResultId = resultId;
                        }
                        else
                        {
                            long resultId = pcdch.Result.GetByName("Wrong Answer").ID;
                            solution.Result = pcdch.Result.GetByName("Wrong Answer");
                            solution.ResultId = resultId;
                        }
                    }
                    else
                    {
                        long resultId = pcdch.Result.GetByName("Output File Not Created").ID;
                        solution.Result = pcdch.Result.GetByName("Output File Not Created");
                        solution.ResultId = resultId;
                    }

                    solution.RequireTime = Convert.ToDouble(Convert.ToDouble(start) / 1000);
                    pcdch.ProgrammingContestDatabase.SubmitChanges();
                }
            }
            else
            {
                try
                {
                    System.Diagnostics.Process pro = System.Diagnostics.Process.GetProcessById(id);
                    pro.Kill();
                }
                catch (Exception)
                {
                }

                using (ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler())
                {
                    Solution solution = pcdch.Solution.GetById(SoluTionID);
                    solution.Output = output;
                    File.WriteAllText(OutputFile, output);
                    long resultId = pcdch.Result.GetByName("Time Limit Exit").ID;
                    solution.Result = pcdch.Result.GetByName("Time Limit Exit");
                    solution.ResultId = resultId;
                    solution.RequireTime = Convert.ToDouble(Convert.ToDouble(start) / 1000);
                    pcdch.ProgrammingContestDatabase.SubmitChanges();
                }
            }

            p.Close();
            sr.Close();
            err.Close();
        }
        catch
        {
            using (ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler())
            {
                Solution solution = pcdch.Solution.GetById(SoluTionID);
                long resultId = pcdch.Result.GetByName("Crash").ID;
                solution.Result = pcdch.Result.GetByName("Crash");
                solution.ResultId = resultId;

                solution.RequireTime = Convert.ToDouble(Convert.ToDouble(start) / 1000);
                pcdch.ProgrammingContestDatabase.SubmitChanges();
            }
        }
    }
    private bool FileCompare(string file1, string file2)
    {
        if (file1 == file2)
            return true;

        string solutionOutput = "";
        string problemOutput = "";

        using (ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler())
        {
            Problem problem = pcdch.Problems.GetById(ProBlemsID);

            if (problem.Output == null || problem.Output == "")
            {
                FileInfo fiRead = new FileInfo(file2);
                string input = "";

                if (fiRead.Exists)
                    input = File.ReadAllText(file2);

                problem.Output = input;

                pcdch.ProgrammingContestDatabase.SubmitChanges();
            }

            problemOutput = problem.Output;

            Solution solution = pcdch.Solution.GetById(SoluTionID);
            solutionOutput = solution.Output;
        }

        Boolean result = true;

        string[] fileOne = solutionOutput.Replace("\r\n","\n").Split('\n');
        string[] fileTwo = problemOutput.Replace("\r\n", "\n").Split('\n');
        int currentOne = 0;
        int currentTwo = 0;

        string line1 = fileOne[currentOne];
        string line2 = fileTwo[currentTwo];
        int lastIndex = -1;

        if (line1 != line2)
            result = false;

        if (result == true)
        {
            while (line1 != null || line2 != null)
            {
                currentOne++;
                currentTwo++;

                if (currentOne < fileOne.Length)
                    line1 = fileOne[currentOne];
                else
                    line1 = null;

                if (currentTwo < fileTwo.Length)
                    line2 = fileTwo[currentTwo];
                else
                    line2 = null;

                if (line1 != null)
                    while (line1.EndsWith(" "))
                    {
                        lastIndex = line1.Length - 1;
                        line1 = line1.Remove(lastIndex, 1);
                    }

                if (line2 != null)
                    while (line2.EndsWith(" "))
                    {
                        lastIndex = line2.Length - 1;
                        line2 = line2.Remove(lastIndex, 1);
                    }

                if (line1 != line2)
                {
                    if ((line1 == null && line2 == "") || (line1 == "" && line2 == null))
                        continue;

                    result = false;
                    break;
                }
            }
        }

        //fileOne.Close();
        //fileTwo.Close();

        return result;
    }
    private void Edit(long id)
    {
        ViewState["mode"] = "Edit";
        ViewState["ID"] = id.ToString();
        ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
        User pro = pcdch.Users.GetById(id);
        txtName.Text = pro.Name;
        txtIPAddress.Text = pro.IPAddress;
        LoadDdlForEdit(pcdch);

        if (pcdch.ContestPermission.GetByUserIdAndContestId(pro.ID, Convert.ToInt64(ddlSelectContest.SelectedValue)) != null)
            CheckBox1.Checked = true;
        else
            CheckBox1.Checked = false;

            mvProblem.ActiveViewIndex = 1;
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        ProgrammingContestDataContextHandler pcdch = new ProgrammingContestDataContextHandler();
        ContestSetting contestSetting = pcdch.ContestSetting.GetById(Convert.ToInt64(Session["ContestID"].ToString()));
        DateTime nowDateTime = DateTime.Now;

        if (nowDateTime >= contestSetting.StartTime && nowDateTime <= contestSetting.EndTime)
        {
            if (fuSubmit.FileName.ToLower().EndsWith(".exe"))
            {
                Solution solution = new Solution();
                solution.FileName = fuSubmit.FileName;
                solution.ContestId = Convert.ToInt64(Session["ContestID"].ToString());
                solution.Problem = pcdch.Problems.GetById(Convert.ToInt64(ViewState["ProblemId"].ToString()));
                solution.ProblemId = Convert.ToInt64(ViewState["ProblemId"].ToString());
                solution.time = DateTime.Now;
                solution.User = pcdch.Users.GetByName(Session["User"].ToString());
                solution.UserId = pcdch.Users.GetByName(Session["User"].ToString()).ID;
                solution.Result = pcdch.Result.GetByName("Pending");
                solution.ResultId = pcdch.Result.GetByName("Pending").ID;

                pcdch.ProgrammingContestDatabase.Solutions.InsertOnSubmit(solution);
                pcdch.ProgrammingContestDatabase.SubmitChanges();

                string path = Server.MapPath("Solution");
                path += "\\" + solution.UserId.ToString();
                DirectoryInfo df = new DirectoryInfo(path);

                if (!df.Exists)
                    df.Create();

                path += "\\" + solution.ProblemId.ToString();

                df = new DirectoryInfo(path);

                if (!df.Exists)
                    df.Create();

                path += "\\" + solution.ID.ToString();

                df = new DirectoryInfo(path);

                if (!df.Exists)
                    df.Create();

                string codePath = path + "\\" + fuCode.FileName;
                path += "\\" + solution.FileName;
                FileInfo fi = new FileInfo(path);

                if (fi.Exists)
                    fi.Delete();
                fuSubmit.SaveAs(path);
                fuCode.SaveAs(codePath);

                solution.SolutionFileName = "Solution" + "/" + solution.UserId.ToString() + "/" + solution.ProblemId.ToString() + "/" + solution.ID.ToString() + "/" + fuCode.FileName;
                pcdch.ProgrammingContestDatabase.SubmitChanges();

                Problem prob = pcdch.Problems.GetById(solution.ProblemId);

                string inputJudgeFile = Server.MapPath("JudgeSolution");
                inputJudgeFile += "\\" + prob.ID.ToString() + "\\" + prob.InputFile;
                FileInfo rrr1 = new FileInfo(inputJudgeFile);

                if (rrr1.Exists)
                {
                    fi = new FileInfo(path);
                    string contestInputFile = fi.DirectoryName + "\\" + prob.InputFile;
                    rrr1.CopyTo(contestInputFile, true);
                    string contestOutputFile = fi.DirectoryName + "\\" + prob.OutputFile;

                    string outputJudgeFile = Server.MapPath("JudgeSolution");
                    outputJudgeFile += "\\" + prob.ID.ToString() + "\\" + prob.OutputFile;

                    rrr1 = new FileInfo(outputJudgeFile);

                    if (rrr1.Exists)
                    {
                        Judgement judge = new Judgement(path, contestOutputFile, contestInputFile, outputJudgeFile, solution.ID, prob.ID);

                        JudgeManager.Instance.AddSolution(judge);
                        //Thread thread = new Thread(judge.GoToJudgement);
                        //thread.Start();

                    }
                }

                Response.Redirect(HttpContext.Current.Request.Url.ToString());
            }
            else
                ltlErrorMessage.Text = "*You have to select an exe file.";
        }
        else
            Response.Redirect("Rank.aspx");
    }