Esempio n. 1
0
        public IList <MaterialStimulationDto> GetList(Guid personalFileId)
        {
            using (var db = _dbFactory.Create(PersonalFilePermissions.ReadOperation))
            {
                var items = db.Set <MaterialStimulation>()
                            .Where(x => x.PersonalFileId == personalFileId && x.RecordDeleted == null)
                            .Select(x => new MaterialStimulationDto
                {
                    ID             = x.ID,
                    OrderDate      = x.OrderHead.OrderDate,
                    OrderNumber    = x.OrderHead.OrderNumber,
                    PersonalFileId = x.PersonalFileId,

                    DateStart    = x.DateStart,
                    DateEnd      = x.DateEnd,
                    MustBeNotify = x.MustBeNotify,
                    SalaryType   = new SalaryTypeDto
                    {
                        ID          = x.SalaryTypeId,
                        Name        = x.SalaryType.Name,
                        UnitMeasure = new EnumItemDto
                        {
                            Id = x.SalaryType.UnitMeasure
                        }
                    },
                    Value = x.SalaryValue,
                })
                            .ToArray();

                return(items);
            }
        }
Esempio n. 2
0
 public RemovalStatus Remove(object id)
 {
     Contract.Requires <ArgumentNullException>(id != null);
     using (var operation = _operationContextFactory.Create())
     {
         var entityToDelete = operation.DataContext.Query.Find <TEntity>(id);
         if (entityToDelete == null)
         {
             return(RemovalStatus.ElementDoesNotExist);
         }
         Contract.Assert(typeof(TEntity).IsAssignableFrom(typeof(TEntity)));
         try
         {
             operation.DataContext.Factory.Delete(entityToDelete);
             operation.Complete();
             return(RemovalStatus.Success);
         }
         catch (GraphLabsDbUpdateException e)
         {
             if (e.ExceptionCode == DbUpgradeFailure.FkViolated)
             {
                 return(RemovalStatus.SomeFKExistOnTheElement);
             }
             return(RemovalStatus.UnknownFailure);
         }
     }
 }
Esempio n. 3
0
 public ActionResult Test(StudentAnswersModel answers)
 {
     try
     {
         foreach (var answer in answers.ChosenAnswerIds)
         {
             var operation = _operationContextFactory.Create();
             var entity    = operation.DataContext.Query.OfEntities <StudentAnswer>().FirstOrDefault(e => e.TestResult.Id == answers.TestResultId && e.AnswerVariant.Id == answer);
             var Id        = entity == null ? 0 : entity.Id;
             _answerSaver.CreateOrUpdate(new StudentAnswerModel
             {
                 Id             = Id,
                 ChosenAnswerId = answer,
                 TestResultId   = answers.TestResultId
             });
             var testResult = operation.DataContext.Query.OfEntities <TestResult>().FirstOrDefault(e => e.Id == answers.TestResultId);
             testResult.Score = CalculateMarkForTheTest(testResult);
             operation.Complete();
         }
         return(Json(true));
     }
     catch (GraphLabsDbUpdateException e)
     {
         return(Json(false));
     }
 }
Esempio n. 4
0
        private LoginResult TryLoginImpl(string email, string password, string clientIp, out Guid sessionGuid, bool force)
        {
            using (var operation = _operationFactory.Create())
            {
                var user = operation.QueryOf <User>()
                           .SingleOrDefault(u => u.Email == email &&
                                            (!(u is Student) || ((u as Student).IsVerified && !(u as Student).IsDismissed)));

                if (user == null || !UserIsValid(user, password))
                {
                    _log.InfoFormat("Неудачный вход, e-mail: {0}, ip: {1}", email, clientIp);

                    sessionGuid = Guid.Empty;
                    return(LoginResult.InvalidLoginPassword);
                }

                var lastSessions = GetSessionsOrderedByCreationTime(operation.DataContext, user);
                if (lastSessions.Any())
                {
                    if (!force)
                    {
                        sessionGuid = Guid.Empty;
                        return(LoginResult.LoggedInWithAnotherSessionId);
                    }

                    foreach (var s in lastSessions)
                    {
                        operation.DataContext.Factory.Delete(s);
                    }
                }

                var session = CreateSession(operation.DataContext.Factory, user, clientIp);
                SetLastAction(session);

                _log.InfoFormat("Удачный вход, e-mail: {0}, ip: {1}", email, clientIp);
                SetupCurrentPrincipal(user);

                sessionGuid = session.Guid;

                operation.Complete();
            }

            return(LoginResult.Success);
        }
