예제 #1
0
파일: Gen.cs 프로젝트: xguppy/ALS
        private async Task <bool> Compile(int lr, int var)
        {
            string          name = ProcessCompiler.CreatePath(lr, var);
            ProcessCompiler pc   = new ProcessCompiler(PathToSoulution(name), PathExecuteModel(name));

            return(await Task.Run(() => pc.Execute(60000)));
        }
예제 #2
0
        private static string CreateDirectoriesSources(int lwId, int variantId, int userId)
        {
            var userDirectory = Path.Combine(Environment.CurrentDirectory, "sourceCodeUser", userId.ToString());

            if (!Directory.Exists(userDirectory))
            {
                Directory.CreateDirectory(userDirectory);
            }
            //Получим директорию решения пользователя
            var taskDirectory = Path.Combine(userDirectory, ProcessCompiler.CreatePath(lwId, variantId));

            if (!Directory.Exists(taskDirectory))
            {
                Directory.CreateDirectory(taskDirectory);
            }
            //Посмотрим на все его попытки
            var numberLastSolution   = 0;
            var directoriesSolutions = Directory.GetDirectories(taskDirectory);

            if (directoriesSolutions.Length != 0)
            {
                numberLastSolution = directoriesSolutions.Max(dir => int.TryParse(Path.GetFileName(dir), out int res) ? res : 0);
            }
            //И создадим папку с новым решением
            var solutionDirectory = Path.Combine(taskDirectory, (numberLastSolution + 1).ToString());

            Directory.CreateDirectory(solutionDirectory);

            return(solutionDirectory);
        }
예제 #3
0
        private static string CreateExecuteDirectories(int lwId, int variantId, int userId)
        {
            var userDirectory = Path.Combine(Environment.CurrentDirectory, "executeUser", userId.ToString());

            if (!Directory.Exists(userDirectory))
            {
                Directory.CreateDirectory(userDirectory);
            }
            //Получим директорию решения пользователя
            var taskDirectory = Path.Combine(userDirectory, ProcessCompiler.CreatePath(lwId, variantId));

            if (!Directory.Exists(taskDirectory))
            {
                Directory.CreateDirectory(taskDirectory);
            }

            return(Path.Combine(taskDirectory, $"{ProcessCompiler.CreatePath(lwId, variantId)}.exe"));
        }
