Exemple #1
0
        public ExamDTO ToDTO(ExamEntity ef)
        {
            ExamDTO dto = new ExamDTO();

            dto.Address         = ef.Address;
            dto.ClassName       = ef.ClassName;
            dto.ExamTime        = ef.ExamTime;
            dto.MajorName       = ef.MajorName;
            dto.PlaceNum        = ef.PlaceNum;
            dto.SchoolName      = ef.SchoolName;
            dto.SFZCode         = ef.SFZCode;
            dto.StuName         = ef.StuName;
            dto.SysName         = ef.SysName;
            dto.TypeId          = ef.TypeId;
            dto.TypeName        = ef.ExamTypes.Name;
            dto.TypeDescription = ef.ExamTypes.Description;
            dto.ZKZCode         = ef.ZKZCode;
            dto.IsLook          = ef.IsLook;
            dto.LLExamAddress   = ef.LLExamAddress;
            dto.LLExamTime      = ef.LLExamTime;
            dto.LLExamPlaceNum  = ef.LLExamPlaceNum;
            dto.StuId           = ef.StuId;
            dto.Id    = ef.Id;
            dto.llzwh = ef.llzwh;
            return(dto);
        }
Exemple #2
0
        public JsonResult GetInformationGroup(int examId)
        {
            string functionName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            try
            {
                //Check id exam exist in the database
                if (!_examRepository.ExamExist(examId))
                {
                    Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.examNotFound));
                    return(Json(MessageResult.GetMessage(MessageType.EXAM_NOT_FOUND)));
                }

                if (!ModelState.IsValid)
                {
                    Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.notFound));
                    return(Json(MessageResult.GetMessage(MessageType.NOT_FOUND)));
                }

                //This is get all information of exam by Id
                ExamEntity examEntity = _examRepository.GetExamById(examId);

                return(Json(examEntity));
            }
            catch (Exception ex)
            {
                Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(ex.Message));
                return(Json(MessageResult.ShowServerError(ex.Message)));
            }
        }
Exemple #3
0
        public ExamEntity getexambyname(string name, int numPreguntas)
        {
            DataTable     dataTable = new DataTable();
            SqlConnection con = new SqlConnection("Server= arquisqlserver.database.windows.net; Database= arquitectura;User Id=arquisqlserver;Password = arquitectura2019!;"); int i = 0;
            //insert the information to the database
            StringBuilder stringquery = new StringBuilder();

            stringquery.Append("select  * from Examen ");
            stringquery.Append("where NombreExamen= '" + name + "'");


            ExamEntity Exam = new ExamEntity();


            string     query = stringquery.ToString();
            SqlCommand cmd   = new SqlCommand(query, con);


            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();

            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    Exam.idexamen   = dr.GetInt32(dr.GetOrdinal("IdExamen"));
                    Exam.nombre     = dr.GetString((dr.GetOrdinal("NombreExamen")));
                    Exam.areaexamen = dr.GetString((dr.GetOrdinal("AreaExamen")));
                }
                con.Close();
            }
            return(Exam);
        }
Exemple #4
0
 public long Add(ExamDTO model)
 {
     using (MyDbContext ctx = new MyDbContext())
     {
         ExamEntity ef = new ExamEntity();
         ef.Address        = model.Address;
         ef.ClassName      = model.ClassName;
         ef.ExamTime       = model.ExamTime;
         ef.MajorName      = model.MajorName;
         ef.PlaceNum       = model.PlaceNum;
         ef.SchoolName     = model.SchoolName;
         ef.SFZCode        = model.SFZCode;
         ef.StuName        = model.StuName;
         ef.SysName        = model.SysName;
         ef.ZKZCode        = model.ZKZCode;
         ef.TypeId         = model.TypeId;
         ef.LLExamAddress  = model.LLExamAddress;
         ef.LLExamTime     = model.LLExamTime;
         ef.LLExamPlaceNum = model.LLExamPlaceNum;
         ef.StuId          = model.StuId;
         ef.llzwh          = model.llzwh;
         ctx.Exams.Add(ef);
         ctx.SaveChanges();
         return(ef.Id);
     }
 }
Exemple #5
0
        /// <summary>
        /// 根据ID,返回一个Exam对象
        /// </summary>
        /// <param name="id">id</param>
        /// <returns>Exam对象</returns>
        public ExamEntity Get_ExamEntity(long id)
        {
            ExamEntity _obj = null;

            SqlParameter[] _param =
            {
                new SqlParameter("@Id", SqlDbType.BigInt)
            };
            _param[0].Value = id;
            string sqlStr = "select * from Exam with(nolock) where Id=@Id  and isactive=1 ";

            using (SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.Connection, CommandType.Text, sqlStr, _param))
            {
                while (dr.Read())
                {
                    _obj = Populate_ExamEntity_FromDr(dr);
                }

                if (!dr.IsClosed)
                {
                    dr.Close();
                }
            }
            return(_obj);
        }
        public ExamEntity getExambyname(string nombreexamen, int numPreguntas)
        {
            ExamBL exambl = new ExamBL();
            List <ResponseEntity> correctas   = new List <ResponseEntity>();
            List <ResponseEntity> incorrectas = new List <ResponseEntity>();

            QuestionBL            questionbl = new QuestionBL();
            ResponseBL            responsebl = new ResponseBL();
            ExamEntity            exam       = exambl.getexambyname(nombreexamen, numPreguntas);
            List <QuestionEntity> questions  = questionbl.GetQuestionsByExamID(exam.idexamen, numPreguntas);

            foreach (QuestionEntity question in questions)
            {
                List <ResponseEntity> responses = responsebl.GetResponseFromQuestionID(question.idPregunta);
                foreach (ResponseEntity res in responses)
                {
                    if (res.RespuestaCorrecta > 0)
                    {
                        correctas.Add(res);
                    }
                    else if (res.RespuestaCorrecta < 1)
                    {
                        incorrectas.Add(res);
                    }
                }
                exam.correctas   = correctas;
                exam.incorrectas = incorrectas;
            }

            return(exam);
        }
