Exemple #1
0
        public ActionResult Manage(LocalPasswordModel model)
        {
            ViewBag.ReturnUrl = Url.Action("Manage");
            if (ModelState.IsValid)
            {
                // 在某些出错情况下,ChangePassword 将引发异常,而不是返回 false。
                bool changePasswordSucceeded;
                try
                {
                    changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    using (var db = new AGPDataContext())
                    {
                        LogHelper.Log(db, User.Identity.Name, AGPDefine.LogLevelType.Info, AGPDefine.LogEventType.Update, AGPDefine.LogObjectType.User, "");
                    }
                    return(RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess }));
                }
                else
                {
                    ModelState.AddModelError("", "当前密码不正确或新密码无效。");
                }
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return(View(model));
        }
Exemple #2
0
        public ActionResult Register(RegisterModel model)
        {
            AddViewData();
            if (ModelState.IsValid)
            {
                // 尝试注册用户
                try
                {
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { RealName = model.RealName, State = (int)AGPDefine.CommitType.Normal });
                    Roles.AddUsersToRole(new string[] { model.UserName }, roles[model.UserRole - 1]);
                    WebSecurity.Login(model.UserName, model.Password);
                    using (var db = new AGPDataContext())
                    {
                        LogHelper.Log(db, User.Identity.Name, AGPDefine.LogLevelType.Info, AGPDefine.LogEventType.Register, AGPDefine.LogObjectType.User, null);
                    }
                    return(RedirectToAction("Index", "Home"));
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            model.UserName = string.Empty;
            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            return(View(model));
        }
Exemple #3
0
 public static bool Log(AGPDataContext db, string userName, AGPDefine.LogLevelType logLevel,
                        AGPDefine.LogEventType logEvent, AGPDefine.LogObjectType logObject, string message)
 {
     try
     {
         var u = db.Users.Single(a => a.UserName == userName);
         var l = db.LogLevels.Find((int)logLevel);
         var e = db.LogEvents.Find((int)logEvent);
         var o = db.LogObjects.Find((int)logObject);
         db.Logs.Add(new SystemLog()
         {
             User   = u,
             Time   = DateTime.Now,
             Level  = l,
             Event  = e,
             Object = o,
             Text   = message
         });
         db.SaveChanges();
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
        public JsonDotNetResult AGP_Log(int rows = 10, int page = 1)
        {
            RequireCorrentAction();

            WebSecurity.RequireRoles("管理员");

            using (var db = new AGPDataContext())
            {
                var logs = db.Logs
                           .Include(a => a.User)
                           .Include(a => a.Level)
                           .Include(a => a.Event)
                           .Include(a => a.Object)
                           .OrderBy(a => a.Time);
                var total  = logs.FutureCount();
                var result = logs
                             .Skip(rows * (page - 1))
                             .Take(rows).Future();

                var count = total.Value;
                if (count == 0)
                {
                    return(new JsonDotNetResult()
                    {
                        Data = JsonLogListModel.Empty()
                    });
                }

                return(new JsonDotNetResult()
                {
                    Data = JsonLogListModel.FromModel(count, result)
                });
            }
        }
        public JsonDotNetResult AGP_Question_All_Verify(int rows = 10, int page = 1)
        {
            RequireCorrentAction();

            WebSecurity.RequireRoles("审核员");

            using (var db = new AGPDataContext())
            {
                var questions = db.Questions
                                .Include(a => a.Owner)
                                .Include(a => a.Verifier)
                                .Include(a => a.Catalog)
                                .Where(a => a.State != (int)AGPDefine.CommitType.Normal)
                                .OrderBy(a => a.QuestionId);
                var total  = questions.FutureCount();
                var result = questions
                             .Skip(rows * (page - 1))
                             .Take(rows).Future();

                var count = total.Value;
                if (count == 0)
                {
                    return(new JsonDotNetResult()
                    {
                        Data = JsonQuestionListModel.Empty()
                    });
                }

                return(new JsonDotNetResult()
                {
                    Data = JsonQuestionListModel.FromModel(count, result)
                });
            }
        }
        public JsonDotNetResult AGP_Paper_All(int rows = 10, int page = 1)
        {
            RequireCorrentAction();

            WebSecurity.RequireRoles("教师");

            using (var db = new AGPDataContext())
            {
                var papers = db.Papers
                             .Include(a => a.Owner)
                             .Include(a => a.Verifier)
                             .OrderBy(a => a.PaperId)
                             .Where(a => a.State == (int)AGPDefine.CommitType.Normal);
                var total  = papers.FutureCount();
                var result = papers
                             .Skip(rows * (page - 1))
                             .Take(rows).Future();

                var count = total.Value;
                if (count == 0)
                {
                    return(new JsonDotNetResult()
                    {
                        Data = JsonPaperListModel.Empty()
                    });
                }

                return(new JsonDotNetResult()
                {
                    Data = JsonPaperListModel.FromModel(count, result)
                });
            }
        }
        public JsonDotNetResult AGP_Question_Details_Verify(int id = 0)
        {
            RequireCorrentAction();

            WebSecurity.RequireRoles("审核员");

            using (var db = new AGPDataContext())
            {
                var question = db.Questions
                               .Include(a => a.Owner)
                               .Include(a => a.Verifier)
                               .Include(a => a.Catalog)
                               .Where(a => a.QuestionId == id);

                if (question.Count() == 0)
                {
                    SetResponseStatusAndEndRequest(HttpStatusCode.NotFound);
                }

                return(new JsonDotNetResult()
                {
                    Data = JsonQuestionModel.FromModel(this, question.First())
                });
            }
        }
Exemple #8
0
        public ActionResult LogOff()
        {
            using (var db = new AGPDataContext())
            {
                LogHelper.Log(db, User.Identity.Name, AGPDefine.LogLevelType.Info, AGPDefine.LogEventType.Logout, AGPDefine.LogObjectType.User, null);
            }
            WebSecurity.Logout();

            return(RedirectToAction("Index", "Home"));
        }
        public static void DeleteQuestion(AGPDataContext db, int id)
        {
            var paper = db.Questions.Find(id);

            if (paper == null)
            {
                return;
            }

            //删除试题
            db.Questions.Remove(paper);
            db.SaveChanges();
        }
        public static void DeletePaper(AGPDataContext db, int id)
        {
            var paper = db.Papers.Find(id);

            if (paper == null)
            {
                return;
            }

            //删除相关项 - 外键关系表FK_Paper_Question
            db.PQs.Where(a => a.PaperId == id).Delete();

            //删除试卷
            db.Papers.Remove(paper);
            db.SaveChanges();
        }
        public static bool ValidateGenPaperStrategies(AGPDataContext db, AGPGenPaperStrategiesModel model, ModelStateDictionary ModelState)
        {
            bool error     = false;
            var  strExceed = "数量超过预期";
            var  questions = db.Questions.Include(a => a.Catalog);

            if (db.Courses.Count(a => a.CourseId == model.CourseId) == 0)
            {
                error = true;
                ModelState.AddModelError("CourseId", "未选择课程");
            }
            if (model.CatalogList.Count == 0 ||
                (from x in db.Catalogs
                 join y in model.CatalogList on x.CatalogId equals y
                 select x.CatalogId).Count() != model.CatalogList.Count)
            {
                error = true;
                ModelState.AddModelError("CatalogList", "类别不正确");
            }
            if (model.SingleSelectCount > questions.Count(a => a.Catalog.CatalogId == model.CourseId && a.TypeId == (int)AGPDefine.QuestionType.SingleSelect))
            {
                error = true;
                ModelState.AddModelError("SingleSelectCount", strExceed);
            }
            if (model.MultiSelectCount > questions.Count(a => a.Catalog.CatalogId == model.CourseId && a.TypeId == (int)AGPDefine.QuestionType.MultiSelect))
            {
                error = true;
                ModelState.AddModelError("MultiSelectCount", strExceed);
            }
            if (model.CheckCount > questions.Count(a => a.Catalog.CatalogId == model.CourseId && a.TypeId == (int)AGPDefine.QuestionType.Check))
            {
                error = true;
                ModelState.AddModelError("CheckCount", strExceed);
            }
            if (model.BlankCount > questions.Count(a => a.Catalog.CatalogId == model.CourseId && a.TypeId == (int)AGPDefine.QuestionType.Blank))
            {
                error = true;
                ModelState.AddModelError("BlankCount", strExceed);
            }
            if (model.ShortAnswerCount > questions.Count(a => a.Catalog.CatalogId == model.CourseId && a.TypeId == (int)AGPDefine.QuestionType.SingleSelect))
            {
                error = true;
                ModelState.AddModelError("ShortAnswerCount", strExceed);
            }
            return(error);
        }
        public JsonDotNetResult AGP_Get_Course_List()
        {
            RequireCorrentAction();

            WebSecurity.RequireRoles("教师");

            using (var db = new AGPDataContext())
            {
                var courses = from x in db.Courses
                              orderby x.CourseId
                              select new
                {
                    id  = x.CourseId,
                    val = x.Info.Name
                };

                return(new JsonDotNetResult()
                {
                    Data = courses.ToList()
                });
            }
        }
Exemple #13
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                using (var db = new AGPDataContext())
                {
                    var uc = db.Users.Count(a => a.UserName == model.UserName && a.State == (int)AGPDefine.CommitType.Normal);
                    if (uc == 0)
                    {
                        ModelState.AddModelError("UserName", ErrorCodeToString(MembershipCreateStatus.InvalidUserName));
                    }
                    else if (WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
                    {
                        LogHelper.Log(db, model.UserName, AGPDefine.LogLevelType.Info, AGPDefine.LogEventType.Login, AGPDefine.LogObjectType.User, null);
                        return(RedirectToLocal(returnUrl));
                    }
                }
            }

            // 如果我们进行到这一步时某个地方出错,则重新显示表单
            ModelState.AddModelError("", "提供的用户名或密码不正确。");
            return(View(model));
        }
        public JsonDotNetResult AGP_Get_Catalog_List(int id)
        {
            RequireCorrentAction();

            WebSecurity.RequireRoles("教师");

            using (var db = new AGPDataContext())
            {
                var courses = from x in db.Catalogs.Include(a => a.Course)
                              where x.Course.CourseId == id
                              orderby x.CatalogId
                              select new
                {
                    id  = x.CatalogId,
                    val = x.Info.Name
                };

                return(new JsonDotNetResult()
                {
                    Data = courses.ToList()
                });
            }
        }
            public SimpleMembershipInitializer()
            {
                Database.SetInitializer <AGPDataContext>(null);
                bool init = false;

                try
                {
                    using (var context = new AGPDataContext())
                    {
                        if (!context.Database.Exists())
                        {
                            // 创建不包含 Entity Framework 迁移架构的 SimpleMembership 数据库
                            ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                            init = true;
                        }
                    }

                    WebSecurity.InitializeDatabaseConnection("DefaultConnection", "User", "UserId", "UserName", true);

                    if (init)
                    {
                        using (var context = new AGPDataContext())
                        {
                            AGPDatabaseSeed.Seed(context);
                        }
                    }
                }
                catch (DbEntityValidationException)
                {
                    throw new Exception("数据验证失败");
                }
                catch (Exception ex)
                {
                    throw new InvalidOperationException("无法初始化 ASP.NET Simple Membership 数据库。有关详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=256588", ex);
                }
            }
        public static int GeneratePaper(AGPDataContext db, string owner, AGPGenPaperStrategiesModel model)
        {
            var dict = new Dictionary <AGPDefine.QuestionType, AGPGenPaperStrategiesCountModel>();

            dict.Add(AGPDefine.QuestionType.SingleSelect, new AGPGenPaperStrategiesCountModel()
            {
                Count = model.SingleSelectCount, Point = model.SingleSelectPoint
            });
            dict.Add(AGPDefine.QuestionType.MultiSelect, new AGPGenPaperStrategiesCountModel()
            {
                Count = model.MultiSelectCount, Point = model.MultiSelectPoint
            });
            dict.Add(AGPDefine.QuestionType.Check, new AGPGenPaperStrategiesCountModel()
            {
                Count = model.CheckCount, Point = model.CheckPoint
            });
            dict.Add(AGPDefine.QuestionType.Blank, new AGPGenPaperStrategiesCountModel()
            {
                Count = model.BlankCount, Point = model.BlankPoint
            });
            dict.Add(AGPDefine.QuestionType.ShortAnswer, new AGPGenPaperStrategiesCountModel()
            {
                Count = model.ShortAnswerCount, Point = model.ShortAnswerPoint
            });

            var user  = db.Users.Single(a => a.UserName == owner);
            var paper = new Paper()
            {
                Info = new ModelDescription()
                {
                    Name = model.Name
                },
                Time       = new ModelTime(),
                Difficulty = model.DifficultyType,
                Owner      = user,
                Points     = 0
            };

            db.Papers.Add(paper);
            db.SaveChanges();

            var allQuestions = from x in db.Questions.Include(a => a.Catalog).Include(a => a.Catalog.Course)
                               where x.State == (int)AGPDefine.CommitType.Normal
                               where x.Catalog.Course.CourseId == model.CourseId
                               join y in model.CatalogList on x.Catalog.CatalogId equals y
                               orderby Guid.NewGuid().ToString()
                               select x;

            var easyQuestion   = allQuestions.Where(IsEasy.Compile());
            var middleQuestion = allQuestions.Where(IsMiddle.Compile());
            var hardQuestion   = allQuestions.Where(IsHard.Compile());

            var selectedQuestion = new List <Paper_Question_Relationship>();

            foreach (var kv in dict)
            {
                if (kv.Value.Count == 0 || kv.Value.Point == 0)
                {
                    continue;
                }

                var     easy     = (int)Math.Ceiling(kv.Value.Count * DiffAlloc[model.DifficultyType].Item1);
                var     middle   = (int)Math.Ceiling(kv.Value.Count * DiffAlloc[model.DifficultyType].Item2);
                var     hard     = kv.Value.Count - easy - middle;
                decimal perPoint = (decimal)kv.Value.Point / (decimal)kv.Value.Count;

                var middleQ = (from x in middleQuestion
                               where x.TypeId == (int)kv.Key
                               select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = perPoint
                }).Take(middle);
                var hardQ = (from x in hardQuestion
                             where x.TypeId == (int)kv.Key
                             select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = perPoint
                }).Take(hard);
                var easyQ = (from x in easyQuestion
                             where x.TypeId == (int)kv.Key
                             select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = perPoint
                }).Take(kv.Value.Count - middleQ.Count() - hardQ.Count());
                selectedQuestion.AddRange(easyQ);
                selectedQuestion.AddRange(middleQ);
                selectedQuestion.AddRange(hardQ);
            }

            foreach (var pq in selectedQuestion)
            {
                db.PQs.Add(pq);
            }

            db.Papers.Where(a => a.PaperId == paper.PaperId).Update(a => new Paper
            {
                Points = selectedQuestion.Sum(b => b.Points)
            });

            db.SaveChanges();

            return(paper.PaperId);
        }
