public StopForumSpamResponse Check(CheckParameters parameters)
        {
            StopForumSpamResponse response = null;

            try
            {
                parameters?.Validate();

                var uriString = string.Concat(Constants.ApiBaseAddress, Constants.GetEndpoint);

                var baseUri = new Uri(uriString, UriKind.Absolute);

                var uriBuilder = new UriBuilder(baseUri)
                {
                    Query = parameters?.ToQuery()
                };

                var httpWebRequest = HttpWebRequestFactory.CreateHttpWebRequest(uriBuilder.Uri, HttpMethod.GET, this.Timeout, Constants.JsonMediaType);

                var json = httpWebRequest.ReadResponseAsString();

                response = json.FromJson <StopForumSpamResponse>();
            }
            catch (Exception ex)
            {
                response = new StopForumSpamResponse {
                    Success = 0, Error = ex.ToString()
                };
            }

            return(response);
        }
Exemplo n.º 2
0
 public CheckParametersForChecker(CheckParameters parameters, string checkerFileName, string solutionOutputFileName) :
     base(checkerFileName, parameters.InputTestFileName, parameters.OutputTestFileName, parameters.TimeLimit,
          parameters.MemoryLimit)
 {
     SolutionOutputFileName = solutionOutputFileName;
     LanguageHandler        = parameters.LanguageHandler;
 }
        public Task <StopForumSpamResponse> CheckAsync(CheckParameters parameters, CancellationToken cancellationToken)
        {
            if (cancellationToken == null)
            {
                cancellationToken = CancellationTokenFactory.Token();
            }

            var task = Task.Factory.StartNew(() => this.Check(parameters), cancellationToken);

            return(task);
        }
        public async Task CheckAsyncTest()
        {
            var firstResponse = await this._client.CheckAsync(Username, Email, Ip);

            Assert.AreEqual(true, firstResponse.Successful);

            var parameters = new CheckParameters {
                Username = Username, Email = Email, Ip = Ip
            };
            var secondResponse = await this._client.CheckAsync(parameters);

            Assert.AreEqual(true, secondResponse.Successful);
        }
        public void CheckTest()
        {
            var firstResponse = this._client.Check(Username, Email, Ip);

            Assert.AreEqual(true, firstResponse.Successful);

            var parameters = new CheckParameters {
                Username = Username, Email = Email, Ip = Ip
            };
            var secondResponse = this._client.Check(parameters);

            Assert.AreEqual(true, secondResponse.Successful);
        }
        public async Task CheckAsyncWithTokenTest()
        {
            var token = CancellationTokenFactory.Token();

            var firstResponse = await this._client.CheckAsync(Username, Email, Ip, token);

            Assert.AreEqual(true, firstResponse.Successful);

            var parameters = new CheckParameters {
                Username = Username, Email = Email, Ip = Ip
            };
            var secondResponse = await this._client.CheckAsync(parameters, token);

            Assert.AreEqual(true, secondResponse.Successful);
        }
Exemplo n.º 7
0
        private static ResultMessage CompileAndExecute(CheckParameters parameters, ref string output, ref string errors,
                                                       ref double usedTime, ref double usedMemory, bool isChecker = false)
        {
            var languageHandler = parameters.LanguageHandler;

            var compileResult = languageHandler.Compile(parameters.FileName, ref errors);

            if (!compileResult)
            {
                return(ResultMessage.CE);
            }

            var executeResult = languageHandler.Execute(parameters, ref output, ref errors, ref usedTime, ref usedMemory, isChecker);

            return(!executeResult ? ResultMessage.EE : ResultMessage.OK);
        }