예제 #4
0
        void SetupDatabase(ApplicationContext context)
        {
            // check and add roles
            AuthService auth = new AuthService(Configuration);

            if (!context.Disciplines.Any())
            {
                context.Disciplines.Add(new Discipline {
                    Name = "Программирование", Cipher = "pr1"
                });
                context.SaveChanges();
            }

            if (!context.Specialties.Any())
            {
                var softwareEngineering = new Specialty {
                    Name = "Программная инженерия", Code = "09.03.04"
                };
                var computerScienceAndComputing = new Specialty
                {
                    Name = "Информатика и вычислительная техника", Code = "09.03.01"
                };
                context.Specialties.Add(softwareEngineering);
                context.Specialties.Add(computerScienceAndComputing);

                context.Groups.Add(new Group {
                    Name = "ДИПР-31", Year = 2019, Specialty = softwareEngineering
                });
                context.Groups.Add(new Group
                {
                    Name = "ДИНР-31", Year = 2019, Specialty = computerScienceAndComputing
                });
                context.SaveChanges();
            }

            if (!context.Roles.Any())
            {
                context.Roles.Add(new Role {
                    RoleId = 1, RoleName = RoleEnum.Student
                });
                context.Roles.Add(new Role {
                    RoleId = 2, RoleName = RoleEnum.Teacher
                });
                context.Roles.Add(new Role {
                    RoleId = 3, RoleName = RoleEnum.Admin
                });

                context.SaveChanges();
            }

            if (!context.Users.Any())
            {
                var student = new User {
                    Surname = "Михайлов", Name = "Дмитрий", Patronymic = "Владимирович", Email = "*****@*****.**", PwHash = auth.GetHashedPassword("tmpstudent"), GroupId = 1
                };
                var student1 = new User {
                    Surname = "Иванов", Name = "Иван", Patronymic = "Иванович", Email = "*****@*****.**", PwHash = auth.GetHashedPassword("ivan"), GroupId = 2
                };
                var student2 = new User {
                    Surname = "Петров", Name = "Петр", Patronymic = "Петрович", Email = "*****@*****.**", PwHash = auth.GetHashedPassword("petr"), GroupId = 1
                };
                var student3 = new User {
                    Surname = "Макаров", Name = "Макар", Patronymic = "Макарович", Email = "*****@*****.**", PwHash = auth.GetHashedPassword("makar"), GroupId = 2
                };
                var student4 = new User {
                    Surname = "Сидорова", Name = "Александра", Patronymic = "Михайловна", Email = "*****@*****.**", PwHash = auth.GetHashedPassword("alexandrochka"), GroupId = 1
                };
                var student5 = new User {
                    Surname = "Владов", Name = "Владислав", Patronymic = "Владиславович", Email = "*****@*****.**", PwHash = auth.GetHashedPassword("vlad"), GroupId = 2
                };
                var student6 = new User {
                    Surname = "Федоров", Name = "Федор", Patronymic = "Федорович", Email = "*****@*****.**", PwHash = auth.GetHashedPassword("fedor"), GroupId = 1
                };
                var teacher = new User {
                    Surname = "Семёнов", Name = "Иван", Patronymic = "Васильевич", Email = "*****@*****.**", PwHash = auth.GetHashedPassword("tmpprepod")
                };
                var admin = new User {
                    Surname = "Админов", Name = "Админ", Patronymic = "Админович", Email = "*****@*****.**", PwHash = auth.GetHashedPassword("tmpadmin")
                };


                context.Users.Add(student);
                context.Users.Add(student1);
                context.Users.Add(student2);
                context.Users.Add(student3);
                context.Users.Add(student4);
                context.Users.Add(student5);
                context.Users.Add(student6);
                context.Users.Add(admin);
                context.Users.Add(teacher);
                context.SaveChanges();

                context.UserRoles.Add(new UserRole {
                    UserId = student.Id, RoleId = 1
                });
                context.UserRoles.Add(new UserRole {
                    UserId = student1.Id, RoleId = 1
                });
                context.UserRoles.Add(new UserRole {
                    UserId = student2.Id, RoleId = 1
                });
                context.UserRoles.Add(new UserRole {
                    UserId = student3.Id, RoleId = 1
                });
                context.UserRoles.Add(new UserRole {
                    UserId = student4.Id, RoleId = 1
                });
                context.UserRoles.Add(new UserRole {
                    UserId = student5.Id, RoleId = 1
                });
                context.UserRoles.Add(new UserRole {
                    UserId = student6.Id, RoleId = 1
                });
                context.UserRoles.Add(new UserRole {
                    UserId = teacher.Id, RoleId = 2
                });
                context.UserRoles.Add(new UserRole {
                    UserId = admin.Id, RoleId = 3
                });

                context.SaveChanges();
            }



            if (!context.Themes.Any())
            {
                context.Themes.Add(new Theme {
                    Name = "простые взаимодействие с числами", DisciplineCipher = "pr1"
                });
                context.Themes.Add(new Theme {
                    Name = "условные операторы", DisciplineCipher = "pr1"
                });
                context.SaveChanges();
            }
            if (!context.TemplateLaboratoryWorks.Any())
            {
                context.TemplateLaboratoryWorks.Add(new TemplateLaboratoryWork {
                    TemplateTask = @"C:/Users/kampukter/source/repos/ALS/ALS.GeneratorModule/Tasks/task1.gentemp", ThemeId = 2
                });
                //context.TemplateLaboratoryWorks.Add(new TemplateLaboratoryWork { TemplateTask = @"C:/Users/kampukter/source/repos/ALS/ALS.GeneratorModule/Docs/Exp3.txt", ThemeId = 1 });
                //context.TemplateLaboratoryWorks.Add(new TemplateLaboratoryWork { TemplateTask = @"C:/Users/kampukter/source/repos/ALS/ALS.GeneratorModule/Docs/Exp.txt", ThemeId = 2 });
                //context.TemplateLaboratoryWorks.Add(new TemplateLaboratoryWork { TemplateTask = @"C:/Users/kampukter/source/repos/ALS/ALS.GeneratorModule/Docs/Exp2.txt", ThemeId = 2 });
                context.SaveChanges();
            }

            if (!context.LaboratoryWorks.Any())
            {
                //context.LaboratoryWorks.Add(new LaboratoryWork { UserId = 9, ThemeId = 2, Name = "lr1", Description = "lr1_description", Constraints = "{\"Memory\": 4096000, \"Time\": 60000}", DisciplineCipher = "pr1"});
                context.LaboratoryWorks.Add(new LaboratoryWork {
                    UserId = 9, ThemeId = 1, Name = "ЛР1 - работа с числами", Description = "Выполнить операции с числами", Constraints = "{\"Memory\": 4096000,\"Time\": 5000,\"Checker\" : \"AbsoluteChecker\"}", DisciplineCipher = "pr1", Evaluation = Evaluation.NotStrict
                });
                context.LaboratoryWorks.Add(new LaboratoryWork {
                    TemplateLaboratoryWorkId = 1, UserId = 9, ThemeId = 2, Name = "ЛР2 - работа с файлами", Description = "Выполнить операции с числами из файла input.txt и запишите в файл output.txt", Constraints = "{\"Memory\": 4096000,\"Time\": 5000,\"Checker\" : \"FileChecker\", \"Finaliter\" : \"FileFinaliter\", \"Preparer\": \"FilePreparer\"}", DisciplineCipher = "pr1", Evaluation = Evaluation.Strict
                });
                context.LaboratoryWorks.Add(new LaboratoryWork
                {
                    TemplateLaboratoryWorkId = 1, UserId = 9, ThemeId = 2, Name = "ЛР3 - работа со строками",
                    Description =
                        "В стандартный поток ввода принимаются 10 строк, по одной выполнить для каждой строки выполнить операцию, указанную в варианте и вывести в стандартный поток вывода результирующи строки",
                    Constraints      = "{\"Memory\": 4096000,\"Time\": 5000,\"Checker\" : \"AbsoluteChecker\"}",
                    DisciplineCipher = "pr1", Evaluation = Evaluation.Penalty
                });
                //context.LaboratoryWorks.Add(new LaboratoryWork { UserId = 2, ThemeId = 1, Name = "lr1", Description = "lr1_description", Constraints = "{\"Memory\": 4096000, \"Time\": 60000}", DisciplineCipher = "pr1"});
                //context.LaboratoryWorks.Add(new LaboratoryWork { UserId = 2, ThemeId = 1, Name = "lr2", Description = "Вывести четные элементы", Constraints = "{\"Memory\": 4096000, \"Time\": 60000}", DisciplineCipher = "pr1"});
                //context.LaboratoryWorks.Add(new LaboratoryWork { TemplateLaboratoryWorkId = 3, UserId = 2, ThemeId = 2, Name = "lr3", Description = "descrition", Constraints = "{\"Memory\": 4096000, \"Time\": 60000}", DisciplineCipher = "pr1" });
                context.SaveChanges();
            }
            if (!context.Variants.Any())
            {
                context.Variants.Add(new Variant {
                    VariantNumber = 1, LaboratoryWorkId = 1, Description = "var descr"
                });
                context.Variants.Add(new Variant {
                    VariantNumber = 2, LaboratoryWorkId = 1, Description = "Тест"
                });
                context.Variants.Add(new Variant {
                    VariantNumber = 1, LaboratoryWorkId = 3, LinkToModel = Path.Combine(Environment.CurrentDirectory, "executeModel", $"{ProcessCompiler.CreatePath(2, 1)}.exe"), Description = "В стандартный поток ввода принимаются 10 целых чисел. Вывести в стандартный поток вывода только чётные числа.", InputDataRuns = "\"тест1[60] : 2|4|6|8|6|10|12|14|18|20;тест2 [20]: 2|4|6|8|6|10|12|14|18|20;тест3 [20]: 2|4|6|8|6|10|12|14|18|20;тест4 [20]: 2|4|6|8|6|10|12|14|18|20;тест5 [20]: 1|2|3|4|5|6|7|8|9|10;\""
                });
                context.Variants.Add(new Variant {
                    VariantNumber = 1, LaboratoryWorkId = 2, LinkToModel = Path.Combine(Environment.CurrentDirectory, "executeModel", $"{ProcessCompiler.CreatePath(1, 3)}.exe"), Description = "Прочитать числа из одного файла и записать квадраты этих чисел в другой. Считывать символы до встречи буквы 'n'", InputDataRuns = "\"тест1[60] : #случайноеЦелое(10 , 200, 10);тест2 [20]: 2|4|6|8|6|10|12|14|18|20;тест3 [20]: 1|2|3|4|5|6|7|8|9|10;\""
                });
                context.Variants.Add(new Variant {
                    VariantNumber = 3, LaboratoryWorkId = 1, LinkToModel = Path.Combine(Environment.CurrentDirectory, "executeModel", $"{ProcessCompiler.CreatePath(3, 1)}.exe"), Description = "Все символы в строке расположить в обратном порядке", InputDataRuns = "\"тест1[20] : asddsaasd|Hello|qwerrty|asdfdgfdgh|zxcbvcbv|asdasdasd|klkjkj|yhyhyh|opopopo|jkjkjkk;тест2 [5]: Jow|woJ|Raw|waR|Kill|Llik|ClikKK|Sam|Zxc|Cxz;тест3 [75]: Hi|Di|Ui|ds|sD|as|fd|qw|re|sd; \""
                });
                context.SaveChanges();
            }

            if (!context.AssignedVariants.Any())
            {
                context.AssignedVariants.Add(new AssignedVariant {
                    UserId = 3, VariantId = 2, AssignDateTime = DateTime.Now
                });
                context.AssignedVariants.Add(new AssignedVariant {
                    UserId = 2, VariantId = 2, AssignDateTime = DateTime.Now
                });
                context.AssignedVariants.Add(new AssignedVariant {
                    UserId = 1, VariantId = 2, AssignDateTime = DateTime.Now
                });
                context.AssignedVariants.Add(new AssignedVariant {
                    UserId = 1, VariantId = 1, AssignDateTime = DateTime.Now
                });

                context.AssignedVariants.Add(new AssignedVariant {
                    UserId = 4, VariantId = 3, AssignDateTime = DateTime.Now
                });
                context.AssignedVariants.Add(new AssignedVariant {
                    UserId = 4, VariantId = 2, AssignDateTime = DateTime.Now
                });
                context.AssignedVariants.Add(new AssignedVariant {
                    UserId = 4, VariantId = 1, AssignDateTime = DateTime.Now
                });

                context.AssignedVariants.Add(new AssignedVariant {
                    UserId = 5, VariantId = 1, AssignDateTime = DateTime.Now
                });
                context.AssignedVariants.Add(new AssignedVariant {
                    UserId = 5, VariantId = 2, AssignDateTime = DateTime.Now
                });

                context.AssignedVariants.Add(new AssignedVariant {
                    UserId = 6, VariantId = 1, AssignDateTime = DateTime.Now
                });
                context.AssignedVariants.Add(new AssignedVariant {
                    UserId = 6, VariantId = 2, AssignDateTime = DateTime.Now
                });

                context.SaveChanges();
            }

            if (!context.Solutions.Any())
            {
                context.Solutions.Add(new Solution {
                    IsSolved = false, SendDate = DateTime.Now.AddHours(20), IsCompile = true, AssignedVariantId = 4
                });


                context.Solutions.Add(new Solution {
                    IsSolved = false, IsCompile = true, SendDate = DateTime.Now.AddHours(2), AssignedVariantId = 5
                });
                context.Solutions.Add(new Solution {
                    IsSolved = false, IsCompile = false, SendDate = DateTime.Now.AddHours(12), AssignedVariantId = 5
                });

                context.Solutions.Add(new Solution {
                    IsSolved = false, IsCompile = true, SendDate = DateTime.Now.AddHours(10), AssignedVariantId = 6
                });
                context.Solutions.Add(new Solution {
                    IsSolved = false, IsCompile = false, SendDate = DateTime.Now.AddHours(9), AssignedVariantId = 6
                });
                context.Solutions.Add(new Solution {
                    IsSolved = false, IsCompile = true, SendDate = DateTime.Now.AddHours(5), AssignedVariantId = 7
                });
                context.Solutions.Add(new Solution {
                    IsSolved = false, IsCompile = false, SendDate = DateTime.Now.AddHours(17), AssignedVariantId = 7
                });

                context.Solutions.Add(new Solution {
                    IsSolved = true, IsCompile = true, SendDate = DateTime.Now.AddHours(15), AssignedVariantId = 8
                });
                context.Solutions.Add(new Solution {
                    IsSolved = false, IsCompile = false, SendDate = DateTime.Now.AddHours(6), AssignedVariantId = 9
                });

                context.SaveChanges();
            }

            if (!context.Plans.Any())
            {
                context.Plans.Add(new Plan {
                    DisciplineCipher = "pr1", GroupId = 1, UserId = 9
                });
                context.Plans.Add(new Plan {
                    DisciplineCipher = "pr1", GroupId = 2, UserId = 9
                });

                context.SaveChanges();
            }
        }