Exemple #7
0
        /// <summary>
        /// 向数据库中插入一条新记录。
        /// </summary>
        /// <param name="_ExamModel">Exam实体</param>
        /// <returns>新插入记录的编号</returns>
        public long Insert(ExamEntity _ExamModel)
        {
            string sqlStr = "insert into Exam([Id],[ExamTitle],[Type],[SubType],[CreateTime],[UpdateTime],[IsActive]) values(@Id,@ExamTitle,@Type,@SubType,@CreateTime,@UpdateTime,@IsActive) select @Id";
            long   res;

            SqlParameter[] _param =
            {
                new SqlParameter("@Id",         SqlDbType.BigInt),
                new SqlParameter("@ExamTitle",  SqlDbType.VarChar),
                new SqlParameter("@Type",       SqlDbType.SmallInt),
                new SqlParameter("@SubType",    SqlDbType.SmallInt),
                new SqlParameter("@CreateTime", SqlDbType.DateTime),
                new SqlParameter("@UpdateTime", SqlDbType.DateTime),
                new SqlParameter("@IsActive",   SqlDbType.SmallInt)
            };
            _param[0].Value = _ExamModel.Id;
            _param[1].Value = _ExamModel.ExamTitle;
            _param[2].Value = _ExamModel.Type;
            _param[3].Value = _ExamModel.SubType;
            _param[4].Value = _ExamModel.CreateTime;
            _param[5].Value = _ExamModel.UpdateTime;
            _param[6].Value = _ExamModel.IsActive;
            res             = Convert.ToInt64(SqlHelper.ExecuteScalar(SqlHelper.Connection, CommandType.Text, sqlStr, _param));
            return(res);
        }
        public void AllQuestionsShouldHaveExplanationsTest()
        {
            ExamEntity exam = ExamsToCheck.FirstOrDefault(f => f.Code == "AZ-900");

            foreach (QuestionEntity question in exam.Questions)
            {
                Assert.False(string.IsNullOrWhiteSpace(question.ExplanationText));
            }
        }
        public ActionResult Create([Bind(Include = "Name,PassLine,RetryCostScore,MinutesLimit,RewardMemberScore")] ExamEntity entity)
        {
            if (!ModelState.IsValid)
            {
                return(View(entity));
            }
            var result = _examContract.Insert(entity);

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Exemple #10
0
        public ActionResult Update([Bind(Include = "Id,Name,PassLine,RetryCostScore,MinutesLimit,RewardMemberScore")] ExamEntity dto)
        {
            var entity = _examContract.Entities.FirstOrDefault(e => e.Id == dto.Id);

            entity.Name              = dto.Name;
            entity.PassLine          = dto.PassLine;
            entity.RetryCostScore    = dto.RetryCostScore;
            entity.RewardMemberScore = dto.RewardMemberScore;
            var result = _examContract.Update(new ExamEntity[] { entity });

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Exemple #11
0
        /// <summary>
        /// 得到  exam 数据实体
        /// </summary>
        /// <param name="dr">dr</param>
        /// <returns>exam 数据实体</returns>
        public ExamEntity Populate_ExamEntity_FromDr(IDataReader dr)
        {
            ExamEntity Obj = new ExamEntity();

            Obj.Id         = ((dr["Id"]) == DBNull.Value) ? 0 : (long)dr["Id"];
            Obj.ExamTitle  = dr["ExamTitle"].ToString();
            Obj.Type       = ((dr["Type"]) == DBNull.Value) ? (short)0 : (short)dr["Type"];
            Obj.SubType    = ((dr["SubType"]) == DBNull.Value) ? (short)0 : (short)dr["SubType"];
            Obj.CreateTime = ((dr["CreateTime"]) == DBNull.Value) ? Convert.ToDateTime("1900-1-1") : Convert.ToDateTime(dr["CreateTime"]);
            Obj.UpdateTime = ((dr["UpdateTime"]) == DBNull.Value) ? Convert.ToDateTime("1900-1-1") : Convert.ToDateTime(dr["UpdateTime"]);
            Obj.IsActive   = ((dr["IsActive"]) == DBNull.Value) ? (short)0 : (short)dr["IsActive"];

            return(Obj);
        }
        public void CheckForSimilarityOfQuestionsTest()
        {
            List <ExamEntity> exams = DataGenerator.Initialize(null);

            ExamEntity theExam = exams.FirstOrDefault(e => e.Code.Equals("az-900", StringComparison.CurrentCultureIgnoreCase));

            List <QuestionEntity> allquestions = theExam.Questions;

            List <double> distances = new List <double>();

            List <Tuple <QuestionEntity, QuestionEntity, string> > duplicatesLists =
                new List <Tuple <QuestionEntity, QuestionEntity, string> >();

            List <Tuple <QuestionEntity, QuestionEntity, double> > distanceListAllQuestions =
                new List <Tuple <QuestionEntity, QuestionEntity, double> >();

            for (int i = 0; i < allquestions.Count; i++)
            {
                for (int j = i + 1; j < allquestions.Count; j++)
                {
                    QuestionEntity q1 = allquestions[i];
                    QuestionEntity q2 = allquestions[j];

                    string text1 = q1.ContentText.Replace(" ", string.Empty) + q1.AnswerText.Replace(" ", string.Empty);

                    string text2 = q2.ContentText.Replace(" ", string.Empty) + q2.AnswerText.Replace(" ", string.Empty);

                    string helperTextForDebug = $"{q1.Id + 1}{text1}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{q2.Id + 1}{text2}";

                    double distance = LevenshteinDistance.CalculateSimilarity(text1, text2);
                    distances.Add(Math.Round(distance, 2));
                    if (distance > 0.81)
                    {
                        duplicatesLists.Add(new Tuple <QuestionEntity, QuestionEntity, string>(
                                                q1, q2, distance.ToString()));

                        string textToSee = $"{text1} {Environment.NewLine}{Environment.NewLine} {text2}";
                    }

                    distanceListAllQuestions.Add(new Tuple <QuestionEntity, QuestionEntity, double>(
                                                     q1, q2, distance));
                }
            }
            string duplicateResultHelper = string.Join("\r\n\r\n\r\n", duplicatesLists.Select(s => s.Item1.ContentText + " ----- " + s.Item2.ContentText).ToList());

            distances = distances.OrderByDescending(d => d).ToList();

            distanceListAllQuestions = distanceListAllQuestions.OrderByDescending(d => d.Item3).ToList();
        }
Exemple #13
0
        public JsonResult GetListExam(int accountId, int groupId)
        {
            string functionName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            try
            {
                //Check value enter id group
                if (accountId == 0 || groupId == 0)
                {
                    Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.emailAndPasswordWrong));
                    return(Json(MessageResult.GetMessage(MessageType.EMAIL_AND_PASSWORD_WRONG)));
                }

                List <AccountExamEntity> listAccountExams = _accountExamRepository.GetAccountExamByAccountId(accountId);

                if (listAccountExams == null)
                {
                    Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.notInformationAccount));
                    return(Json(MessageResult.GetMessage(MessageType.ACCOUNT_NOT_FOUND)));
                }

                List <ExamResult> examResults = new List <ExamResult>();
                GroupOwnerEntity  ownerEntity = _groupOwnerRepository.GetGroupOwnerByGroupId(groupId);
                foreach (var accountExam in listAccountExams)
                {
                    ExamEntity examEntity = _examRepository.GetExamById(accountExam.ExamId);
                    if (examEntity.GroupId == groupId)
                    {
                        ExamResult result = new ExamResult();
                        result.examId = accountExam.ExamId;
                        result.name   = examEntity.Name;
                        result.status = accountExam.IsStatus;
                        examResults.Add(result);
                    }
                }

                ExamResultHasOwner examResultHasOwner = new ExamResultHasOwner();
                examResultHasOwner.ownerId     = ownerEntity.AccountId;
                examResultHasOwner.examResults = examResults;
                return(Json(examResultHasOwner));
            }
            catch (Exception ex)
            {
                Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(ex.Message));
                return(Json(MessageResult.ShowServerError(ex.Message)));
            }
        }
        public void CheckForSimilarityOfCustomTextTest()
        {
            List <ExamEntity> exams = DataGenerator.Initialize(null);

            ExamEntity theExam = exams.FirstOrDefault(e => e.Code.Equals("AZ-900"));

            List <QuestionEntity> allquestions = theExam.Questions;

            List <double> distances = new List <double>();

            List <Tuple <QuestionEntity, QuestionEntity, string> > duplicatesLists =
                new List <Tuple <QuestionEntity, QuestionEntity, string> >();

            for (int i = 0; i < allquestions.Count; i++)
            {
                QuestionEntity q1 = allquestions[i];

                string text1 = q1.ContentText.Replace(" ", string.Empty) + q1.AnswerText.Replace(" ", string.Empty);

                string questionText = @"This question requires that you evaluate the underlined text to determine if it is correct.
When you are implementing a software as a service (SaaS) solution, you are responsible for configuring high availability.
Instructions: Review the underlined text. If it makes the statement correct, select If the statement is incorrect, select the answer choice that makes the statement correct.
A.No change is needed.
B.defining scalability rules
C.installing the SaaS solution
D.configuring the SaaS solution


";
                string answerText   = string.Empty;

                string text2 = questionText.Replace(" ", string.Empty); // + answerText.Replace(" ", string.Empty);

                string helperTextForDebug = $"{q1.Id + 1}{text1}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{q1.Id + 1}{text2}";

                double distance = LevenshteinDistance.CalculateSimilarity(text1, text2);
                distances.Add(Math.Round(distance, 2));
                if (distance > 0.81)
                {
                    duplicatesLists.Add(new Tuple <QuestionEntity, QuestionEntity, string>(
                                            q1, q1, distance.ToString()));

                    string textToSee = $"{text1} {Environment.NewLine}{Environment.NewLine} {text2}";
                }
            }
            distances = distances.OrderByDescending(d => d).ToList();
        }
        public JsonResult GetInformationAccount(int accountId)
        {
            string functionName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            try
            {
                //Check id account exist in the database
                if (!_accountRepository.AccountExists(accountId))
                {
                    Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.accountNotFound));
                    return(Json(MessageResult.GetMessage(MessageType.ACCOUNT_NOT_FOUND)));
                }

                if (!ModelState.IsValid)
                {
                    Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.notFound));
                    return(Json(MessageResult.GetMessage(MessageType.NOT_FOUND)));
                }

                //Get list all history by id account
                List <HistoryEntity> list = _historyRepository.getHistoryByAccount(accountId);

                List <HistoryResult> listResult = new List <HistoryResult>();

                foreach (var history in list)
                {
                    HistoryResult result = new HistoryResult();
                    ExamEntity    exam   = _examRepository.GetExamById(history.ExamId);
                    GroupEntity   group  = _groupRepository.GetGroupById(history.GroupId);
                    result.nameExam  = exam.Name;
                    result.nameGroup = group.Name;

                    listResult.Add(result);
                }

                return(Json(listResult));
            }
            catch (Exception ex)
            {
                Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(ex.Message));
                return(Json(MessageResult.ShowServerError(ex.Message)));
            }
        }