Exemplo n.º 8
0
        public static TestResult CheckWithChecker(CheckParameters parameters, string checkerFileName)
        {
            var output     = "";
            var tempErrors = "";

            double usedTime   = 0;
            double usedMemory = 0;

            var compilationAndExecutionResult = CompileAndExecute(parameters, ref output, ref tempErrors, ref usedTime, ref usedMemory);

            if (compilationAndExecutionResult == ResultMessage.CE || compilationAndExecutionResult == ResultMessage.EE)
            {
                return(new TestResult("решение:\r\n" + tempErrors, compilationAndExecutionResult, usedTime, usedMemory));
            }

            var outputFilePath = Path.GetDirectoryName(parameters.FileName) + @"\output.txt";

            var sw = new StreamWriter(outputFilePath);

            sw.Write(output);
            sw.Close();

            var checkerParameters = new CheckParametersForChecker(parameters, checkerFileName, outputFilePath);

            var checkerOutput = "";
            var checkerCompilationAndExecutionResult = CompileAndExecute(checkerParameters, ref checkerOutput, ref tempErrors, ref usedTime,
                                                                         ref usedMemory, true);

            if (checkerCompilationAndExecutionResult == ResultMessage.CE || checkerCompilationAndExecutionResult == ResultMessage.EE)
            {
                return(new TestResult("чекер:\r\n" + tempErrors, checkerCompilationAndExecutionResult, usedTime, usedMemory));
            }

            var sr         = new StreamReader(parameters.OutputTestFileName);
            var testOutput = sr.ReadToEnd();

            sr.Close();

            //checker should return "true" or "false"
            return(checkerOutput.ToLower().Replace("\r\n", "") == "true"
                ? new TestResult("", ResultMessage.OK, usedTime, usedMemory)
                : new TestResult(
                       "Ожидаемый результат:\r\n" + testOutput + ".\r\n" + "Полученный результат:.\r\n" + output,
                       ResultMessage.TE, usedTime, usedMemory));
        }
        /// <summary>
        /// Sets the check defaults.
        /// </summary>
        /// <param name="fatPipeRowCount">The fat pipe row count.</param>
        /// <param name="mediumCostOperator">The medium cost operator.</param>
        /// <param name="highCostOperator">The high cost operator.</param>
        /// <param name="highDesiredMemoryKB">The high desired memory kb.</param>
        /// <param name="highRewindCount">The high rewind count.</param>
        /// <param name="highScanCount">The high scan count.</param>
        /// <param name="highSortCost">The high sort cost.</param>
        /// <param name="highSortCount">The high sort count.</param>
        /// <param name="highJoinCount">The high join count.</param>
        /// <param name="veryHighJoinCount">The very high join count.</param>
        // ReSharper disable once InconsistentNaming
        public void SetCheckDefaults(int fatPipeRowCount = 100000, int mediumCostOperator = 200,
                                     // ReSharper disable once InconsistentNaming
                                     int highCostOperator = 1000, int highDesiredMemoryKB = 1000000,
                                     int highRewindCount  = 50, int highScanCount         = 1000,
                                     int highSortCost     = 20, int highSortCount         = 50000,
                                     int highJoinCount    = 7, int veryHighJoinCount      = 10)
        {
            this.CheckParameters = new CheckParameters
            {
                FatPipeRowCount     = fatPipeRowCount,
                MediumCostOperator  = mediumCostOperator,
                HighCostOperator    = highCostOperator,
                HighDesiredMemoryKb = highDesiredMemoryKB,
                HighRewindCount     = highRewindCount,
                HighScanCount       = highScanCount,

                HighSortCost      = Math.Min(100, Math.Max(10, highSortCost)),
                HighSortCount     = highSortCount,
                HighJoinCount     = highJoinCount,
                VeryHighJoinCount = veryHighJoinCount,
            };
        }
Exemplo n.º 10
0
        public static TestResult Check(CheckParameters parameters)
        {
            var output     = "";
            var tempErrors = "";

            double usedTime   = 0;
            double usedMemory = 0;

            var compilationAndExecutionResult = CompileAndExecute(parameters, ref output, ref tempErrors, ref usedTime, ref usedMemory);

            if (compilationAndExecutionResult == ResultMessage.CE || compilationAndExecutionResult == ResultMessage.EE)
            {
                return(new TestResult(tempErrors, compilationAndExecutionResult, usedTime, usedMemory));
            }

            var sr         = new StreamReader(parameters.OutputTestFileName);
            var testOutput = sr.ReadToEnd();

            sr.Close();

            return(string.Compare(output, testOutput, StringComparison.OrdinalIgnoreCase) != 0
                ? new TestResult("Ожидаемый результат:\r\n" + testOutput + ".\r\n" + "Полученный результат:.\r\n" + output, ResultMessage.TE, usedTime, usedMemory)
                : new TestResult("", ResultMessage.OK, usedTime, usedMemory));
        }
Exemplo n.º 11
0
 public abstract bool Execute(CheckParameters parameters, ref string output, ref string errors, ref double usedTime,
                              ref double usedMemory, bool isChecker);
 public Task <StopForumSpamResponse> CheckAsync(CheckParameters parameters) => this.CheckAsync(parameters, CancellationTokenFactory.Token());