Exemple #17
0
        public static MvcHtmlString AGP_DisplayForPaper(this HtmlHelper html, int id)
        {
            using (var db = new AGPDataContext())
            {
                var paper = db.Papers.Find(id);
                if (paper == null)
                {
                    return(new MvcHtmlString("抱歉,无考卷信息。"));
                }

                var title = paper.Info.Name;                 // 试卷名称
                var PQs   = from x in db.PQs.Include(a => a.Question).Include(a => a.Question.Catalog)
                            where x.PaperId == paper.PaperId
                            select x;

                var model = ConvertHelper.ConvertPaperForPrint(title, ConvertHelper.DefaultSubTitle, PQs);

                var sb       = new StringBuilder();
                var document = new TagBuilder("div");
                document.AddCssClass("paper");

                //主标题和副标题
                {
                    var tag_title = new TagBuilder("h2")
                    {
                        InnerHtml = !string.IsNullOrEmpty(model.Title) ? HttpUtility.HtmlEncode(model.Title) : string.Empty
                    };
                    tag_title.AddCssClass("text-center");
                    sb.AppendLine(tag_title.ToString());
                    var tag_subtitle = new TagBuilder("h5")
                    {
                        InnerHtml = !string.IsNullOrEmpty(model.SubTitle) ? HttpUtility.HtmlEncode(model.SubTitle) : string.Empty
                    };
                    tag_subtitle.AddCssClass("text-center");
                    sb.AppendLine(tag_subtitle.ToString());
                }

                //题目
                {
                    foreach (var q in model.Items)
                    {
                        var question_div = new TagBuilder("div");
                        question_div.AddCssClass("question");

                        var tag_group = new TagBuilder("div");

                        if (q.IsGroup())
                        {
                            tag_group.InnerHtml = !string.IsNullOrEmpty(q.GetTitle()) ? HttpUtility.HtmlEncode(q.GetTitle()) : string.Empty;
                            tag_group.AddCssClass("question-nav");
                        }
                        else
                        {
                            tag_group.AddCssClass("question-group");

                            var tag_content = new TagBuilder("div")
                            {
                                InnerHtml = !string.IsNullOrEmpty(q.GetTitle()) ? HttpUtility.HtmlEncode(q.GetTitle()) : string.Empty
                            };
                            tag_content.AddCssClass("question-content");
                            tag_content.InnerHtml = q.GetId().ToString() + ". " + tag_content.InnerHtml;

                            if (q.HasOptions())
                            {
                                var tag_ol = new TagBuilder("ol");
                                foreach (var o in q.GetOptions())
                                {
                                    var tag_option = new TagBuilder("li")
                                    {
                                        InnerHtml = !string.IsNullOrEmpty(o) ? HttpUtility.HtmlEncode(o) : string.Empty
                                    };
                                    tag_ol.InnerHtml += tag_option.ToString();
                                }
                                tag_content.InnerHtml += tag_ol.ToString();
                            }

                            var tag_summary = new TagBuilder("div");
                            tag_summary.AddCssClass("question-summary");

                            {
                                var tag_summary_item = new TagBuilder("div");
                                tag_summary_item.AddCssClass("question-summary-left");

                                tag_summary_item.InnerHtml = string.Format("编号:{0}", q.GetUniqueId());
                                tag_summary.InnerHtml     += tag_summary_item.ToString();

                                tag_summary_item.InnerHtml = string.Format("分类:{0}", q.GetCatalog());
                                tag_summary.InnerHtml     += tag_summary_item.ToString();

                                tag_summary_item.InnerHtml = string.Format("难度:{0}", q.GetDifficulty());
                                tag_summary.InnerHtml     += tag_summary_item.ToString();

                                tag_summary_item.InnerHtml = string.Format("更新时间:{0}", q.GetUpdateTime().ToShortDateString());
                                tag_summary.InnerHtml     += tag_summary_item.ToString();

                                var answer = ConvertHelper.GetAnswerFromQuestion(q.GetQuestionType(), q.GetAnswer());

                                var tag_ask_for_answer = new TagBuilder("div");
                                tag_ask_for_answer.InnerHtml = "查看答案";
                                tag_ask_for_answer.AddCssClass("question-summary-right");
                                tag_ask_for_answer.MergeAttribute("data-toggle", "tooltip");
                                tag_ask_for_answer.MergeAttribute("title", string.Format("答案:{0}",
                                                                                         string.IsNullOrEmpty(answer) ? "略" : answer));

                                tag_summary.InnerHtml += tag_ask_for_answer.ToString();
                            }

                            tag_group.InnerHtml += tag_summary.ToString();
                            tag_group.InnerHtml += tag_content.ToString();
                        }

                        question_div.InnerHtml += tag_group.ToString();
                        sb.AppendLine(question_div.ToString());
                    }
                }

                document.InnerHtml = sb.ToString();
                return(MvcHtmlString.Create(document.ToString()));
            }
        }