Exemple #16
0
        /// <summary>
        /// 通用单表列表翻页+where字符串拼接查询。(op后台使用,不适合高并发因为拼接sql没有参数化)
        /// </summary>
        /// <param name="pageCount">记录数</param>
        /// <param name="pageIndex">页号</param>
        /// <param name="pageSize">页码</param>
        /// <param name="where">查询条件</param>
        /// <param name="orderField">排序字段</param>
        /// <param name="isDesc">排序规则(true正序false倒序)</param>
        /// <returns></returns>
        public IList <ExamEntity> Search(out int pageCount, int pageIndex, int pageSize, string where, string orderField, bool isDesc)
        {
            IList <ExamEntity> list = new List <ExamEntity>();

            SqlParameter[] _param =
            {
                new SqlParameter("@pageIndex",    SqlDbType.Int),
                new SqlParameter("@pageSize",     SqlDbType.Int),
                new SqlParameter("@strWhere",     SqlDbType.VarChar),
                new SqlParameter("@fldName",      SqlDbType.VarChar),
                new SqlParameter("@OrderType",    SqlDbType.Bit),
                new SqlParameter("@tblName",      SqlDbType.VarChar),
                new SqlParameter("@strGetFields", SqlDbType.VarChar),
                new SqlParameter("@pageCount",    SqlDbType.Int)
            };
            _param[0].Value     = pageIndex;
            _param[1].Value     = pageSize;
            _param[2].Value     = where;
            _param[3].Value     = orderField;
            _param[4].Value     = isDesc;
            _param[5].Value     = "Exam";
            _param[6].Value     = "*";
            _param[7].Direction = ParameterDirection.Output;

            using (IDataReader dr = SqlHelper.ExecuteReader(SqlHelper.Connection, CommandType.StoredProcedure, "sp_OF_Page", _param))
            {
                while (dr.Read())
                {
                    ExamEntity info = Populate_ExamEntity_FromDr(dr);
                    list.Add(info);
                }

                if (!dr.IsClosed)
                {
                    dr.Close();
                }

                pageCount = Convert.ToInt32(_param[7].Value.ToString());
            }

            return(list);
        }
Exemple #17
0
        /// <summary>
        /// 得到  exam 数据实体
        /// </summary>
        /// <param name="row">row</param>
        /// <returns>exam 数据实体</returns>
        public ExamEntity Populate_ExamEntity_FromDr(DataRow row)
        {
            ExamEntity Obj = new ExamEntity();

            if (row != null)
            {
                Obj.Id         = ((row["Id"]) == DBNull.Value) ? 0 : (long)row["Id"];
                Obj.ExamTitle  = row["ExamTitle"].ToString();
                Obj.Type       = ((row["Type"]) == DBNull.Value) ? (short)0 : (short)row["Type"];
                Obj.SubType    = ((row["SubType"]) == DBNull.Value) ? (short)0 : (short)row["SubType"];
                Obj.CreateTime = ((row["CreateTime"]) == DBNull.Value) ? Convert.ToDateTime("1900-1-1") : Convert.ToDateTime(row["CreateTime"]);
                Obj.UpdateTime = ((row["UpdateTime"]) == DBNull.Value) ? Convert.ToDateTime("1900-1-1") : Convert.ToDateTime(row["UpdateTime"]);
                Obj.IsActive   = ((row["IsActive"]) == DBNull.Value) ? (short)0 : (short)row["IsActive"];
            }
            else
            {
                return(null);
            }
            return(Obj);
        }
Exemple #18
0
        /// <summary>
        /// 向数据表Exam更新一条记录。
        /// </summary>
        /// <param name="_ExamModel">_ExamModel</param>
        /// <returns>影响的行数</returns>
        public int Update(ExamEntity _ExamModel)
        {
            string sqlStr = "update Exam set [ExamTitle]=@ExamTitle,[Type]=@Type,[SubType]=@SubType,[CreateTime]=@CreateTime,[UpdateTime]=@UpdateTime,[IsActive]=@IsActive where Id=@Id";

            SqlParameter[] _param =
            {
                new SqlParameter("@Id",         SqlDbType.BigInt),
                new SqlParameter("@ExamTitle",  SqlDbType.VarChar),
                new SqlParameter("@Type",       SqlDbType.SmallInt),
                new SqlParameter("@SubType",    SqlDbType.SmallInt),
                new SqlParameter("@CreateTime", SqlDbType.DateTime),
                new SqlParameter("@UpdateTime", SqlDbType.DateTime),
                new SqlParameter("@IsActive",   SqlDbType.SmallInt)
            };
            _param[0].Value = _ExamModel.Id;
            _param[1].Value = _ExamModel.ExamTitle;
            _param[2].Value = _ExamModel.Type;
            _param[3].Value = _ExamModel.SubType;
            _param[4].Value = _ExamModel.CreateTime;
            _param[5].Value = _ExamModel.UpdateTime;
            _param[6].Value = _ExamModel.IsActive;
            return(SqlHelper.ExecuteNonQuery(SqlHelper.Connection, CommandType.Text, sqlStr, _param));
        }
Exemple #19
0
 public long Update(ExamEntity examEntity)
 {
     return(examdal.Update(examEntity));
 }