Exemplo n.º 13
0
        public override bool Execute(CheckParameters parameters, ref string output, ref string errors, ref double usedTime,
                                     ref double usedMemory, bool isChecker)
        {
            var extension          = Path.GetExtension(parameters.FileName);
            var executableFilePath = parameters.FileName.Substring(0, parameters.FileName.Length - extension.Length) + ".exe";

            var inputFilePath = isChecker
                ? ((CheckParametersForChecker)parameters).SolutionOutputFileName
                : parameters.InputTestFileName;

            var timeLimit = parameters.TimeLimit;

            if (timeLimit == 0)
            {
                timeLimit = 120; //2 mins
            }

            if (!File.Exists(executableFilePath))
            {
                //errors += "If you see this message, please contact administrator (ExErr1).";
                errors += "Если Вы видите это сообщение, пожалуйста, свяжитесь с администратором (ExErr1).";
                return(false);
            }
            if (!File.Exists(inputFilePath))
            {
                //errors += "If you see this message, please contact administrator (ExErr2).";
                errors += "Если Вы видите это сообщение, пожалуйста, свяжитесь с администратором (ExErr2).";
                return(false);
            }
            if (isChecker)
            {
                if (!File.Exists(parameters.InputTestFileName))
                {
                    //errors += "If you see this message, please contact administrator (ExErr3).";
                    errors += "Если Вы видите это сообщение, пожалуйста, свяжитесь с администратором (ExErr3).";
                    return(false);
                }
                if (!File.Exists(parameters.OutputTestFileName))
                {
                    //errors += "If you see this message, please contact administrator (ExErr4).";
                    errors += "Если Вы видите это сообщение, пожалуйста, свяжитесь с администратором (ExErr4).";
                    return(false);
                }
            }

            bool   hasExited = false;
            bool   hasLimitExceptions = false;
            int    exitCode = 0;
            string stdout = "", stderr = "";
            string limitStderr      = "";
            double tempUsedTime     = 0;
            double tempUsedMemory   = 0;
            var    assemblyFileName = Path.GetDirectoryName(inputFilePath).Replace("App_Data", @"bin\CPTLib.dll");

            try
            {
                PermissionSet ps = new PermissionSet(PermissionState.None);
                ps.AddPermission(new UIPermission(PermissionState.Unrestricted));
                ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution));
                ps.AddPermission(new SecurityPermission(SecurityPermissionFlag.UnmanagedCode));
                ps.AddPermission(new FileIOPermission(
                                     FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, assemblyFileName));
                ps.AddPermission(new FileIOPermission(FileIOPermissionAccess.PathDiscovery | FileIOPermissionAccess.Read, executableFilePath));
                ps.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, inputFilePath));
                if (isChecker)
                {
                    ps.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, parameters.InputTestFileName));
                    ps.AddPermission(new FileIOPermission(FileIOPermissionAccess.Read, parameters.OutputTestFileName));
                }
                AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
                setup.ShadowCopyFiles = "true";
                var sandbox = AppDomain.CreateDomain("Sandbox", null, setup, ps);
                AppDomain.MonitoringIsEnabled = true;

                TextReader inputFileReader = new StreamReader(inputFilePath);
                string[]   arguments       = isChecker
                    ? new string[] { inputFilePath, parameters.InputTestFileName, parameters.OutputTestFileName }
                    : new string[] { inputFilePath };

                try
                {
                    var          hookName = typeof(SandboxHook).FullName;
                    ObjectHandle obj      = sandbox.CreateInstanceFrom(assemblyFileName, hookName);
                    using (SandboxHook hook = (SandboxHook)obj.Unwrap())
                    {
                        hook.Capture(inputFileReader == null ? String.Empty : inputFileReader.ReadToEnd());
                        inputFileReader.Close();

                        var t =
                            new Task(
                                () =>
                                WaitForExit(sandbox, hook, executableFilePath, arguments, ref stdout, ref stderr,
                                            ref exitCode, ref hasExited));
                        t.Start();
                        var t2 =
                            new Task(
                                () =>
                                CheckTimeLimit(sandbox, timeLimit, parameters.MemoryLimit, ref tempUsedTime,
                                               ref tempUsedMemory, ref limitStderr, ref hasExited, ref hasLimitExceptions));
                        t2.Start();

                        Task.WaitAll(t, t2);
                    }
                }
                finally
                {
                    if (!hasLimitExceptions)
                    {
                        AppDomain.Unload(sandbox);
                    }
                }
            }
            catch (Exception ex)
            {
                errors += hasLimitExceptions ? "" : ex.Message + "\r\n";
            }

            output += stdout;
            errors += hasLimitExceptions ? limitStderr : stderr;

            usedTime   = tempUsedTime;
            usedMemory = tempUsedMemory;

            if (File.Exists(executableFilePath))
            {
                try
                {
                    File.Delete(executableFilePath);
                }
                catch (Exception) { }
            }

            return(hasExited && errors == "" && exitCode == 0);
        }