Esempio n. 5
0
        /// <summary> Получает вариант задания по Id </summary>
        /// <param name="id"> Id варианта</param>
        public TaskVariantDto GetVariant(long id)
        {
            Contract.Assume(Contract.Result <TaskVariantDto>() != null);

            using (var op = _operationFactory.Create())
            {
                var variant = op.DataContext.Query.Find <TaskVariant>(id);
                if (variant == null)
                {
                    throw new ArgumentException("Вариант с указанным Id не найден.");
                }

                return(new TaskVariantDto
                {
                    Data = variant.Data,
                    GeneratorVersion = variant.GeneratorVersion,
                    Number = variant.Number,
                    Version = variant.Version,
                    Id = variant.Id
                });
            }
        }
Esempio n. 6
0
        public ActionResult UploadTask(HttpPostedFileBase xap)
        {
            // Verify that the user selected a file
            if (xap != null && xap.ContentLength > 0)
            {
                TaskPoco newTask;
                try
                {
                    newTask = _taskManager.UploadTask(xap.InputStream);
                }
                catch (Exception)
                {
                    return(RedirectToAction("UploadTask", "Task", new { ErrorMessage = UserMessages.UPLOAD_ERROR }));
                }

                if (newTask == null)
                {
                    return(RedirectToAction("UploadTask", "Task", new { ErrorMessage = UserMessages.TASK_EXISTS }));
                }

                long id;
                using (var op = _operationFactory.Create())
                {
                    var task = op.DataContext.Factory.Create <Task>();
                    var data = op.DataContext.Factory.Create <TaskData>();
                    data.Xap = newTask.Xap;

                    task.Name             = newTask.Name;
                    task.VariantGenerator = null;
                    task.Sections         = newTask.Sections;
                    task.Version          = newTask.Version;
                    task.TaskData         = data;
                    task.Note             = "";

                    op.Complete();

                    id = task.Id;
                }

                return(RedirectToAction("EditTask", "Task", new { Id = id, StatusMessage = UserMessages.TaskController_UploadTask_Задание_успешно_загружено }));
            }

            // redirect back to the index action to show the form once again
            return(RedirectToAction("UploadTask", "Task", new { ErrorMessage = UserMessages.UPLOAD_FILE_NOT_SPECIFIED }));
        }
Esempio n. 7
0
        /// <summary> Регистрирует действия студента </summary>
        /// <param name="taskId"> Идентификатор модуля-задания </param>
        /// <param name="sessionGuid"> Идентификатор сессии </param>
        /// <param name="actions"> Действия для регистрации </param>
        /// <param name="isTaskFinished"> Задание завершено? </param>
        /// <returns> Количество баллов студента </returns>
        /// <remarks> От этой штуки зависит GraphLabs.Components </remarks>
        public int?RegisterUserActions(long taskId, Guid sessionGuid, ActionDescription[] actions, bool isTaskFinished = false)
        {
            using (var op = _operationFactory.Create())
            {
                var task          = op.DataContext.Query.Get <Task>(taskId);
                var session       = GetSessionWithChecks(op.DataContext.Query, sessionGuid);
                var resultLog     = GetCurrentResultLog(op.DataContext.Query, session);
                var taskResultLog = GetCurrentTaskResultLog(resultLog, task);
                if (taskResultLog.Score == null)
                {
                    taskResultLog.Score = StartingScore;
                }

                if (actions.Any())
                {
                    foreach (var actionDescription in actions)
                    {
                        var newAction = op.DataContext.Factory.Create <StudentAction>();
                        newAction.Description = actionDescription.Description;
                        newAction.Penalty     = actionDescription.Penalty;
                        newAction.TaskResult  = taskResultLog;
                        newAction.Time        = actionDescription.TimeStamp;

                        taskResultLog.StudentActions.Add(newAction);
                    }

                    taskResultLog.Score -= actions.Last().Penalty;
                }

                if (isTaskFinished)
                {
                    var newAction = op.DataContext.Factory.Create <StudentAction>();
                    newAction.Description = $"Задание {task.Name} выполнено.";
                    newAction.Penalty     = 0;
                    newAction.TaskResult  = taskResultLog;
                    newAction.Time        = _systemDate.Now();
                    taskResultLog.Status  = ExecutionStatus.Complete;
                    taskResultLog.StudentActions.Add(newAction);
                }

                op.Complete();

                return(taskResultLog.Score);
            }
        }
        private VariantExecutionModelBase CreateTestExecutionModel(Uri taskCompleteRedirect, DomainModel.TestPoolEntry test, LabVariant variant, LabWork lab, Result result)
        {
            var model = new TestExecutionModel();

            model.Name       = test.TestPool.Name;
            model.Question   = test.TestQuestion.Question;
            model.Answers    = test.TestQuestion.AnswerVariants;
            model.QuestionId = test.Id;
            model.OtherTasks = GetOtherTasksModels(lab, result, null, test).ToArray();
            model.VariantId  = variant.Id;
            model.LabName    = lab.Name;
            var operation  = _operationFactory.Create();
            var testResult = operation.DataContext.Query.OfEntities <TestResult>().FirstOrDefault(e => e.TestPoolEntry.Id == test.Id & e.Result.Id == result.Id);

            operation.Complete();
            model.TestResult = testResult.Id;
            return(model);
        }