Exemple #20
0
        protected IActionResult QuestionGenericInternal(string provider, string examCode, string id)
        {
            ExamEntity examEntity = DataGenerator.AllExams
                                    .Where(e => e.Provider.Equals(provider, StringComparison.InvariantCultureIgnoreCase) &&
                                           e.Code.Equals(examCode, StringComparison.InvariantCultureIgnoreCase))

                                    .FirstOrDefault();

            ExamViewModel examViewModel = mapper.Map <ExamViewModel>(examEntity);

            string title = $"Exam {examViewModel.Code}: Question {id}";

            ViewData["title"] = title;

            ViewData["id"] = id;
            if (examViewModel.Code?.Equals("CRT-251", StringComparison.InvariantCultureIgnoreCase) == true)
            {
                ViewData["imageUrl"] = "images/salesforce/crt-251.png";
                ViewData["imageAlt"] = $"{examViewModel.Provider}, {examViewModel.Code}: {examViewModel.Name}";
            }
            else if (examViewModel.Code?.Equals("AZ-900", StringComparison.InvariantCultureIgnoreCase) == true)
            {
                ViewData["imageUrl"] = "images/az-900.png";
                ViewData["imageAlt"] = $"{examViewModel.Provider}, {examViewModel.Code}: {examViewModel.Name}";
            }
            else if (examViewModel.Code?.Equals("AZ-100", StringComparison.InvariantCultureIgnoreCase) == true)
            {
                ViewData["imageUrl"] = "images/az-100.png";
                ViewData["imageAlt"] = $"{examViewModel.Provider}, {examViewModel.Code}: {examViewModel.Name}";
            }

            string cd = Environment.CurrentDirectory;

            if (int.TryParse(id, out int intId))
            {
                ViewData["basePath"] = $"{examViewModel.Provider.ToLowerInvariant()}/{examViewModel.Code.ToLowerInvariant()}/question";
                ViewData["prev"]     = intId - 1;
                ViewData["next"]     = intId + 1;
                ViewData["current"]  = intId;
                ViewData["max"]      = examViewModel.Questions.Count;
            }

            if (intId > examViewModel.Questions.Count || intId == 0)
            {
                return(NotFound());
            }

            QuestionViewModel questionVM = examViewModel.Questions[intId - 1];

            ViewData["description"] = questionVM.Contents?.FirstOrDefault()?.Text;

            StringBuilder microdataJson = new StringBuilder();

            string dateCreated = "2020-03-27T15:01Z";

            ViewData["hasMicrodata"] = true;

            string author = HttpUtility.JavaScriptStringEncode("exam-answer.com");

            string upvoteCount         = HttpUtility.JavaScriptStringEncode("0");
            string canonicalUrl        = $"https://www.exam-answer.com/{examViewModel.Provider?.ToLowerInvariant()}/{examViewModel.Code?.ToLowerInvariant()}/question{id}";
            string canonicalUrlEncoded = HttpUtility.JavaScriptStringEncode(canonicalUrl);

            List <AnswerViewModel> acceptedAnswers = questionVM.Answers.Where(a => a.IsCorrect == true).ToList();

            List <AnswerViewModel> suggestedAnswers = questionVM.Answers.Where(a => a.IsCorrect != true).ToList();

            if (questionVM.QuestionType == QuestionType.DropDown)
            {
                acceptedAnswers  = new List <AnswerViewModel>();
                suggestedAnswers = new List <AnswerViewModel>();
                foreach (var ans in questionVM.Answers)
                {
                    var values           = ans.Text.Split(";", StringSplitOptions.RemoveEmptyEntries).ToList();
                    var titleOfDdlAnswer = values.FirstOrDefault();

                    values = values.Skip(1).ToList();

                    List <string> wrongAnswers   = values.Where(v => !v.Trim().EndsWith("*")).ToList().Select(s => s.Replace("*", string.Empty).Trim()).ToList();
                    List <string> correctAnswers = values.Where(v => v.Trim().EndsWith("*")).ToList().Select(s => s.Replace("*", string.Empty).Trim()).ToList();

                    acceptedAnswers.Add(new AnswerViewModel()
                    {
                        Text = $"{titleOfDdlAnswer}: {string.Join(", ", correctAnswers)}"
                    });
                    suggestedAnswers.Add(new AnswerViewModel()
                    {
                        Text = $"{titleOfDdlAnswer}: {string.Join(", ", wrongAnswers)}"
                    });
                }
            }

            StringBuilder sbAcceptedAnswer  = new StringBuilder();
            StringBuilder sbSuggestedAnswer = new StringBuilder();

            sbAcceptedAnswer.AppendLine("[");

            string allAnswers = string.Empty;

            foreach (AnswerViewModel aa in acceptedAnswers)
            {
                allAnswers += $"{aa.Text} ";
            }

            allAnswers = allAnswers.Trim();

            if (string.IsNullOrWhiteSpace(allAnswers))
            {
                allAnswers = questionVM.AcceptedAnswer;
            }

            if (allAnswers != null) // TO DO for DropDown
            {
                allAnswers = allAnswers.Replace("\\", "\\\\").Replace("\"", "\\\"");
            }
            else
            {
                allAnswers = string.Empty; // TO DO for DropDown
            }

            sbAcceptedAnswer.Append($@"{{
        ""@type"": ""Answer"",
        ""author"": ""{author}"",
        ""upvoteCount"": ""{upvoteCount}"",
        ""url"": ""{canonicalUrlEncoded}"",
        ""dateCreated"": ""{dateCreated}"",
        ""text"": ""{allAnswers}""
                }}");

            sbAcceptedAnswer.AppendLine("]");

            sbSuggestedAnswer.AppendLine("[");
            foreach (AnswerViewModel aa in suggestedAnswers)
            {
                string text = HttpUtility.JavaScriptStringEncode(aa.Text);

                sbSuggestedAnswer.Append($@"{{
        ""@type"": ""Answer"",
        ""author"": ""{author}"",
        ""upvoteCount"": ""{upvoteCount}"",
        ""url"": ""{canonicalUrlEncoded}"",
        ""dateCreated"": ""{dateCreated}"",
        ""text"": ""{text}""
                }}");
                if (suggestedAnswers.IndexOf(aa) != suggestedAnswers.Count - 1)
                {
                    sbSuggestedAnswer.Append(",");
                }
            }
            sbSuggestedAnswer.AppendLine("]");

            string acceptedAnswer  = sbAcceptedAnswer.ToString();
            string suggestedAnswer = sbSuggestedAnswer.ToString();

            StringBuilder sbQuestionText = new StringBuilder();

            foreach (ContentViewModel c in questionVM.Contents)
            {
                sbQuestionText.Append($"{c.Text} ");
            }
            string test         = HttpUtility.JavaScriptStringEncode("\"test\"");
            string questionText = HttpUtility.JavaScriptStringEncode(sbQuestionText.ToString());

            // https://developers.google.com/search/docs/data-types/faqpage
            microdataJson.Append(
                $@"
<script type=""application/ld+json"">
{{
  ""@context"": ""http://schema.org"",
  ""@type"": ""FAQPage"",
  ""mainEntity"": {{
  ""@type"": ""Question"",
  ""name"": ""{questionText}"",
  ""author"": ""{author}"",
  ""url"": ""{canonicalUrlEncoded}"",
  ""dateCreated"": ""{dateCreated}"",
  ""text"": ""{questionText}"",
  ""answerCount"": ""{questionVM.Answers.Count}"",
  ""acceptedAnswer"": {acceptedAnswer},
  ""suggestedAnswer"": {suggestedAnswer}
}}
}}
 </script>");

            string microdata = microdataJson.ToString();

            ViewData["microdata"] = microdata;

            if (intId <= examViewModel.Questions.Count)
            {
                QuestionViewModel theQuestion    = examViewModel.Questions[intId - 1];
                QuestionEntity    questionEntity = examEntity.Questions[intId - 1];

                theQuestion.PageBaseCanonicalUrl = pageBaseCanonicalUrl;
                theQuestion.PageMicrodata        = microdata;
                theQuestion.PageTitle            = title + " | Exam-Answer";

                // Page description should be max 160 chars.
                List <string> words = new List <string>();

                foreach (ContentEntity content in questionEntity.Contents)
                {
                    words.AddRange(content.Text.Split(" ", StringSplitOptions.RemoveEmptyEntries).ToList());
                }

                foreach (AnswerEntity answer in questionEntity.Answers)
                {
                    words.AddRange(answer.Text.Split(" ", StringSplitOptions.RemoveEmptyEntries).ToList());
                }

                StringBuilder pageDescription = new StringBuilder();

                foreach (string w in words)
                {
                    if (pageDescription.Length + w.Length >= 160)
                    {
                        break;
                    }
                    else
                    {
                        pageDescription.Append($"{w} ");
                    }
                }

                theQuestion.PageDescription  = pageDescription.ToString().Trim();
                theQuestion.PageCanonicalUrl = canonicalUrl;
                theQuestion.PageMicrodata    = microdata;
                ViewResult view = View("Question", theQuestion);

                return(view);
            }
            else
            {
                return(NotFound());
            }
        }
