Exemple #1
0
        private static void SaveProblem(byte[] Data, out int ProblemID, out DateTime LastModifiedTime)
        {
            Int32  FileNameLength = BitConverter.ToInt32(Data, 8);
            string FileName       = Encoding.ASCII.GetString(Data, 12, FileNameLength);

            int id;

            Int32.TryParse(Path.GetFileNameWithoutExtension(FileName), out id);
            ProblemID        = id;
            LastModifiedTime = DateTime.MinValue;

            try
            {
                if (!Directory.Exists(LocalPath.ProblemsDirectory))
                {
                    Directory.CreateDirectory(LocalPath.ProblemsDirectory);
                }

                if (File.Exists(LocalPath.ProblemsDirectory + FileName + ".zip"))
                {
                    File.Delete(LocalPath.ProblemsDirectory + FileName + ".zip");
                }
                if (Directory.Exists(LocalPath.ProblemsDirectory + ProblemID.ToString()))
                {
                    DirectoryExtensions.Delete(LocalPath.ProblemsDirectory + ProblemID.ToString());
                }

                using (BinaryWriter bw = new BinaryWriter(
                           File.Open(LocalPath.ProblemsDirectory + FileName + ".zip", FileMode.Create)))
                {
                    bw.Write(Data, FileNameLength + 12, Data.Length - FileNameLength - 12);
                }

                ZipFile.ExtractToDirectory(
                    LocalPath.ProblemsDirectory + FileName + ".zip",
                    LocalPath.ProblemsDirectory + ProblemID.ToString());
                File.Delete(LocalPath.ProblemsDirectory + FileName + ".zip");

                double   timeLimit;
                int      memoryLimit;
                string   name;
                DateTime lastModifiedTime;
                ProblemLegend.Read(LocalPath.ProblemsDirectory + ProblemID.ToString(),
                                   out name, out timeLimit, out memoryLimit, out lastModifiedTime);
                LastModifiedTime = lastModifiedTime;

                logger.Debug("Problem {0} saved", ProblemID);
                if (logger.IsDebugEnabled)
                {
                    Console.WriteLine(DateTime.Now.ToString(culture) + " - Problem {0} saved", ProblemID);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error occurred on problem {0} saving: {1}", ProblemID, ex.Message);
                Console.WriteLine(DateTime.Now.ToString(culture) + " - Error occurred on problem {0} saving: {1}", ProblemID, ex.Message);
                throw;
            }
        }
        private void SaveProblemOpen(viewModels.NewProblemViewModel Model, int ProblemID, DateTime LastModifiedTime)
        {
            // Write model data to App_Data
            ParseImagesPath(Model.Description);
            string dirName = ProblemID.ToString();

            if (!Directory.Exists(LocalPath.AbsoluteProblemsDirectory + dirName))
            {
                Directory.CreateDirectory(LocalPath.AbsoluteProblemsDirectory + dirName);
            }

            // Write problem legend
            ProblemLegend.Write(LocalPath.AbsoluteProblemsDirectory + dirName,
                                Model.Name, Model.TimeLimit, Model.MemoryLimit, LastModifiedTime, ProblemTypes.Open,
                                Model.Description, Model.InputFormat, Model.OutputFormat);

            SaveChecker(Model.CheckerListID, Model.Checker, dirName);

            SaveOpenProblemResult(Model.OpenProblemResult, dirName);

            // Create zip for tester
            ZipFile.CreateFromDirectory(
                LocalPath.AbsoluteProblemsDirectory + dirName,
                LocalPath.AbsoluteProblemsDirectory + dirName + ".zip");

            // Save attachment
            List <string> attach = new List <string>();

            attach.AddRange(ParseImagesPath(Model.Description));
            attach.AddRange(ParseImagesPath(Model.OutputFormat));
            SaveImages(attach, LocalPath.AbsoluteProblemsDirectory + dirName);

            // Delete description, inputFormat and outputFormat from archive
            using (ZipArchive archive = ZipFile.Open(
                       LocalPath.AbsoluteProblemsDirectory + dirName + ".zip", ZipArchiveMode.Update))
            {
                List <ZipArchiveEntry> forDelete = new List <ZipArchiveEntry>();

                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    if (entry.Name == "Description" ||
                        entry.Name == "InputFormat" ||
                        entry.Name == "OutputFormat")
                    {
                        forDelete.Add(entry);
                    }
                }

                forDelete.Each(e => archive.Entries.First(en => en == e).Delete());
            }

            // Move tester zip
            if (System.IO.File.Exists(LocalPath.AbsoluteProblemsDirectory + dirName + ".zip"))
            {
                System.IO.File.Move(LocalPath.AbsoluteProblemsDirectory + dirName + ".zip",
                                    LocalPath.AbsoluteProblemsDirectory + dirName + "/" + dirName + ".zip");
            }
        }
        public ActionResult Update(int ProblemID = -1)
        {
            logger.Debug("User " + WebSecurity.GetUserId(User.Identity.Name) +
                         " \"" + User.Identity.Name + "\" visited ProblemsManagement/Problem/Update");

            Problem problem = repository.Problems.FirstOrDefault(p => p.ProblemID == ProblemID);

            if (problem == null)
            {
                logger.Warn("Problem with id = " + ProblemID + " not found");
                throw new HttpException(404, "Problem not found");
            }

            // Read problem info
            string name, description = "Error occurred",
                   inputFormat  = "Error occurred",
                   outputFormat = "Error occurred",
                   checkerCode  = "Error occurred";
            double       timeLimit;
            int          memoryLimit;
            ProblemTypes pt;

            try
            {
                ProblemLegend.Read(LocalPath.AbsoluteProblemsDirectory + problem.ProblemID,
                                   out name,
                                   out timeLimit,
                                   out memoryLimit,
                                   out pt,
                                   out description,
                                   out inputFormat,
                                   out outputFormat);

                string checkerPath = "";
                if (System.IO.File.Exists(LocalPath.AbsoluteProblemsDirectory + problem.ProblemID + "/checker.cpp"))
                {
                    checkerPath = LocalPath.AbsoluteProblemsDirectory + problem.ProblemID + "/checker.cpp";
                }
                else if (System.IO.File.Exists(LocalPath.AbsoluteProblemsDirectory + problem.ProblemID + "/checker.pas"))
                {
                    checkerPath = LocalPath.AbsoluteProblemsDirectory + problem.ProblemID + "/checker.pas";
                }

                using (StreamReader sr = new StreamReader(checkerPath))
                {
                    checkerCode = sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error occurred on problem legend reading:", ex);
            }

            EditProblemViewModel viewModel = new EditProblemViewModel()
            {
                ProblemID          = problem.ProblemID,
                Name               = problem.Name,
                ProblemTypesListID = (int)problem.Type,

                TimeLimit   = problem.TimeLimit,
                MemoryLimit = problem.MemoryLimit,

                Description  = description,
                InputFormat  = inputFormat,
                OutputFormat = outputFormat,

                CheckerCode = checkerCode,

                Tournaments = problem.Tournaments.Select(t => t.Name),

                CheckPending = problem.CheckPending
            };

            repository.ProblemTags.Each(t =>
                                        viewModel.ProblemTagsList.Add(new SelectListItem()
            {
                Text     = t.Name,
                Value    = t.ProblemTagID.ToString(),
                Selected = problem.Tags.Count(tag => tag.ProblemTagID == t.ProblemTagID) > 0
            }
                                                                      )
                                        );

            return(View(viewModel));
        }
        private void SaveProblemStandart(viewModels.EditProblemViewModel Model, int ProblemID, DateTime LastModifiedTime)
        {
            // Write model data to App_Data

            string dirName = ProblemID.ToString();

            if (!Directory.Exists(LocalPath.AbsoluteProblemsDirectory + dirName))
            {
                throw new DirectoryNotFoundException("Problem directory not found");
            }

            if (System.IO.File.Exists(LocalPath.AbsoluteProblemsDirectory + dirName + "/" + dirName + ".zip"))
            {
                System.IO.File.Delete(LocalPath.AbsoluteProblemsDirectory + dirName + "/" + dirName + ".zip");
            }

            // Write problem legend
            ProblemLegend.Write(LocalPath.AbsoluteProblemsDirectory + dirName,
                                Model.Name, Model.TimeLimit, Model.MemoryLimit, LastModifiedTime, ProblemTypes.Standart,
                                Model.Description, Model.InputFormat, Model.OutputFormat);

            SaveChecker(Model.CheckerListID, Model.Checker, dirName);

            if (Model.TestsDropDownID == "other")
            {
                if (Directory.Exists(LocalPath.AbsoluteProblemsDirectory + dirName + "/Tests"))
                {
                    Directory.Delete(LocalPath.AbsoluteProblemsDirectory + dirName + "/Tests", true);
                }
                SaveTests(Model.Tests, dirName);
            }

            // Save attachment
            List <string> attach = new List <string>();

            attach.AddRange(ParseImagesPath(Model.Description));
            attach.AddRange(ParseImagesPath(Model.InputFormat));
            attach.AddRange(ParseImagesPath(Model.OutputFormat));
            SaveImages(attach, LocalPath.AbsoluteProblemsDirectory + dirName);

            // Create zip for tester
            if (System.IO.File.Exists(LocalPath.AbsoluteProblemsDirectory + dirName + ".zip"))
            {
                System.IO.File.Delete(LocalPath.AbsoluteProblemsDirectory + dirName + ".zip");
            }
            ZipFile.CreateFromDirectory(
                LocalPath.AbsoluteProblemsDirectory + dirName,
                LocalPath.AbsoluteProblemsDirectory + dirName + ".zip");

            // Delete description, inputFormat and outputFormat from archive
            using (ZipArchive archive = ZipFile.Open(
                       LocalPath.AbsoluteProblemsDirectory + dirName + ".zip", ZipArchiveMode.Update))
            {
                List <ZipArchiveEntry> entriesForDelete = new List <ZipArchiveEntry>();
                foreach (ZipArchiveEntry entry in archive.Entries)
                {
                    if (entry.Name == "Description" ||
                        entry.Name == "InputFormat" ||
                        entry.Name == "OutputFormat")
                    {
                        entriesForDelete.Add(entry);
                    }
                }

                entriesForDelete.Each(e => e.Delete());
            }

            // Move tester zip
            if (System.IO.File.Exists(LocalPath.AbsoluteProblemsDirectory + dirName + ".zip"))
            {
                System.IO.File.Move(LocalPath.AbsoluteProblemsDirectory + dirName + ".zip",
                                    LocalPath.AbsoluteProblemsDirectory + dirName + "/" + dirName + ".zip");
            }

            if (Model.SamplesDropDownID == "other")
            {
                if (Directory.Exists(LocalPath.AbsoluteProblemsDirectory + dirName + "/Samples"))
                {
                    Directory.Delete(LocalPath.AbsoluteProblemsDirectory + dirName + "/Samples", true);
                }
                SaveSamples(Model.Samples, dirName);
            }
        }
        /// <summary>
        /// Partial view for problem content.
        /// </summary>
        /// <param name="ProblemID">ID of problem</param>
        public PartialViewResult ProblemContent(int ProblemID)
        {
            Problem problem = repository.Problems.FirstOrDefault(p => p.ProblemID == ProblemID);

            if (problem == null && ProblemID != -1)
            {
                logger.Warn("Problem with id = " + ProblemID + " not found");
                throw new HttpException(404, "Problem with id = " + ProblemID + " not found");
            }

            if (problem == null)
            {
                return(PartialView(new ProblemContentViewModel()
                {
                    ProblemID = -1
                }));
            }

            // Read problem info
            string       name, description, inputFormat, outputFormat;
            double       timeLimit;
            int          memoryLimit;
            ProblemTypes pt;

            try
            {
                ProblemLegend.Read(LocalPath.AbsoluteProblemsDirectory + problem.ProblemID,
                                   out name,
                                   out timeLimit,
                                   out memoryLimit,
                                   out pt,
                                   out description,
                                   out inputFormat,
                                   out outputFormat);

                if (pt != problem.Type)
                {
                    throw new ArgumentException("Problem types in database and in legend file are different");
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error occurred on problem legend reading:", ex);
                return(PartialView(new ProblemContentViewModel()
                {
                    ProblemID = -1
                }));
            }

            List <Tuple <string, string, string> > samples = null;
            bool comments = false;

            if (problem.Type != ProblemTypes.Open)
            {
                #region Read problem samples
                samples = new List <Tuple <string, string, string> >();
                string[] files = null;
                try
                {
                    files = System.IO.Directory
                            .GetFiles(LocalPath.AbsoluteProblemsDirectory + problem.ProblemID + "/Samples", "*")
                            .Where(f => Path.GetExtension(f) == ".in")
                            .ToArray();

                    if (files.Length == 0)
                    {
                    }
                    else
                    {
                        string input = "", output = "", comment = "";
                        foreach (string file in files)
                        {
                            if (System.IO.File.Exists(LocalPath.AbsoluteProblemsDirectory + problem.ProblemID + "/Samples/" +
                                                      Path.GetFileNameWithoutExtension(file) + ".cmt"))
                            {
                                comments = true;
                            }

                            using (StreamReader srIn = new StreamReader(file))
                            {
                                using (StreamReader srOut = new StreamReader(
                                           LocalPath.AbsoluteProblemsDirectory + problem.ProblemID + "/Samples/" +
                                           Path.GetFileNameWithoutExtension(file) + ".out"))
                                {
                                    input  = HttpUtility.HtmlEncode(srIn.ReadToEnd()).Replace("\n", "<br />");
                                    output = HttpUtility.HtmlEncode(srOut.ReadToEnd()).Replace("\n", "<br />");

                                    if (comments)
                                    {
                                        try
                                        {
                                            using (StreamReader srCmt = new StreamReader(
                                                       LocalPath.AbsoluteProblemsDirectory + problem.ProblemID + "/Samples/" +
                                                       Path.GetFileNameWithoutExtension(file) + ".cmt"))
                                            {
                                                comment = HttpUtility.HtmlEncode(srCmt.ReadToEnd()).Replace("\n", "<br />");
                                            }
                                        }
                                        catch (FileNotFoundException)
                                        {
                                            comment = "";
                                        }
                                    }
                                }
                            }

                            samples.Add(new Tuple <string, string, string>(input, output, comment));
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("Error occurred on problem samples reading:", ex);
                    return(PartialView(new ProblemContentViewModel()
                    {
                        ProblemID = -1
                    }));
                }
                #endregion
            }

            ProblemContentViewModel viewModel = new ProblemContentViewModel
            {
                ProblemID = problem.ProblemID,
                PT        = problem.Type,

                Name                = name,
                TimeLimit           = timeLimit,
                MemoryLimit         = memoryLimit,
                Description         = ReplaceImagesWithHTMLTags(HttpUtility.HtmlEncode(description), problem.ProblemID).Replace("\n", "<br />"),
                InputFormat         = ReplaceImagesWithHTMLTags(HttpUtility.HtmlEncode(inputFormat), problem.ProblemID).Replace("\n", "<br />"),
                OutputFormat        = ReplaceImagesWithHTMLTags(HttpUtility.HtmlEncode(outputFormat), problem.ProblemID).Replace("\n", "<br />"),
                TestSamplesComments = comments,
                TestSamples         = samples
            };

            return(PartialView(viewModel));
        }
        public void TestStandart(Int32 ProblemID, Int32 SolutionID, string SolutionName,
                                 ProgrammingLanguages PL, TournamentFormats TF,
                                 out TestResults Result, out int Score, out List <Tuple <long, long, TestResults> > TestResults)
        {
            // TODO: FL
            Result      = Solomon.TypesExtensions.TestResults.RTE;
            TestResults = null;
            Score       = 0;

            File.Copy(LocalPath.ProblemsDirectory + ProblemID.ToString() + "\\checker.exe",
                      LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\checker.exe", true);

            DirectoryExtensions.Copy(LocalPath.ProblemsDirectory + ProblemID.ToString() + "\\Tests",
                                     LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\Tests", false);

            if (!Directory.Exists(LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\exe"))
            {
                Directory.CreateDirectory(LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\exe");
            }
            if (!Directory.Exists(LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\output"))
            {
                Directory.CreateDirectory(LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\output");
            }

            CompilerSingleton.Instance.Compile(
                LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\" + SolutionName,
                LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\exe\\" + SolutionName + ".exe", PL, out Result, SolutionID);

            if (Result != Solomon.TypesExtensions.TestResults.OK)
            {
                //Interlocked.Decrement(ref threadCount);
                return;
            }

            // Testing
            // TODO: FL
            Result      = Solomon.TypesExtensions.TestResults.RTE;
            TestResults = new List <Tuple <long, long, TestResults> >();
            Tuple <long, long, TestResults> tempTuple;

            // Get all "in" files
            String[] inFiles = null;

            inFiles = Directory.GetFiles(
                LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\Tests", "*.in");

            double   timeLimit;
            int      memoryLimit;
            string   name;
            long     solutionTime, solutionMemory;
            DateTime lastModifiedTime;

            ProblemLegend.Read(LocalPath.ProblemsDirectory + ProblemID.ToString(),
                               out name, out timeLimit, out memoryLimit, out lastModifiedTime);

            int testOK = 0;

            foreach (String inFile in inFiles)
            {
                solutionTime   = 0;
                solutionMemory = 0;

                try
                {
                    if (PL == ProgrammingLanguages.Java)
                    {
                        RunSolutionClass(
                            LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\exe\\" + SolutionName,
                            inFile,
                            LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\output\\output.txt",
                            timeLimit, memoryLimit, out Result, out solutionTime, out solutionMemory);
                    }
                    else if (PL == ProgrammingLanguages.Python)
                    {
                        RunSolutionPython(
                            LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\exe\\" + SolutionName,
                            inFile,
                            LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\output\\output.txt",
                            timeLimit, memoryLimit, out Result, out solutionTime, out solutionMemory);
                    }
                    else
                    {
                        RunSolutionExe(
                            LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\exe\\" + SolutionName + ".exe",
                            inFile,
                            LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\output\\output.txt",
                            timeLimit, memoryLimit, out Result, out solutionTime, out solutionMemory);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("Warning on solution {0} running: {1}", SolutionID, ex.Message);
                    Console.WriteLine(DateTime.Now.ToString(culture) + " - Warning on solution {0} running: {1}", SolutionID, ex.Message);
                }

                if (Result != Solomon.TypesExtensions.TestResults.OK)
                {
                    tempTuple = new Tuple <long, long, TestResults>(solutionTime, solutionMemory, Result);
                    TestResults.Add(tempTuple);

                    if (TF == TournamentFormats.ACM)
                    {
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }

                Result = Solomon.TypesExtensions.TestResults.Executing;
                for (int i = 0; i < 5 && (int)Result >= 4; i++)
                {
                    CheckSolutionOutput(
                        LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\checker.exe",
                        inFile,
                        LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\output\\output.txt",
                        LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\Tests\\" + Path.GetFileNameWithoutExtension(inFile) + ".out",
                        out Result);
                }

                tempTuple = new Tuple <long, long, TestResults>(solutionTime, solutionMemory, Result);
                TestResults.Add(tempTuple);

                if (Result != Solomon.TypesExtensions.TestResults.OK)
                {
                    if (TF == TournamentFormats.ACM)
                    {
                        break;
                    }
                }
                else
                {
                    testOK++;
                }
            }

            if (TF == TournamentFormats.IOI)
            {
                Score  = 100 * testOK / inFiles.Length;
                Result = testOK == inFiles.Length ? Solomon.TypesExtensions.TestResults.OK : Solomon.TypesExtensions.TestResults.PS;
            }

            if (File.Exists(LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\output\\output.txt"))
            {
                File.Delete(LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\output\\output.txt");
            }

            for (int i = 0; i < 5; i++)
            {
                try
                {
                    Directory.Delete(LocalPath.SolutionsDirectory + SolutionID.ToString() + "\\Tests", true);
                    break;
                }
                catch (Exception) { Thread.Sleep(100); }
            }
        }