예제 #5
0
        public async Task <IActionResult> Check(IFormFileCollection uploadedSources, [FromHeader] int variantId)
        {
            //Получим идентификатор юзера из его сессии
            var userIdentifier = int.Parse(User.Claims.First(c => c.Type == ClaimTypes.NameIdentifier).Value);
            //Проверим что вариант назначен пользователю
            var assignedVar =
                await _db.AssignedVariants.Include(aw => aw.Variant).ThenInclude(var => var.LaboratoryWork).FirstOrDefaultAsync(av =>
                                                                                                                                av.UserId == userIdentifier && av.VariantId == variantId);

            if (assignedVar != null)
            {
                //Возможно пользователь уже решил вариант
                var solution =
                    await _db.Solutions.FirstOrDefaultAsync(sol => sol.AssignedVariant == assignedVar && sol.IsSolved);

                if (solution == null)
                {
                    //Получим метод оценки
                    var evaluation = assignedVar.Variant.LaboratoryWork.Evaluation;
                    //Если не решил, то создадим нужные директории
                    var solutionDirectory = CreateDirectoriesSources(assignedVar.Variant.VariantId, variantId, userIdentifier);
                    //Cохраним его код в директорию пользователя
                    await SaveSources(solutionDirectory, uploadedSources);

                    //Создаём новое решение
                    solution = new Solution {
                        AssignedVariant = assignedVar, IsSolved = true, SendDate = DateTime.Now, SourceCode = solutionDirectory, IsCompile = true
                    };

                    //Возьмём пути для исполняемых файлов
                    var programFileUser = CreateExecuteDirectories(assignedVar.Variant.VariantId, variantId, userIdentifier);


                    var programFileModel = new Uri((await _db.Variants.FirstOrDefaultAsync(var => var.VariantId == variantId)).LinkToModel).AbsolutePath;
                    //Создадим директорию для запуска эталонной программы программы
                    var moveModelProgram = Path.Combine(Environment.CurrentDirectory, "modelTestingFiled", $"{userIdentifier}_{variantId}");
                    Directory.CreateDirectory(moveModelProgram);
                    //Новая файл в директории
                    var newPathProgram = Path.Combine(moveModelProgram, Path.GetFileName(programFileModel));
                    System.IO.File.Copy(programFileModel, newPathProgram, true);
                    //Скомпилируем программу пользователя
                    var compiler  = new ProcessCompiler(solutionDirectory, programFileUser);
                    var isCompile = await compiler.Execute(10000);

                    var extractUserDirectory = new DirectoryInfo(programFileUser).Parent.FullName;
                    //Если не скомпилировалась заносим, то в последнее решение добавим информацию что программа пользователя не была скомпилированна
                    if (isCompile != true)
                    {
                        solution.IsCompile = false;
                        solution.IsSolved  = false;
                        await _db.Solutions.AddAsync(solution);

                        DeleteProgramsDirectories(extractUserDirectory, moveModelProgram);
                        await _db.SaveChangesAsync();

                        var result = compiler.CompileState;
                        //Удалим показанный путь программы
                        return(BadRequest(result.Replace(solutionDirectory, null)));
                    }

                    //Прогоним по тестам
                    List <ResultRun> resultTests;
                    string[]         testNames;
                    double[]         weights;
                    try
                    {
                        //Получим входные данные для задачи
                        var gen = new Gen();

                        // testData: класс Test с полями Name, Data, Weight
                        // имя   вес   данные                    | если нужные еще какие-либо данные
                        // test [30] : #случайноеЦелое(10,20,10) | n;
                        var testData = gen.GetTestsFromJson(assignedVar.Variant.InputDataRuns);
                        testNames = testData.Select(td => td.Name).ToArray();
                        weights   = testData.Select(td => td.Weight).ToArray();
                        //Получим ограничения лабы
                        var constrainsLab = JsonConvert.DeserializeObject <Constrains>(
                            assignedVar.Variant.LaboratoryWork.Constraints,
                            new JsonSerializerSettings {
                            DefaultValueHandling = DefaultValueHandling.Populate
                        });
                        var variantConstrainsJson = assignedVar.Variant.Constraints;
                        if (variantConstrainsJson != null)
                        {
                            //Получим ограничения варианта
                            var constrainsVar = JsonConvert.DeserializeObject <Constrains>(
                                assignedVar.Variant.Constraints,
                                new JsonSerializerSettings {
                                DefaultValueHandling = DefaultValueHandling.Populate
                            });

                            //Перезапишем ограничениями лабы ограничениями варианта(которые доступны)
                            constrainsLab = OverridingConstrains(constrainsLab, constrainsVar);
                        }
                        var verification = new Verification(programFileUser, newPathProgram, constrainsLab);
                        resultTests = await verification.RunTests(testData.Select(t => t.Data).ToList());
                    }
                    catch (Exception e)
                    {
                        //Если произошло что-то не хорошее, то не будем понапрасну тратить драгоценные байты хранилища и удали исходные коды пользователя
                        Directory.Delete(solutionDirectory, true);
                        return(BadRequest(e.Message));
                    }
                    finally
                    {
                        //В любом случае удалим директорию пользователя с исполняемым файлом и директорию с моделью
                        DeleteProgramsDirectories(extractUserDirectory, moveModelProgram);
                    }

                    //Сохраним сейчас чтобы добавить тестовые прогоны в БД
                    await _db.Solutions.AddAsync(solution);

                    await _db.SaveChangesAsync();

                    var counterName = 0;
                    foreach (var result in resultTests)
                    {
                        var testRun = new TestRun
                        {
                            Name       = testNames[counterName++],
                            InputData  = result.Input.ToArray(),
                            OutputData = result.Output.ToArray(),
                            ResultRun  = JsonConvert.SerializeObject(new { result.Time, result.Memory, result.IsCorrect, result.Comment }),
                            SolutionId = solution.SolutionId
                        };
                        await _db.TestRuns.AddAsync(testRun);
                    }

                    var countCompleteTest = resultTests.Count(rt => rt.IsCorrect);
                    solution.IsSolved = Rate(evaluation, resultTests, weights, out var currMark);
                    assignedVar.Mark  = currMark;
                    await _db.SaveChangesAsync();

                    //Выведем количество верных тестовых прогонов и комментарии к ним
                    return(Ok($"{countCompleteTest} / {resultTests.Count} тестов пройдено.{FormattingResultLog(resultTests, testNames)}"));
                }
                return(Ok("Задача уже решена"));
            }
            return(BadRequest("Нет доступа"));
        }