Exemple #21
0
        public GroupEntity GetGroupByExam(ExamEntity examEntity)
        {
            int groupId = examEntity.GroupId;

            return(GetGroupById(groupId));
        }
Exemple #22
0
        protected ExamViewModel GetExamViewModelFromHttpContext()
        {
            // HttpContext.Request.Path = /salesforce/salesforce-certified-field-service-lightning-consultant

            var parts    = HttpContext.Request.Path.ToString().Split('/', StringSplitOptions.RemoveEmptyEntries);
            var provider = parts[0];
            var code     = parts[1];

            ExamEntity examEntity = examAnswerContext.Exams
                                    .Where(e => e.Provider.Equals(provider, StringComparison.InvariantCultureIgnoreCase) &&
                                           e.Code.Equals(code, StringComparison.InvariantCultureIgnoreCase))

                                    .Include(e => e.Questions)
                                    .ThenInclude(q => q.Contents)

                                    .Include(e => e.Questions)
                                    .ThenInclude(q => q.Answers)

                                    .Include(e => e.Questions)
                                    .ThenInclude(q => q.Explanations)

                                    .Include(e => e.Questions)
                                    .ThenInclude(q => q.References)

                                    .AsNoTracking()

                                    .FirstOrDefault();

            ExamViewModel examViewModel = mapper.Map <ExamViewModel>(examEntity);

            examViewModel.PageBaseCanonicalUrl = pageBaseCanonicalUrl;

            examViewModel.PageCanonicalUrl = $"{pageBaseCanonicalUrl}/{provider}/{code}";

            examViewModel.PageMicrodata = $@"<script type=""application/ld+json"">
    {{
      ""@context"": ""http://schema.org"",
      ""@type"": ""Webpage"",
      ""url"": ""{examViewModel.PageCanonicalUrl}"",
      ""name"": ""{examViewModel.Title}"",
      ""headline"": ""{examViewModel.Title}"",
      ""description"": ""{examViewModel.Description}"",
      ""mainEntityOfPage"": {{
        ""@type"": ""WebPage"",
        ""@id"": ""{examViewModel.PageCanonicalUrl}""
      }},
      ""publisher"": {{
        ""@type"": ""Organization"",
        ""name"": ""{examViewModel.PageCanonicalUrl}"",
        ""logo"": {{
          ""url"": ""{examViewModel.PageCanonicalUrl}/android-chrome-512x512.png"",
          ""width"": 512,
          ""height"": 512,
          ""@type"": ""ImageObject""
        }}
      }},
      ""image"": {{
        ""@type"": ""ImageObject"",
        ""url"": ""{examViewModel.PageCanonicalUrl}/android-chrome-512x512.png"",
        ""width"": 512,
        ""height"": 512
      }}
    }}";

            return(examViewModel);
        }
        public static List <ExamEntity> Initialize(ExamAnswerContext context)
        {
            string allText = File.ReadAllText("Exams\\Salesforce-Certified-Field-Service-Lightning-Consultant.txt");

            var quesions = allText.Split("###", StringSplitOptions.RemoveEmptyEntries).ToList();

            List <QuestionEntity> qeList = new List <QuestionEntity>();

            foreach (string question in quesions)
            {
                string[] questionsGroups = question.Split($"---", StringSplitOptions.RemoveEmptyEntries);

                List <string> questionContent = questionsGroups[0].Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).ToList();
                List <string> questionAnswers = questionsGroups[1].Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).ToList();
                //var questionExplanations = questionsGroups[2].Split(Environment.NewLine);
                //var questionReferences = questionsGroups[3].Split(Environment.NewLine);
                QuestionEntity qe = new QuestionEntity();
                qe.Order = quesions.IndexOf(question);
                if (questionContent.FirstOrDefault()?.Equals("C") == true)
                {
                    qe.QuestionType = QuestionType.CheckBox;
                    questionContent = questionContent.Skip(1).ToList();
                }

                foreach (string content in questionContent)
                {
                    ContentEntity contentEntity = new ContentEntity()
                    {
                        Text  = content,
                        Order = questionContent.IndexOf(content),
                    };
                    qe.Contents.Add(contentEntity);
                }

                foreach (string answer in questionAnswers)
                {
                    AnswerEntity answerEntity = new AnswerEntity()
                    {
                        Text  = answer,
                        Order = questionAnswers.IndexOf(answer),
                    };
                    if (answer.EndsWith("*"))
                    {
                        answerEntity.IsCorrect = true;
                        answerEntity.Text      = answer.TrimEnd('*').Trim();
                    }
                    qe.Answers.Add(answerEntity);
                }

                qeList.Add(qe);
            }

            List <ExamEntity> result = new List <ExamEntity>();

            ExamEntity adm201 = new ExamEntity()
            {
                Provider        = "Salesforce",
                ExamProviderUrl = "https://www.exam-answer.com/salesforce",
                ExamUrl         = "https://www.exam-answer.com/salesforce/adm-201",
                Code            = "ADM-201",
                Name            = "Administration Essentials for New Admins",
                PageTitle       = "Exam ADM-201: Administration Essentials for New Admins",
                PageDescription = "Prepare for Exam ADM-201: Administration Essentials for New Admins. Free demo questions with answers and explanations.",
                Questions       = GetQuestions("Exams\\adm-201.txt"),
                Order           = 3,
            };

            context?.Exams?.Add(adm201);
            result.Add(adm201);

            ExamEntity scfslc = new ExamEntity()
            {
                Provider        = "Salesforce",
                ExamProviderUrl = "https://www.exam-answer.com/salesforce",
                ExamUrl         = "https://www.exam-answer.com/salesforce/salesforce-certified-field-service-lightning-consultant",
                Code            = "Salesforce-Certified-Field-Service-Lightning-Consultant",
                Name            = "Salesforce Certified Field Service Lightning Consultant",
                PageTitle       = "Salesforce Certified Field Service Lightning Consultant",
                PageDescription = "Prepare for Salesforce Certified Field Service Lightning Consultant. Free demo questions with answers and explanations.",
                Questions       = qeList,
                Order           = 2,
            };

            context?.Exams?.Add(scfslc);
            result.Add(scfslc);

            ExamEntity crt251 = new ExamEntity()
            {
                Provider        = "Salesforce",
                Code            = "CRT-251",
                ExamProviderUrl = "https://www.exam-answer.com/salesforce",
                ExamUrl         = "https://www.exam-answer.com/salesforce/crt-251",
                Name            = "Sales Cloud Consultant",
                PageTitle       = "Exam CRT-251: Sales Cloud Consultant",
                PageDescription = "Prepare for Exam CRT-251: Sales Cloud Consultant. Free demo questions with answers and explanations.",
                Questions       = new List <QuestionEntity>(),
                Order           = 1,
            };

            crt251.Questions.Add(Q1.Instance);
            crt251.Questions.Add(Q2.Instance);
            crt251.Questions.Add(Q3.Instance);
            crt251.Questions.Add(Q4.Instance);
            crt251.Questions.Add(Q5.Instance);
            crt251.Questions.Add(Q6.Instance);
            crt251.Questions.Add(Q7.Instance);
            crt251.Questions.Add(Q8.Instance);
            crt251.Questions.Add(Q9.Instance);
            crt251.Questions.Add(Q10.Instance);
            crt251.Questions.Add(Q11.Instance);
            crt251.Questions.Add(Q12.Instance);
            crt251.Questions.Add(Q13.Instance);
            crt251.Questions.Add(Q14.Instance);
            crt251.Questions.Add(Q15.Instance);
            crt251.Questions.Add(Q16.Instance);
            crt251.Questions.Add(Q17.Instance);
            crt251.Questions.Add(Q18.Instance);
            crt251.Questions.Add(Q19.Instance);
            crt251.Questions.Add(Q20.Instance);
            crt251.Questions.Add(Q21.Instance);
            crt251.Questions.Add(Q22.Instance);
            crt251.Questions.Add(Q23.Instance);
            crt251.Questions.Add(Q24.Instance);
            crt251.Questions.Add(Q25.Instance);
            crt251.Questions.Add(Q26.Instance);
            crt251.Questions.Add(Q27.Instance);
            crt251.Questions.Add(Q28.Instance);
            crt251.Questions.Add(Q29.Instance);
            crt251.Questions.Add(Q30.Instance);
            crt251.Questions.Add(Q31.Instance);
            crt251.Questions.Add(Q32.Instance);
            crt251.Questions.Add(Q33.Instance);
            crt251.Questions.Add(Q34.Instance);
            crt251.Questions.Add(Q35.Instance);
            crt251.Questions.Add(Q36.Instance);
            crt251.Questions.Add(Q37.Instance);
            crt251.Questions.Add(Q38.Instance);
            crt251.Questions.Add(Q39.Instance);
            crt251.Questions.Add(Q40.Instance);
            crt251.Questions.Add(Q41.Instance);
            crt251.Questions.Add(Q42.Instance);
            crt251.Questions.Add(Q43.Instance);
            crt251.Questions.Add(Q44.Instance);
            crt251.Questions.Add(Q45.Instance);
            crt251.Questions.Add(Q46.Instance);
            crt251.Questions.Add(Q47.Instance);
            crt251.Questions.Add(Q48.Instance);
            crt251.Questions.Add(Q49.Instance);
            crt251.Questions.Add(Q50.Instance);
            crt251.Questions.Add(Q51.Instance);
            crt251.Questions.Add(Q52.Instance);
            crt251.Questions.Add(Q53.Instance);
            crt251.Questions.Add(Q54.Instance);
            crt251.Questions.Add(Q55.Instance);
            crt251.Questions.Add(Q56.Instance);
            crt251.Questions.Add(Q57.Instance);
            crt251.Questions.Add(Q58.Instance);
            crt251.Questions.Add(Q59.Instance);
            crt251.Questions.Add(Q60.Instance);
            crt251.Questions.Add(Q61.Instance);
            crt251.Questions.Add(Q62.Instance);
            crt251.Questions.Add(Q63.Instance);
            crt251.Questions.Add(Q64.Instance);
            crt251.Questions.Add(Q65.Instance);
            crt251.Questions.Add(Q66.Instance);
            crt251.Questions.Add(Q67.Instance);
            crt251.Questions.Add(Q68.Instance);
            crt251.Questions.Add(Q69.Instance);
            crt251.Questions.Add(Q70.Instance);
            crt251.Questions.Add(Q71.Instance);
            crt251.Questions.Add(Q72.Instance);
            crt251.Questions.Add(Q73.Instance);
            crt251.Questions.Add(Q74.Instance);
            crt251.Questions.Add(Q75.Instance);
            crt251.Questions.Add(Q76.Instance);
            crt251.Questions.Add(Q77.Instance);
            crt251.Questions.Add(Q78.Instance);
            crt251.Questions.Add(Q79.Instance);
            crt251.Questions.Add(Q80.Instance);
            crt251.Questions.Add(Q81.Instance);
            crt251.Questions.Add(Q82.Instance);
            crt251.Questions.Add(Q83.Instance);
            crt251.Questions.Add(Q84.Instance);
            crt251.Questions.Add(Q85.Instance);
            crt251.Questions.Add(Q86.Instance);
            crt251.Questions.Add(Q87.Instance);
            crt251.Questions.Add(Q88.Instance);
            crt251.Questions.Add(Q89.Instance);
            crt251.Questions.Add(Q90.Instance);
            crt251.Questions.Add(Q91.Instance);
            crt251.Questions.Add(Q92.Instance);
            crt251.Questions.Add(Q93.Instance);
            crt251.Questions.Add(Q94.Instance);
            crt251.Questions.Add(Q95.Instance);
            crt251.Questions.Add(Q96.Instance);
            crt251.Questions.Add(Q97.Instance);
            crt251.Questions.Add(Q98.Instance);
            crt251.Questions.Add(Q99.Instance);
            crt251.Questions.Add(Q100.Instance);

            crt251.ShowUdemy        = false;
            crt251.UdemyLinkUrl     = "https://www.udemy.com/salesforce-crt-251-sales-cloud-consultant-exam-questions/?couponCode=50_OFF";
            crt251.UdemyLinkMessage = "Salesforce CRT-251: Sales Cloud Consultant - 50% OFF";
            crt251.UdemyMessage     =
                "If you like what you see, please support the future development of our web site by buying this practice test at Udemy." +
                " Click this link for a 50% discount. The price is ONLY 9.99!";

            context?.Exams?.Add(crt251);

            result.Add(crt251);

            ExamEntity saa_c01 = new ExamEntity()
            {
                Provider        = "Amazon",
                Code            = "SAA-C01",
                Name            = "AWS Certified Solutions Architect - Associate",
                ExamProviderUrl = "https://www.exam-answer.com/amazon",
                ExamUrl         = "https://www.exam-answer.com/amazon/saa-c01",
                PageTitle       = "Exam SAA-C01: AWS Certified Solutions Architect – Associate",
                PageDescription = "Prepare for Exam SAA-C01: AWS Certified Solutions Architect – Associate. Free demo questions with answers and explanations.",
                Questions       = GetQuestions("Exams\\SAA-C01.txt"),
                Order           = 1,
            };

            context?.Exams?.Add(saa_c01);
            result.Add(saa_c01);

            ExamEntity saa_c02 = new ExamEntity()
            {
                Provider        = "Amazon",
                Code            = "SAA-C02",
                Name            = "AWS Certified Solutions Architect - Associate",
                ExamProviderUrl = "https://www.exam-answer.com/amazon",
                ExamUrl         = "https://www.exam-answer.com/amazon/saa-c02",
                PageTitle       = "Exam SAA-C02: AWS Certified Solutions Architect – Associate",
                PageDescription = "Prepare for Exam SAA-C02: AWS Certified Solutions Architect – Associate. Free demo questions with answers and explanations.",
                Questions       = GetQuestions("Exams\\SAA-C02.txt"),
                Order           = 2,
            };

            context?.Exams?.Add(saa_c02);
            result.Add(saa_c02);

            ExamEntity slf_c01 = new ExamEntity()
            {
                Provider        = "Amazon",
                Code            = "CLF-C01",
                Name            = "AWS Certified Cloud Practitioner",
                ExamProviderUrl = "https://www.exam-answer.com/amazon",
                ExamUrl         = "https://www.exam-answer.com/amazon/clf-c01",
                PageTitle       = "Exam CLF-C01: AWS Certified Cloud Practitioner",
                PageDescription = "Prepare for Exam CLF-C01: AWS Certified Cloud Practitioner. Free demo questions with answers and explanations.",
                Questions       = GetQuestions("Exams\\CLF-C01.txt"),
                Order           = 3,
            };

            context?.Exams?.Add(slf_c01);
            result.Add(slf_c01);


            ExamEntity az300 = new ExamEntity()
            {
                Provider        = "Microsoft",
                Code            = "AZ-300",
                Name            = "Microsoft Azure Architect Technologies",
                ExamProviderUrl = "https://www.exam-answer.com/microsoft",
                ExamUrl         = "https://www.exam-answer.com/microsoft/az-300",
                PageTitle       = "Exam AZ-300: Microsoft Azure Architect Technologies",
                PageDescription = "Prepare for Exam AZ-300: Microsoft Azure Architect Technologies. Free demo questions with answers and explanations.",
                Questions       = GetQuestions("Exams\\az-300.txt"),
                Order           = 2,
            };

            context?.Exams?.Add(az300);
            result.Add(az300);

            ExamEntity az400 = new ExamEntity()
            {
                Provider        = "Microsoft",
                Code            = "AZ-400",
                ExamProviderUrl = "https://www.exam-answer.com/microsoft",
                ExamUrl         = "https://www.exam-answer.com/microsoft/az-400",
                Name            = "Designing and Implementing Microsoft DevOps Solutions",
                PageTitle       = "Exam AZ-400: Designing and Implementing Microsoft DevOps Solutions",
                PageDescription = "Prepare for Exam AZ-400: Designing and Implementing Microsoft DevOps Solutions. Free demo questions with answers and explanations.",
                Questions       = GetQuestions("Exams\\az-400.txt"),
                Order           = 4,
            };

            context?.Exams?.Add(az400);
            result.Add(az400);

            ExamEntity az100 = new ExamEntity()
            {
                Provider        = "Microsoft",
                Code            = "AZ-100",
                ExamProviderUrl = "https://www.exam-answer.com/microsoft",
                ExamUrl         = "https://www.exam-answer.com/microsoft/az-100",
                Name            = "Microsoft Azure Infrastructure and Deployment",
                PageTitle       = "Exam AZ-100: Microsoft Azure Infrastructure and Deployment",
                PageDescription = "Prepare for Exam AZ-100: Microsoft Azure Infrastructure and Deployment. Free demo questions with answers and explanations.",
                Questions       = GetQuestions("Exams\\az-100.txt"),
                Order           = 1,
            };

            context?.Exams?.Add(az100);
            result.Add(az100);

            ExamEntity az301 = new ExamEntity()
            {
                Provider        = "Microsoft",
                Code            = "AZ-301",
                ExamProviderUrl = "https://www.exam-answer.com/microsoft",
                ExamUrl         = "https://www.exam-answer.com/microsoft/az-301",
                Name            = "Microsoft Azure Architect Design",
                PageTitle       = "Exam AZ-301: Microsoft Azure Architect Design",
                PageDescription = "Prepare for Exam AZ-301: Microsoft Azure Architect Design. Free demo questions with answers and explanations.",
                Questions       = GetQuestions("Exams\\az-301.txt"),
                Order           = 3,
            };

            context?.Exams?.Add(az301);
            result.Add(az301);

            ExamEntity az900 = new ExamEntity()
            {
                Provider        = "Microsoft",
                Code            = "AZ-900",
                ExamProviderUrl = "https://www.exam-answer.com/microsoft",
                ExamUrl         = "https://www.exam-answer.com/microsoft/az-900",
                Name            = "Microsoft Azure Fundamentals",
                PageTitle       = "Exam AZ-900: Microsoft Azure Fundamentals",
                PageDescription = "Prepare for Exam AZ-900: Microsoft Azure Fundamentals. Free demo questions with answers and explanations.",
                Questions       = new List <QuestionEntity>(),
                Order           = 5,
            };


            az900.ShowUdemy        = false;
            az900.UdemyLinkUrl     = "https://www.udemy.com/course/exam-az-900-microsoft-azure-fundamentals-exam-questions/?couponCode=50_OFF";
            az900.UdemyLinkMessage = "Exam AZ-900: Microsoft Azure Fundamentals, Exam Question - 50 % OFF";
            az900.UdemyMessage     =
                "If you like what you see, please support the future development of our web site by buying this practice test at Udemy." +
                " Click this link for a 50% discount. The price is ONLY 12.99!";

            List <FieldInfo> az900Fields = typeof(Az900).GetFields(BindingFlags.Static |
                                                                   BindingFlags.Public |
                                                                   BindingFlags.NonPublic).ToList();

            az900Fields = az900Fields.OrderBy(a =>
            {
                int order = int.Parse(a.Name.Replace("Q", string.Empty).Replace("Instance", string.Empty));
                return(order);
            }).ToList();

            foreach (FieldInfo f in az900Fields)
            {
                QuestionEntity qe = f.GetValue(null) as QuestionEntity;
                az900.Questions.Add(qe);
            }

            az900.Questions.AddRange(GetQuestions("Exams\\az-900.txt", az900.Questions.Count));

            context?.Exams?.Add(az900);
            result.Add(az900);

            context?.SaveChanges();

            AllExams = result;
            return(result);
        }