Exemple #18
0
        public static int GeneratePaper(AGPDataContext context, string owner, AGPGenPaperStrategiesModel model)
        {
            var user  = context.Users.Single(a => a.UserName == owner);
            var sum   = model.SingleSelectPoint + model.MultiSelectPoint + model.CheckPoint + model.BlankPoint + model.ShortAnswerPoint;
            var paper = new Paper()
            {
                Info = new ModelDescription()
                {
                    Name = model.Name
                },
                Time       = new ModelTime(),
                Points     = sum,
                Difficulty = model.DifficultyType,
            };

            context.Papers.Add(paper);
            context.SaveChanges();

            var allAuestions = context.Questions.Include(a => a.Catalog)
                               .Where(a => a.Catalog.CatalogId == model.CatalogId)
                               .OrderBy(a => new Guid());
            var easyQuestion   = allAuestions.Where(IsEasy.Compile());
            var middleQuestion = allAuestions.Where(IsMiddle.Compile());
            var hardQuestion   = allAuestions.Where(IsHard.Compile());

            var selectedQuestion = new List <Paper_Question_Relationship>();

            if (model.DifficultyType == 0)
            {
                int easy = 0, middle = 0, hard = 0;

                easy   = (int)(model.SingleSelectCount * 0.8);
                middle = (int)(model.SingleSelectCount * 0.1);
                hard   = model.SingleSelectCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.SingleSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.SingleSelectPoint / model.SingleSelectCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.SingleSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.SingleSelectPoint / model.SingleSelectCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.SingleSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.SingleSelectPoint / model.SingleSelectCount
                }).Take(model.SingleSelectCount - selectedQuestion.Count()));

                easy   = (int)(model.MultiSelectCount * 0.8);
                middle = (int)(model.MultiSelectCount * 0.1);
                hard   = model.MultiSelectCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.MultiSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.MultiSelectPoint / model.MultiSelectCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.MultiSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.MultiSelectPoint / model.MultiSelectCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.MultiSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.MultiSelectPoint / model.MultiSelectCount
                }).Take(model.MultiSelectCount - selectedQuestion.Count()));

                easy   = (int)(model.CheckCount * 0.8);
                middle = (int)(model.CheckCount * 0.1);
                hard   = model.CheckCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Check
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.CheckPoint / model.CheckCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Check
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.CheckPoint / model.CheckCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Check
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.CheckPoint / model.CheckCount
                }).Take(model.CheckCount - selectedQuestion.Count()));

                easy   = (int)(model.BlankCount * 0.8);
                middle = (int)(model.BlankCount * 0.1);
                hard   = model.BlankCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Blank
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.BlankPoint / model.BlankCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Blank
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.BlankPoint / model.BlankCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Blank
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.BlankPoint / model.BlankCount
                }).Take(model.BlankCount - selectedQuestion.Count()));

                easy   = (int)(model.ShortAnswerCount * 0.8);
                middle = (int)(model.ShortAnswerCount * 0.1);
                hard   = model.ShortAnswerCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.ShortAnswer
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.ShortAnswerPoint / model.ShortAnswerCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.ShortAnswer
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.ShortAnswerPoint / model.ShortAnswerCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.ShortAnswer
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.ShortAnswerPoint / model.ShortAnswerCount
                }).Take(model.ShortAnswerCount - selectedQuestion.Count()));
            }
            else if (model.DifficultyType == 1)
            {
                int easy = 0, middle = 0, hard = 0;

                easy   = (int)(model.SingleSelectCount * 0.7);
                middle = (int)(model.SingleSelectCount * 0.2);
                hard   = model.SingleSelectCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.SingleSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.SingleSelectPoint / model.SingleSelectCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.SingleSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.SingleSelectPoint / model.SingleSelectCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.SingleSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.SingleSelectPoint / model.SingleSelectCount
                }).Take(model.SingleSelectCount - selectedQuestion.Count()));

                easy   = (int)(model.MultiSelectCount * 0.7);
                middle = (int)(model.MultiSelectCount * 0.2);
                hard   = model.MultiSelectCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.MultiSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.MultiSelectPoint / model.MultiSelectCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.MultiSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.MultiSelectPoint / model.MultiSelectCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.MultiSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.MultiSelectPoint / model.MultiSelectCount
                }).Take(model.MultiSelectCount - selectedQuestion.Count()));

                easy   = (int)(model.CheckCount * 0.7);
                middle = (int)(model.CheckCount * 0.2);
                hard   = model.CheckCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Check
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.CheckPoint / model.CheckCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Check
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.CheckPoint / model.CheckCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Check
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.CheckPoint / model.CheckCount
                }).Take(model.CheckCount - selectedQuestion.Count()));

                easy   = (int)(model.BlankCount * 0.7);
                middle = (int)(model.BlankCount * 0.2);
                hard   = model.BlankCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Blank
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.BlankPoint / model.BlankCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Blank
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.BlankPoint / model.BlankCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Blank
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.BlankPoint / model.BlankCount
                }).Take(model.BlankCount - selectedQuestion.Count()));

                easy   = (int)(model.ShortAnswerCount * 0.7);
                middle = (int)(model.ShortAnswerCount * 0.2);
                hard   = model.ShortAnswerCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.ShortAnswer
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.ShortAnswerPoint / model.ShortAnswerCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.ShortAnswer
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.ShortAnswerPoint / model.ShortAnswerCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.ShortAnswer
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.ShortAnswerPoint / model.ShortAnswerCount
                }).Take(model.ShortAnswerCount - selectedQuestion.Count()));
            }
            else if (model.DifficultyType == 2)
            {
                int easy = 0, middle = 0, hard = 0;

                easy   = (int)(model.SingleSelectCount * 0.6);
                middle = (int)(model.SingleSelectCount * 0.1);
                hard   = model.SingleSelectCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.SingleSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.SingleSelectPoint / model.SingleSelectCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.SingleSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.SingleSelectPoint / model.SingleSelectCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.SingleSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.SingleSelectPoint / model.SingleSelectCount
                }).Take(model.SingleSelectCount - selectedQuestion.Count()));

                easy   = (int)(model.MultiSelectCount * 0.6);
                middle = (int)(model.MultiSelectCount * 0.1);
                hard   = model.MultiSelectCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.MultiSelect && x.Difficulty == 2
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.MultiSelectPoint / model.MultiSelectCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.MultiSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.MultiSelectPoint / model.MultiSelectCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.MultiSelect
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.MultiSelectPoint / model.MultiSelectCount
                }).Take(model.MultiSelectCount - selectedQuestion.Count()));

                easy   = (int)(model.CheckCount * 0.6);
                middle = (int)(model.CheckCount * 0.1);
                hard   = model.CheckCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Check && x.Difficulty == 2
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.CheckPoint / model.CheckCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Check
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.CheckPoint / model.CheckCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Check
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.CheckPoint / model.CheckCount
                }).Take(model.CheckCount - selectedQuestion.Count()));

                easy   = (int)(model.BlankCount * 0.6);
                middle = (int)(model.BlankCount * 0.1);
                hard   = model.BlankCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Blank && x.Difficulty == 2
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.BlankPoint / model.BlankCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Blank
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.BlankPoint / model.BlankCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.Blank
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.BlankPoint / model.BlankCount
                }).Take(model.BlankCount - selectedQuestion.Count()));

                easy   = (int)(model.ShortAnswerCount * 0.6);
                middle = (int)(model.ShortAnswerCount * 0.1);
                hard   = model.ShortAnswerCount - easy - middle;
                selectedQuestion.AddRange((from x in middleQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.ShortAnswer && x.Difficulty == 2
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.ShortAnswerPoint / model.ShortAnswerCount
                }).Take(middle));
                selectedQuestion.AddRange((from x in hardQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.ShortAnswer
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.ShortAnswerPoint / model.ShortAnswerCount
                }).Take(hard));
                selectedQuestion.AddRange((from x in easyQuestion
                                           where x.TypeId == (int)AGPDefine.QuestionType.ShortAnswer
                                           select new Paper_Question_Relationship()
                {
                    PaperId = paper.PaperId,
                    QuestionId = x.QuestionId,
                    Points = (decimal)model.ShortAnswerPoint / model.ShortAnswerCount
                }).Take(model.ShortAnswerCount - selectedQuestion.Count()));
            }
            foreach (var pq in selectedQuestion)
            {
                context.PQs.Add(pq);
            }
            context.SaveChanges();
            return(paper.PaperId);
        }
        public static Document TransferPaperToWord(string user, int id)
        {
            using (var db = new AGPDataContext())
            {
                var paper = db.Papers.Find(id);
                if (paper == null)
                {
                    return(null);
                }

                LogHelper.Log(db, user, AGPDefine.LogLevelType.Info, AGPDefine.LogEventType.Other, AGPDefine.LogObjectType.Paper, "下载试卷");

                var title = paper.Info.Name;                 // 试卷名称
                var PQs   = from x in db.PQs.Include(a => a.Question).Include(a => a.Question.Catalog)
                            where x.PaperId == paper.PaperId
                            select x;

                var model = ConvertHelper.ConvertPaperForPrint(title, ConvertHelper.DefaultSubTitle, PQs);

                var doc     = new Document();
                var builder = new DocumentBuilder(doc);

                //主标题和副标题
                {
                    builder.Bold      = true;
                    builder.Font.Size = 20;
                    builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                    builder.Writeln(model.Title);
                    builder.InsertBreak(BreakType.LineBreak);

                    builder.Bold      = false;
                    builder.Font.Size = 12;
                    builder.Writeln(model.SubTitle);
                    builder.InsertBreak(BreakType.LineBreak);
                }

                builder.ParagraphFormat.Alignment = ParagraphAlignment.Left;

                //题目
                {
                    foreach (var q in model.Items)
                    {
                        if (q.IsGroup())
                        {
                            builder.InsertBreak(BreakType.LineBreak);
                            builder.Bold      = true;
                            builder.Font.Size = 12;
                            builder.Writeln(q.GetTitle());
                            builder.InsertBreak(BreakType.LineBreak);
                        }
                        else
                        {
                            builder.Bold      = false;
                            builder.Font.Size = 11;
                            builder.Writeln(string.Format("{0}. {1}", q.GetId(), q.GetTitle()));

                            if (q.HasOptions())
                            {
                                var c = 'A';
                                foreach (var o in q.GetOptions())
                                {
                                    builder.Write(string.Format("  {0}. {1}", c, o));
                                    c++;
                                }
                                builder.Writeln();
                            }

                            builder.InsertBreak(BreakType.LineBreak);
                        }
                    }
                }

                return(doc);
            }
        }
        public static bool AddQuestion(AGPDataContext db, string user, QuestionProxyModel model, ModelStateDictionary ModelState, out int id)
        {
            bool success = true;

            id = 0;
            try
            {
                var c = db.Catalogs.Find(model.CatalogId);
                if (c == null)
                {
                    ModelState.AddModelError("CatalogId", "类别不正确");
                    return(false);
                }
                int TypeId = model.TypeId;
                if (TypeId == 0)
                {
                    ModelState.AddModelError("TypeId", "题型不正确");
                    return(false);
                }
                var      QType = (AGPDefine.QuestionType)Enum.ToObject(typeof(AGPDefine.QuestionType), TypeId);
                var      u     = db.Users.Single(a => a.UserName == user);
                Question q     = new Question();
                switch (QType)
                {
                case AGPDefine.QuestionType.SingleSelect:
                {
                    var o   = model.Option.Split('$').ToList();
                    var ans = model.Answer.ToList().ConvertAll <int>(a => a - 'A' + 1).Distinct().OrderBy(a => a).ToList();
                    if (o.Count != 1)
                    {
                        throw new QuestionModelException();
                    }
                    if (!(ans.First() > 0 && ans.First() <= o.Count))
                    {
                        throw new QuestionModelException();
                    }
                    q = new AGPQuestionModel_SingleSelect()
                    {
                        Caption     = model.Name, Option = o, Answer = ans.First(),
                        User        = u, Catalog = c, Points = model.Points, Label = model.Label,
                        Description = model.Description, Difficulty = model.Difficulty
                    }.ConvertToQuestion();
                }
                break;

                case AGPDefine.QuestionType.MultiSelect:
                {
                    var o   = model.Option.Split('$').ToList();
                    var ans = model.Answer.ToList().ConvertAll <int>(a => a - 'A' + 1).Distinct().OrderBy(a => a).ToList();
                    if (o.Count <= 1 || o.Count > 26)
                    {
                        throw new QuestionModelException();
                    }
                    if (!(ans.All(a => a > 0 && a <= o.Count)))
                    {
                        throw new QuestionModelException();
                    }
                    q = new AGPQuestionModel_MultiSelect()
                    {
                        Caption     = model.Name, Option = o, Answer = ans,
                        User        = u, Catalog = c, Points = model.Points, Label = model.Label,
                        Description = model.Description, Difficulty = model.Difficulty
                    }.ConvertToQuestion();
                }
                break;

                case AGPDefine.QuestionType.Check:
                {
                    q = new AGPQuestionModel_Check()
                    {
                        Caption     = model.Name, Answer = string.Compare(model.Answer, "true", true) == 0,
                        User        = u, Catalog = c, Points = model.Points, Label = model.Label,
                        Description = model.Description, Difficulty = model.Difficulty
                    }.ConvertToQuestion();
                }
                break;

                case AGPDefine.QuestionType.Blank:
                {
                    q = new AGPQuestionModel_Blank()
                    {
                        Caption     = model.Name, Answer = model.Answer,
                        User        = u, Catalog = c, Points = model.Points, Label = model.Label,
                        Description = model.Description, Difficulty = model.Difficulty
                    }.ConvertToQuestion();
                }
                break;

                case AGPDefine.QuestionType.ShortAnswer:
                {
                    q = new AGPQuestionModel_ShortAnswer()
                    {
                        Caption     = model.Name, Answer = model.Answer,
                        User        = u, Catalog = c, Points = model.Points, Label = model.Label,
                        Description = model.Description, Difficulty = model.Difficulty
                    }.ConvertToQuestion();
                }
                break;

                default:
                    break;
                }

                q.State = (int)AGPDefine.CommitType.Insert;
                db.Questions.Add(q);
                db.SaveChanges();
                id = q.QuestionId;
            }
            catch (Exception ex)
            {
                success = false;
                ModelState.AddModelError("", ex.Message);
            }
            return(success);
        }