Esempio n. 9
0
        /// <summary> Регистрирует начало выполнения задания </summary>
        /// <param name="taskId"> Идентификатор модуля-задания </param>
        /// <param name="sessionGuid"> Идентификатор сессии </param>
        /// <returns> Данные для задания - как правило, исходный граф, или что-то типа того </returns>
        public TaskVariantDto GetVariant(long taskId, Guid sessionGuid)
        {
            using (var op = _operationFactory.Create())
            {
                var         session     = GetSessionWithChecks(op.DataContext.Query, sessionGuid);
                TaskVariant taskVariant = null;
                if (new [] { UserRole.Teacher, UserRole.Administrator }.Contains(session.User.Role))//вообще должен быть Teacher/Admin
                {
                    var task = op.DataContext.Query.Get <Task>(taskId);
                    taskVariant = op.DataContext.Query.OfEntities <TaskVariant>().First(v => v.Task == task);
                }
                else if (session.User.Role == UserRole.Student)
                {
                    var task          = op.DataContext.Query.Get <Task>(taskId);
                    var resultLog     = GetCurrentResultLog(op.DataContext.Query, session);
                    var taskResultLog = GetCurrentTaskResultLog(resultLog, task);

                    var variant = resultLog.LabVariant;
                    taskVariant = variant.TaskVariants.Single(v => v.Task == task);

                    var action = op.DataContext.Factory.Create <StudentAction>();
                    action.TaskResult  = taskResultLog;
                    action.Time        = _systemDate.Now();
                    action.Description = "$['Task {task.Id}' -> Variant {taskVariant.Number}]";
                    action.Penalty     = 0;
                    taskResultLog.StudentActions.Add(action);

                    op.Complete();
                }
                else
                {
                    throw new NotSupportedException("Неизвестный науке зверь!");
                }
                return(new TaskVariantDto
                {
                    Data = taskVariant.Data,
                    GeneratorVersion = taskVariant.GeneratorVersion,
                    Id = taskVariant.Id,
                    Number = taskVariant.Number,
                    Version = taskVariant.Version
                });
            }
        }
Esempio n. 10
0
        protected override Action <DomainModel.StudentAnswer> GetEntityInitializer(StudentAnswerModel model, IEntityQuery query)
        {
            var result     = query.Get <TestResult>(model.TestResultId);
            var answer     = query.Get <AnswerVariant>(model.ChosenAnswerId);
            var operation  = _operationContextFactory.Create();
            var testResult = operation.DataContext.Query.OfEntities <TestResult>().FirstOrDefault(e => e.Id == result.Id);

            if (testResult != null)
            {
                testResult.Status = ExecutionStatus.Complete;
            }
            operation.Complete();
            return(g =>
            {
                g.TestResult = result;
                g.AnswerVariant = answer;
                g.Time = DateTime.Now;
            });
        }