Exemple #24
0
        public JsonResult CreateAnswerUser([FromBody] AnswerUserModel answerUserModel)
        {
            string functionName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            try
            {
                //Check value enter from the form
                if (answerUserModel == null)
                {
                    Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.notInformationQuestion));
                    return(Json(MessageResult.GetMessage(MessageType.NOT_INFORMATION_QUESTION)));
                }

                if (!_accountRepository.AccountExists(answerUserModel.accountId))
                {
                    Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.accountNotFound));
                    return(Json(MessageResult.GetMessage(MessageType.ACCOUNT_NOT_FOUND)));
                }

                if (!_examRepository.ExamExist(answerUserModel.examId))
                {
                    Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.examNotFound));
                    return(Json(MessageResult.GetMessage(MessageType.EXAM_NOT_FOUND)));
                }

                if (!ModelState.IsValid)
                {
                    Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.notFound));
                    return(Json(MessageResult.GetMessage(MessageType.NOT_FOUND)));
                }
                //get list answer user from form
                List <AnswerUserDto> answersFromForm = answerUserModel.listAnswerUser;
                //get all list question from the examId
                List <ExamQuestionEntity> examQuestionEntity = _examQuestionRepository.getListQuestions(answerUserModel.examId);
                //get all answer user of this account
                List <AnswerUserEntity> answerUsersFromDB = _answerUserRepository.GetAnswerUserEntities(answerUserModel.accountId);

                //if this account haven't ever do the exam. newAccountAnswer will store it
                List <AnswerUserDto> newAccountAnswer = new List <AnswerUserDto>();
                //list answer of this account from DB
                List <AnswerUserDto> oldAccountUser = new List <AnswerUserDto>();


                // divide between old and new answer
                foreach (var answer in answersFromForm)
                {
                    foreach (var item in answerUsersFromDB)
                    {
                        if (answer.questionId == item.QuestionId)
                        {
                            oldAccountUser.Add(answer);
                        }
                    }
                }
                newAccountAnswer = answersFromForm;

                if (oldAccountUser.Count() > 0)
                {
                    // remove old answer
                    for (int i = 0; i < answersFromForm.Count; i++)
                    {
                        foreach (var item in oldAccountUser)
                        {
                            if (item == answersFromForm[i])
                            {
                                answersFromForm.Remove(answersFromForm[i]);
                            }
                        }
                    }

                    foreach (var examQuestion in examQuestionEntity)
                    {
                        foreach (var answer in newAccountAnswer)
                        {
                            if (examQuestion.QuestionId == answer.questionId)
                            {
                                //Map data enter from the form to question entity
                                var answerUser = Mapper.Map <PPT.Database.Entities.AnswerUserEntity>(answer);
                                answerUser.AccountId = answerUserModel.accountId;
                                //This is query insert question
                                _answerUserRepository.CreateAnswerUser(answerUser);
                            }
                        }
                    }

                    foreach (var answer in oldAccountUser)
                    {
                        foreach (var answerU in answerUsersFromDB)
                        {
                            if (answerU.QuestionId == answer.questionId)
                            {
                                answerU.AnswerKey = answer.answerKey;
                            }
                        }
                    }
                }
                //this function shows that user haven't ever done this exam. This is the first time they do it.

                else
                {
                    //1 -> 14
                    foreach (var examQuestion in examQuestionEntity)
                    {
                        //1 -> 2
                        foreach (var answer in newAccountAnswer)
                        {
                            if (examQuestion.QuestionId == answer.questionId)
                            {
                                //Map data enter from the form to question entity
                                var answerUser = Mapper.Map <PPT.Database.Entities.AnswerUserEntity>(answer);
                                answerUser.AccountId = answerUserModel.accountId;
                                //This is query insert question
                                _answerUserRepository.CreateAnswerUser(answerUser);
                                AccountExamEntity accountExamEntity = _accountExamRepository.GetByAccountIdAndExamId(answerUser.AccountId, examQuestion.ExamId);

                                accountExamEntity.IsStatus = "Continue Do Exam";
                                _accountExamRepository.Save();
                            }
                        }
                    }
                }
                AccountExamEntity finishExam = _accountExamRepository.GetByAccountIdAndExamId(answerUserModel.accountId, answerUserModel.examId);
                if (answerUserModel.status != null)
                {
                    finishExam.IsStatus = "Finish";
                    _accountExamRepository.Save();
                }

                //get account by Id
                AccountEntity account = _accountRepository.GetAccountById(answerUserModel.accountId);
                //get exam by Id
                ExamEntity exam    = _examRepository.GetExamById(answerUserModel.examId);
                int        groupId = exam.GroupId;
                //get group by Id
                GroupEntity group = _groupRepository.GetGroupById(groupId);

                if (_historyRepository.CheckAccount(account.AccountId, exam.ExamId))
                {
                    HistoryEntity history = new HistoryEntity();
                    history.AccountId = account.AccountId;
                    history.ExamId    = exam.ExamId;
                    history.Group     = group;
                    _historyRepository.CreateHistory(history);
                    _historyRepository.Save();
                }

                if (!_answerUserRepository.Save())
                {
                    Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.badRequest));
                    return(Json(MessageResult.GetMessage(MessageType.BAD_REQUEST)));
                }

                Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(Constants.createdAnswerUser));
                return(Json(MessageResult.GetMessage(MessageType.CREATED_ANSWER_USER)));
            }
            catch (Exception ex)
            {
                Log4Net.log.Error(className + "." + functionName + " - " + Log4Net.AddErrorLog(ex.Message));
                return(Json(MessageResult.ShowServerError(ex.Message)));
            }
        }