Exemplo n.º 14
0
        public override bool Execute(CheckParameters parameters, ref string output, ref string errors, ref double usedTime, ref double usedMemory, bool isChecker)
        {
            var extension          = Path.GetExtension(parameters.FileName);
            var executableFilePath = parameters.FileName.Substring(0, parameters.FileName.Length - extension.Length) + ".exe";

            var inputFilePath = isChecker
                ? ((CheckParametersForChecker)parameters).SolutionOutputFileName
                : parameters.InputTestFileName;

            var timeLimit = parameters.TimeLimit;

            if (timeLimit == 0)
            {
                timeLimit = 120; //2 mins
            }

            if (!File.Exists(executableFilePath))
            {
                //errors += "If you see this message, please contact administrator (ExErr1).";
                errors += "Если Вы видите это сообщение, пожалуйста, свяжитесь с администратором (ExErr1).";
                return(false);
            }
            if (!File.Exists(inputFilePath))
            {
                //errors += "If you see this message, please contact administrator (ExErr2).";
                errors += "Если Вы видите это сообщение, пожалуйста, свяжитесь с администратором (ExErr2).";
                return(false);
            }
            if (isChecker)
            {
                if (!File.Exists(parameters.InputTestFileName))
                {
                    //errors += "If you see this message, please contact administrator (ExErr3).";
                    errors += "Если Вы видите это сообщение, пожалуйста, свяжитесь с администратором (ExErr3).";
                    return(false);
                }
                if (!File.Exists(parameters.OutputTestFileName))
                {
                    //errors += "If you see this message, please contact administrator (ExErr4).";
                    errors += "Если Вы видите это сообщение, пожалуйста, свяжитесь с администратором (ExErr4).";
                    return(false);
                }
            }

            Process          proc = new Process();
            ProcessStartInfo info = new ProcessStartInfo();

            info.FileName = executableFilePath;
            info.RedirectStandardInput  = true;
            info.RedirectStandardOutput = true;
            info.RedirectStandardError  = true;
            info.UseShellExecute        = false;
            info.CreateNoWindow         = true;
            info.Arguments = inputFilePath + " " + parameters.InputTestFileName + " " + parameters.OutputTestFileName;

            proc.StartInfo = info;
            proc.Start();

            using (StreamWriter sw = proc.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    var    sr = new StreamReader(inputFilePath);
                    string line;

                    while ((line = sr.ReadLine()) != null)
                    {
                        proc.StandardInput.WriteLine(line);
                    }

                    sr.Close();
                }
            }

            var    stdout         = "";
            var    stderr         = "";
            double tempUsedTime   = 0;
            double tempUsedMemory = 0;
            bool   hasStarted     = false;
            bool   hasExited      = false;

            try
            {
                var t1 = new Task(() => WaitForExit(proc, timeLimit, ref stdout, ref stderr, ref hasStarted));

                var t2 =
                    new Task(
                        () =>
                        CheckTimeLimit(proc, timeLimit, parameters.MemoryLimit, ref tempUsedTime, ref tempUsedMemory, ref stderr,
                                       ref hasExited, ref hasStarted));
                t2.Start();
                Thread.Sleep(10);
                t1.Start();

                Task.WaitAll(t1, t2);
            }
            catch (Exception ex)
            {
                errors += ex.Message;
            }

            if (timeLimit < tempUsedTime)
            {
                errors += "Ограничение по времени превышено.\r\n";//"Time limit (" + timeLimit + "s) exceeded.\r\n";
            }

            if (parameters.MemoryLimit != 0 && parameters.MemoryLimit * 1024 < tempUsedMemory)
            {
                errors += "Ограничение по памяти превышено.\r\n";//"Memory limit (" + parameters.MemoryLimit + "Kb) exceeded.\r\n";
            }

            proc.Close();

            output += stdout;
            errors += stderr;

            usedTime   = tempUsedTime;
            usedMemory = tempUsedMemory;

            if (File.Exists(executableFilePath))
            {
                try
                {
                    File.Delete(executableFilePath);
                }
                catch (Exception) { }
            }

            return(hasExited && errors == "");
        }