Esempio n. 11
0
        public DomainModel.News CreateOrUpdate(NewsModel model)
        {
            using (var operation = _operationContextFactory.Create())
            {
                var user = operation.DataContext.Query
                           .OfEntities <User>()
                           .SingleOrDefault(u => u.Email == _currentUser.Identity.Name && !(u is Student));

                if (user == null)
                {
                    return(null);
                }

                DomainModel.News news;
                if (model.Id == 0)
                {
                    news = operation.DataContext.Factory.Create <DomainModel.News>();
                }
                else
                {
                    news = operation.DataContext.Query.Get <DomainModel.News>(model.Id);
                    if (news.User != user && !user.Role.HasFlag(UserRole.Administrator))
                    {
                        return(null);
                    }
                }

                news.Title = model.Title;
                news.Text  = model.Text;
                news.User  = user;

                operation.Complete();

                return(news);
            }
        }
Esempio n. 12
0
        public TEntity CreateOrUpdate(TModel model)
        {
            using (var operation = _operationContextFactory.Create())
            {
                TEntity entity;
                if (!ExistsInDatabase(model))
                {
                    var type = GetEntityType(model);
                    Contract.Assert(typeof(TEntity).IsAssignableFrom(type));
                    entity = (TEntity)operation.DataContext.Factory.Create(
                        type,
                        o => GetEntityInitializer(model, operation.DataContext.Query)((TEntity)o));
                }
                else
                {
                    entity = operation.DataContext.Query.Get <TEntity>(GetEntityKey(model));
                    GetEntityInitializer(model, operation.DataContext.Query).Invoke(entity);
                }

                operation.Complete();

                return(entity);
            }
        }
Esempio n. 13
0
        /// <summary> Загрузить задание для отладки </summary>
        public DebugTaskData UploadDebugTask(byte[] taskData, byte[] variantData)
        {
            if (!WorkingMode.IsDebug())
            {
                throw new InvalidOperationException(
                          "Создание тестовых вариантов возможно только при работе в тестовом режиме.");
            }

            // Загружаем задание
            TaskPoco taskPoco;

            using (var stream = new MemoryStream(taskData))
            {
                taskPoco = _taskManager.UploadTaskWithTimestamp(stream);
            }
            if (taskPoco == null)
            {
                throw new InvalidOperationException("Провал. Задание с таким именем и версией уже существует.");
            }

            using (var operation = _operationFactory.Create())
            {
                var task = operation.DataContext.Factory.Create <Task>();
                var data = operation.DataContext.Factory.Create <TaskData>();
                data.Xap = taskPoco.Xap;

                task.Name             = taskPoco.Name;
                task.VariantGenerator = null;
                task.Sections         = taskPoco.Sections;
                task.Version          = taskPoco.Version;
                task.TaskData         = data;
                task.Note             = "Загружено автоматически сервисом отладки.";

                // Загружаем вариант задания
                var taskVariant = operation.DataContext.Factory.Create <TaskVariant>();
                taskVariant.Data             = variantData;
                taskVariant.GeneratorVersion = "1.0";
                taskVariant.Number           = "Debug";
                taskVariant.Task             = task;

                // Создаём лабу
                var now = DateTime.Now;
                var lab = operation.DataContext.Factory.Create <LabWork>();
                lab.Name = $"Отладка модуля \"{task.Name}\"";

                // Добавляем в расписание для всех групп
                foreach (var group in operation.QueryOf <Group>().ToArray())
                {
                    var sch = operation.DataContext.Factory.Create <GroupLabSchedule>();
                    sch.DateFrom = now.Date;
                    sch.DateTill = now.Date.AddDays(7);
                    sch.Group    = group;
                    sch.LabWork  = lab;
                    sch.Mode     = LabExecutionMode.IntroductoryMode;
                }

                // Добавляем задание в лабу
                var labEntry = operation.DataContext.Factory.Create <LabEntry>();
                labEntry.LabWork = lab;
                labEntry.Order   = 0;
                labEntry.Task    = task;

                // Создаём вариант
                var labVariant = operation.DataContext.Factory.Create <LabVariant>();
                labVariant.IntroducingVariant = true;
                labVariant.LabWork            = lab;
                labVariant.Number             = "Debug";
                labVariant.Version            = 1;
                labVariant.TaskVariants       = new[] { taskVariant };

                operation.Complete();

                return(new DebugTaskData
                {
                    LabWorkId = lab.Id,
                    LabVariantId = labVariant.Id
                });
            }
        }
Esempio n. 14
0
 protected AbstractOperation(IOperationContextFactory <IGraphLabsContext> operationFactory)
 {
     _operation = operationFactory.Create();
 }