Exemple #25
0
 public long Insert(ExamEntity examEntity)
 {
     return(examdal.Insert(examEntity));
 }
Exemple #26
0
 public void CreateExam(ExamEntity examEntity)
 {
     _context.Exams.Add(examEntity);
 }
Exemple #27
0
 public void DeleteExam(ExamEntity exam)
 {
     _context.Exams.Remove(exam);
 }
Exemple #28
0
        public void CreateExportForUdemyTest()
        {
            List <ExamEntity> exams = DataGenerator.Initialize(null);

            ExamEntity theExamToExportToUdemy = exams.FirstOrDefault(f => f.Code == "AZ-900");

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("Question,Question Type (multiple-choice or multi-select),Answer Option 1,Answer Option 2,Answer Option 3,Answer Option 4,Answer Option 5,Answer Option 6,Correct Response,Explanation,Knowledge Area");

            List <QuestionEntity> theQuestions = theExamToExportToUdemy.Questions.Skip(50).Take(50).ToList();

            foreach (QuestionEntity question in theQuestions)
            {
                if (!question.Answers.Any(a => a.IsCorrect == true))
                {
                    continue;
                }

                sb.Append(question.ContentTextUdemy.Replace("\"", "\"\"").Replace(",", ""));
                sb.Append(",");

                if (question.QuestionType == QuestionType.RadioButon)
                {
                    sb.Append("multiple-choice");
                    sb.Append(",");
                }
                else if (question.QuestionType == QuestionType.CheckBox)
                {
                    sb.Append("multi-select");
                    sb.Append(",");
                }

                for (int i = 0; i < 6; i++)
                {
                    if (i < question.Answers?.Count)
                    {
                        AnswerEntity answer = question.Answers[i];
                        sb.Append(answer.Text.Replace("\"", "\"\"").Replace(",", ""));
                        sb.Append(",");
                    }
                    else
                    {
                        //sb.Append(string.Empty);
                        sb.Append(",");
                    }
                }
                if (question.QuestionType == QuestionType.CheckBox)
                {
                    sb.Append("\"");
                }
                for (int i = 0; i < 6; i++)
                {
                    if (i < question.Answers?.Count)
                    {
                        AnswerEntity answer = question.Answers[i];

                        if (answer.IsCorrect == true)
                        {
                            int indexToInsert = question.Answers.IndexOf(answer) + 1;
                            sb.Append(indexToInsert);
                            if (question.QuestionType == QuestionType.CheckBox)
                            {
                                sb.Append(",");
                            }
                        }
                    }
                }

                sb = new StringBuilder(sb.ToString().Trim(','));

                if (question.QuestionType == QuestionType.CheckBox)
                {
                    sb.Append("\"");
                }
                sb.Append(",");
                if (!string.IsNullOrEmpty(question.ExplanationText))
                {
                    sb.Append(question.ExplanationTextUdemy.Replace(",", ""));
                    sb.Append("References: ");
                    sb.Append(question.ReferenceTextUdemy.Replace(",", ""));
                }

                sb.Append(",");

                string knowledgeArea = question.Section.Replace(",", "");

                sb.Append(knowledgeArea);

                sb.Append(Environment.NewLine);
            }

            string result = sb.ToString();

            File.WriteAllText($"BulkImportUdemy{theExamToExportToUdemy.Code}.csv", result);
        }