Inheritance: MonoBehaviour
Exemple #1
0
        public static bool addQA(QuestionAnswer questionAnswer, string connString)
        {
            #region code
            bool rs = false;
            using (SqlConnection conn = new SqlConnection(connString))
            {
                try
                {
                    conn.Open();
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "sony_sp_add_faq";
                        cmd.Parameters.AddWithValue("@question", questionAnswer.Question);
                        cmd.Parameters.AddWithValue("@answer", questionAnswer.Answer);
                        SqlParameter returnVal = new SqlParameter("@returnVal", SqlDbType.Int);
                        returnVal.Direction = ParameterDirection.Output;
                        cmd.Parameters.Add(returnVal);

                        cmd.ExecuteNonQuery();
                        rs = ((int)cmd.Parameters["@returnVal"].Value != 0);
                    }
                }
                catch (Exception ex)
                {
                    WriteLog("", "Add Faq Error: " + ex.Message, connString);
                    return false;
                }
            }
            return rs;
            #endregion
        }
Exemple #2
0
        public static QuestionAnswer getById(int id, string connString)
        {
            #region code
            QuestionAnswer qa = new QuestionAnswer();
            using (SqlConnection conn = new SqlConnection(connString))
            {
                try
                {
                    conn.Open();
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "sony_sp_get_faq_by_id";
                        cmd.Parameters.AddWithValue("@id", id);

                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                qa.Id = (int)reader["id"];
                                qa.Question = reader["question"].ToString();
                                qa.Answer = reader["answer"].ToString();
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    WriteLog("", "Get QuestionAnswer Error: " + ex.Message, connString);
                    return new QuestionAnswer();
                }
            }
            return qa;
            #endregion
        }
 public void AddAnswer(string text, string value, bool preventDuplicates)
 {
     text = text.Trim();
     value = value.Trim();
     int valueInt;
     if(int.TryParse(value, out valueInt)){
         if(valueInt > 9999) value = valueInt.ToString("N");
     }
     if(text.Length <= 0 || value.Length <= 0) return;
     if(preventDuplicates && m_answers.Exists((_answer) => _answer.m_text.Equals(text))) return;
     QuestionAnswer answer = new QuestionAnswer();
     answer.m_text = text;
     answer.m_value = value;
     m_answers.Add(answer);
 }
Exemple #4
0
 private List<QuestionAnswer> buildQuestionAnswersList(XmlDocument x)
 {
     XmlNodeList qNodes = x.SelectNodes("/response/answer");
     if (qNodes.Count > 0)
     {
         List<QuestionAnswer> qList = new List<QuestionAnswer>();
         foreach (XmlNode qNode in qNodes)
         {
             QuestionAnswer answer = new QuestionAnswer();
             XmlUtils.UseNode(qNode);
             answer.Id = XmlUtils.Int("aid");
             answer.QuestionId = XmlUtils.Int("qid");
             answer.UserId = XmlUtils.Int("uid");
             answer.Text = XmlUtils.String("text");
             answer.Number = XmlUtils.Int("num");
             answer.Date = XmlUtils.String("date");
             answer.UserName = XmlUtils.String("name");
             answer.UserPhoto = XmlUtils.String("photo");
             answer.IsUserOnline = XmlUtils.Bool("online");
             qList.Add(answer);
         }
         return qList;
     }
     return null;
 }
Exemple #5
0
 public void RemoveQuestionAnswer(QuestionAnswer questionAnswer)
 {
     _commandDispatcher.Dispatch(new RemoveAnswerCommand {
         QuestionAnswerId = questionAnswer.QuestionAnswerId
     });
 }
Exemple #6
0
    void Start()
    {
        GlobalFunctions.isLoading = false;
        if (qa != null)
        {
            if (qa.GetBank().Count == 0)
            {
                qa.Load();
                qa = qa.GetBank()[level - 1];
            }
        }
        isFinished   = false;
        showQuestion = false;
        input        = "";
        isNotRandom  = true;
        gameTime     = 0;

        if (canvas.activeInHierarchy)
        {
            canvas.SetActive(!canvas.activeInHierarchy);                                                //set the menu canvas to inactive
        }
        isNotRandom = true;                                                                             // Reset the puzzle random state to not random yet.
        GameObject Puzzle = GameObject.Find("Puzzle");                                                  //Find the Puzzle Game object

        PuzzlePieces = Puzzle.GetComponentsInChildren <Transform>();                                    //Transforms property of each puzzle pieces
        int ctr = 0;                                                                                    //A counter

        Texture2D[] images = Resources.LoadAll <Texture2D>("UI/Images/Hard/Level/" + level.ToString()); //Load all images based on level
        images.OrderBy(x => x.name);
        Transform[] PuzzlePiecesHelp = PuzzleHelp.GetComponentsInChildren <Transform>();
        foreach (Transform go in PuzzlePiecesHelp)
        {
            if (go.name != "PuzzleHelp")
            {
                if (ctr <= images.Length - 2)
                {
                    go.GetComponentInChildren <Renderer>().material.mainTexture = images[ctr];
                }
                else
                {
                }
                ctr++;
            }
        }

        ctr = 0;

        foreach (Transform go in PuzzlePieces)
        {
            if (go.name != "Puzzle")
            {
                go.gameObject.AddComponent <PuzzlePieceScript>();
                go.gameObject.GetComponent <PuzzlePieceScript>().isDoneRandomizing = false;
                if (ctr <= images.Length - 2)
                {
                    go.GetComponentInChildren <Renderer>().material.mainTexture = images[ctr];
                }
                else
                {
                    go.gameObject.GetComponent <PuzzlePieceScript>().isNullPiece = true;
                    nullPiece = go.gameObject;
                }
                ctr++;
            }
        }
    }
Exemple #7
0
        /// <summary>
        /// Construct a response containing the applicable requirement questions with their answers.
        /// </summary>
        /// <param name="requirements"></param>
        /// <param name="answers"></param>
        /// <returns></returns>
        private QuestionResponse BuildResponse(List <RequirementPlus> requirements,
                                               List <FullAnswer> answers, List <DomainAssessmentFactor> domains)
        {
            List <QuestionGroup> groupList = new List <QuestionGroup>();
            QuestionGroup        g         = new QuestionGroup();
            QuestionSubCategory  sg        = new QuestionSubCategory();
            QuestionAnswer       qa        = new QuestionAnswer();

            string currentGroupHeading       = string.Empty;
            string currentSubcategoryHeading = string.Empty;

            try
            {
                foreach (var dbRPlus in requirements)
                {
                    var dbR = dbRPlus.Requirement;

                    // Make sure there are no leading or trailing spaces - it will affect the tree structure that is built
                    dbR.Standard_Category     = dbR.Standard_Category == null?null: dbR.Standard_Category.Trim();
                    dbR.Standard_Sub_Category = dbR.Standard_Sub_Category == null?null: dbR.Standard_Sub_Category.Trim();

                    // If the Standard_Sub_Category is null (like CSC_V6), default it to the Standard_Category
                    if (dbR.Standard_Sub_Category == null)
                    {
                        dbR.Standard_Sub_Category = dbR.Standard_Category;
                    }


                    if (dbR.Standard_Category != currentGroupHeading)
                    {
                        g = new QuestionGroup()
                        {
                            GroupHeadingId    = dbR.Question_Group_Heading_Id,
                            GroupHeadingText  = dbR.Standard_Category,
                            StandardShortName = dbRPlus.SetShortName,
                        };

                        if (domains.Any(x => x.AssessmentFactorName == g.GroupHeadingText))
                        {
                            g.DomainName = domains.FirstOrDefault(x => x.AssessmentFactorName == g.GroupHeadingText)
                                           .DomainName;
                        }

                        groupList.Add(g);

                        currentGroupHeading = g.GroupHeadingText;
                    }

                    // new subcategory
                    if (dbR.Standard_Sub_Category != currentSubcategoryHeading)
                    {
                        sg = new QuestionSubCategory()
                        {
                            SubCategoryId          = 0,
                            SubCategoryHeadingText = dbR.Standard_Sub_Category,
                            GroupHeadingId         = g.GroupHeadingId
                        };

                        g.SubCategories.Add(sg);

                        currentSubcategoryHeading = dbR.Standard_Sub_Category;
                    }



                    FullAnswer answer = answers.Where(x => x.a.Question_Or_Requirement_Id == dbR.Requirement_Id).FirstOrDefault();

                    qa = new QuestionAnswer()
                    {
                        DisplayNumber  = dbR.Requirement_Title,
                        QuestionId     = dbR.Requirement_Id,
                        QuestionText   = dbR.Requirement_Text.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>"),
                        Answer         = answer?.a.Answer_Text,
                        AltAnswerText  = answer?.a.Alternate_Justification,
                        Comment        = answer?.a.Comment,
                        Feedback       = answer?.a.Feedback,
                        MarkForReview  = answer?.a.Mark_For_Review ?? false,
                        Reviewed       = answer?.a.Reviewed ?? false,
                        MaturityLevel  = ReqMaturityLevel(dbR.Requirement_Id),
                        SetName        = dbRPlus.SetName,
                        Is_Component   = answer?.a.Is_Component ?? false,
                        Is_Requirement = answer?.a.Is_Requirement ?? false
                    };
                    if (answer != null)
                    {
                        TinyMapper.Map <VIEW_QUESTIONS_STATUS, QuestionAnswer>(answer.b, qa);
                    }

                    qa.ParmSubs = GetTokensForRequirement(qa.QuestionId, (answer != null) ? answer.a.Answer_Id : 0);

                    sg.Questions.Add(qa);
                }

                QuestionResponse resp = new QuestionResponse
                {
                    QuestionGroups  = groupList,
                    ApplicationMode = this.applicationMode
                };

                resp.QuestionCount    = new QuestionsManager(this._assessmentId).NumberOfQuestions();
                resp.RequirementCount = this.NumberOfRequirements();

                // Get the overall risk level
                var acetDash = new ACETDashboardManager().LoadDashboard(this._assessmentId);
                resp.OverallIRP = acetDash.SumRiskLevel;
                if (acetDash.Override > 0)
                {
                    resp.OverallIRP = acetDash.Override;
                }

                BuildComponentsResponse(resp);
                return(resp);
            }catch (Exception e)
            {
                throw e;
            }
        }
 public QuizRound(QuestionAnswer incoming)
 {
     question = incoming;
 }
        public ActionResult <TestStudent> Result([FromBody] ICollection <Question> array)// List<Question> array
        {
            // Check answered and return database
            // Дописать null
            Console.WriteLine("result = " + (array == null));
            if (array == null)
            {
                return(null);
            }

            string idTest    = Request.Cookies["test"];
            var    startDate = Request.Cookies["dateStart"];

            if (idTest == null)
            {
                idTest = Request.Headers["test"];
            }
            if (startDate == null)
            {
                startDate = Request.Headers["dateStart"];
            }

            Console.WriteLine($"test id = {idTest}");
            Test test = _context.Tests.FirstOrDefault(a => a.Id.Equals(idTest));

            TestStudent testStudent = new TestStudent();

            testStudent.Id = Guid.NewGuid().ToString();
            //testStudent.IpAddress = HttpContext.Connection.RemoteIpAddress.ToString();
            testStudent.Test   = test;
            testStudent.TestId = idTest;

            List <QuestionAnswer> questionAnswers = new List <QuestionAnswer>();
            QuestionAnswer        answer;

            long allTime = 0;

            foreach (var quest in array)
            {
                answer             = new QuestionAnswer();
                answer.Id          = Guid.NewGuid().ToString();
                answer.TestStudent = testStudent;

                answer.QuestionId = quest.Id;// (string) array[i]["id"].ToString();
                answer.Question   = _context.Questions.FirstOrDefault(a => a.Id.Equals(quest.Id));

                answer.Answers = quest.RightAnswers;// Users answers
                answer.Time    = quest.Time;
                allTime       += answer.Time;

                answer.Name        = answer.Question.Name;
                answer.Description = answer.Question.Description;

                answer.QuestionAnswers      = answer.Question.Answers;
                answer.QuestionRightAnswers = answer.Question.RightAnswers;
                answer.Appraisal            = answer.Question.Appraisal;

                questionAnswers.Add(answer);
            }
            testStudent.Time            = allTime;
            testStudent.QuestionAnswers = questionAnswers;
            testStudent            = CreateQuestionsStudent.ResultTest(testStudent);
            testStudent.DateFinish = DateTime.Now;
            testStudent.DateStart  = new DateTime(long.Parse(startDate));

            return(Ok(testStudent));
        }
        protected override void Seed(JobPortalDbContext context)
        {
            #region employers

            var redHat = new Employer
            {
                Name         = "RedHat",
                Address      = "Brno, CzechRepublic",
                Email        = "*****@*****.**",
                PhoneNumber  = "+420 123 456 789",
                PasswordHash = "rh_pwd",
                PasswordSalt = "****"
            };
            var google = new Employer
            {
                Name         = "Google",
                Address      = "MountainView, CA",
                Email        = "*****@*****.**",
                PhoneNumber  = "+421 123 456 789",
                PasswordHash = "google_pwd",
                PasswordSalt = "****"
            };

            var microsoft = new Employer
            {
                Name         = "Microsoft",
                Address      = "Praha, CZ",
                Email        = "*****@*****.**",
                PhoneNumber  = "(425) 882-8080",
                PasswordHash = "ms_pwd",
                PasswordSalt = "****"
            };

            context.Employers.Add(redHat);
            context.Employers.Add(google);
            context.Employers.Add(microsoft);

            #endregion

            #region skills

            var cSharp = new SkillTag {
                Name = "C#"
            };
            var java = new SkillTag {
                Name = "Java"
            };
            var php = new SkillTag {
                Name = "Php"
            };
            var angular = new SkillTag {
                Name = "Angular"
            };
            var android = new SkillTag {
                Name = "Android"
            };

            context.SkillTags.Add(cSharp);
            context.SkillTags.Add(java);
            context.SkillTags.Add(php);
            context.SkillTags.Add(angular);
            context.SkillTags.Add(android);

            #endregion

            #region users

            var piskula = new User
            {
                FirstName   = "Piskula",
                LastName    = "Zeleny",
                Email       = "*****@*****.**",
                PhoneNumber = "+420 123 456 789",
                Education   = "High School of Live",
                Skills      = new List <SkillTag>
                {
                    java,
                    php,
                    angular
                },
                PasswordHash = "password",
                PasswordSalt = "aaaa",
            };

            var madki = new User
            {
                FirstName   = "Madki",
                LastName    = "Programmer",
                Email       = "*****@*****.**",
                PhoneNumber = "+421 999 666 789",
                Education   = "Programming High",
                Skills      = new List <SkillTag>
                {
                    java,
                    cSharp,
                    android
                },
                PasswordHash = "password",
                PasswordSalt = "aaaa",
            };

            var anonymous = new Applicant()
            {
                FirstName   = "Anonymous",
                LastName    = "Inkognito",
                Email       = "*****@*****.**",
                PhoneNumber = "+420 5565893",
                Education   = "Secret"
            };

            context.Applicants.Add(piskula);
            context.Applicants.Add(madki);
            context.Applicants.Add(anonymous);

            #endregion

            #region questions

            var javaExperience = new Question {
                Text = "What is your exeperience with Java programming?"
            };
            var javaEeExperience = new Question {
                Text = "What is your exeperience with Java EE programming?"
            };
            var cSharpExperience = new Question {
                Text = "What is your exeperience with .Net programming?"
            };
            var webExperience = new Question {
                Text = "What is your exeperience with web application programming?"
            };
            var androidExperience = new Question {
                Text = "What is your exeperience with Android programming?"
            };
            var softSkills = new Question {
                Text = "Tell us about your soft skills"
            };
            var hobby = new Question {
                Text = "What is your hobby?"
            };

            context.Questions.Add(javaExperience);
            context.Questions.Add(javaEeExperience);
            context.Questions.Add(cSharpExperience);
            context.Questions.Add(webExperience);
            context.Questions.Add(androidExperience);
            context.Questions.Add(softSkills);
            context.Questions.Add(hobby);

            #endregion

            #region job offers

            var googleAndroidOffer = new JobOffer
            {
                Name        = "Associate Android Developer",
                Employer    = google,
                Location    = "Paris, FR",
                Description = "Develop apps for Android - it will be fun!",
                Skills      = new List <SkillTag>
                {
                    java,
                    android
                },
                Questions = new List <Question>
                {
                    softSkills,
                    javaExperience,
                    androidExperience
                }
            };

            var googleBackendOffer = new JobOffer
            {
                Name        = "Java backend senior",
                Employer    = google,
                Location    = "Vienna, Austria",
                Description = "Be a backend hero!",
                Skills      = new List <SkillTag>
                {
                    java
                },
                Questions = new List <Question>
                {
                    javaExperience,
                    javaEeExperience
                }
            };

            var googleFronetEndOffer = new JobOffer
            {
                Name        = "Javascript front end developer",
                Employer    = google,
                Location    = "San Francisco, CA",
                Description = "Create amazing UI",
                Skills      = new List <SkillTag>
                {
                    angular,
                    php
                },
                Questions = new List <Question>
                {
                    webExperience,
                    softSkills,
                    hobby
                }
            };

            var microsoftCsharpDev = new JobOffer
            {
                Name        = "C# dev",
                Employer    = microsoft,
                Location    = "Seattle, WS",
                Description = "Lets see sharp!",
                Skills      = new List <SkillTag>
                {
                    cSharp
                },
                Questions = new List <Question>
                {
                    cSharpExperience
                }
            };

            var microsoftProjectManager = new JobOffer
            {
                Name        = "Project manager junior",
                Employer    = microsoft,
                Location    = "Seattle 2, WS",
                Description = "Manage amazing projects",
                Skills      = new List <SkillTag>
                {
                    cSharp
                },
                Questions = new List <Question>
                {
                    softSkills,
                    hobby
                }
            };

            var redHatQalityEngineer = new JobOffer
            {
                Name        = "Quality engineer",
                Employer    = redHat,
                Location    = "Brno, CZ",
                Description = "Quality matters",
                Skills      = new List <SkillTag>
                {
                    java
                },
                Questions = new List <Question>
                {
                    softSkills,
                    javaExperience,
                    javaEeExperience
                }
            };

            context.JobOffers.Add(googleAndroidOffer);
            context.JobOffers.Add(googleBackendOffer);
            context.JobOffers.Add(googleFronetEndOffer);
            context.JobOffers.Add(microsoftCsharpDev);
            context.JobOffers.Add(microsoftProjectManager);
            context.JobOffers.Add(redHatQalityEngineer);

            #endregion

            #region applications

            var applicationRedHatQuality = new JobApplication
            {
                Applicant            = madki,
                JobOffer             = redHatQalityEngineer,
                JobApplicationStatus = JobApplicationStatus.Open
            };

            var answersoftSkillsRedHat = new QuestionAnswer
            {
                Text        = "Great",
                Application = applicationRedHatQuality,
                Question    = softSkills
            };

            var answersJavaRedHat = new QuestionAnswer
            {
                Text        = "Very Good",
                Application = applicationRedHatQuality,
                Question    = javaExperience
            };

            var answerJavaEeRedHat = new QuestionAnswer
            {
                Text        = "Basic",
                Application = applicationRedHatQuality,
                Question    = javaEeExperience
            };

            applicationRedHatQuality.QuestionAnswers = new List <QuestionAnswer>
            {
                answersoftSkillsRedHat,
                answerJavaEeRedHat,
                answersJavaRedHat
            };


            context.QuestionAnswers.Add(answersoftSkillsRedHat);
            context.QuestionAnswers.Add(answerJavaEeRedHat);
            context.QuestionAnswers.Add(answersJavaRedHat);
            context.JobApplications.Add(applicationRedHatQuality);

            #endregion

            base.Seed(context);
        }
        public ActionResult Create([Bind(Include = "QuestionAnswerID,QuestionID,QuestionAnswer1")] QuestionAnswer questionAnswer)
        {
            if (ModelState.IsValid)
            {
                db.QuestionAnswers.Add(questionAnswer);
                db.SaveChanges();

                if (Session["QuestionType"].ToString() == "Multiple Choice")
                {
                    Session["QuestionAnswerAmount"] = Convert.ToInt32(Session["QuestionAnswerAmount"]) + 1;

                    if (Convert.ToInt32(Session["QuestionAnswerAmount"]) < 4)
                    {
                        return(RedirectToAction("Create"));
                    }
                    else
                    {
                        Session.Remove("QuestionAnswerAmount");
                        Session.Remove("QuestionID");
                        Session.Remove("Question");

                        return(RedirectToAction("Create", "Questions", new { @area = "Questions" }));
                    }
                }

                //if(Session["QuestionType"].ToString() == "Audio")
                //{
                //    Session["QuestionAnswerAmount"] = Convert.ToInt32(Session["QuestionAnswerAmount"]) + 1;

                //    if (Request.Files.Count > 0)
                //    {
                //        var file = Request.Files[0];

                //        if (file != null && file.ContentLength > 0)
                //        {
                //            var fileName = Path.GetFileName(file.FileName);
                //            var filePath = Path.Combine(Server.MapPath("~/Audio/"), fileName);
                //            file.SaveAs(filePath);

                //            Session.Remove("QuestionAnswerAmount");
                //            Session.Remove("QuestionID");
                //            Session.Remove("Question");

                //            return RedirectToAction("Create", "Questions", new { @area = "Questions" });
                //        }
                //    }
                //}

                //if(Session["QuestionType"].ToString() == "Video")
                //{
                //    Session["QuestionAnswerAmount"] = Convert.ToInt32(Session["QuestionAnswerAmount"]) + 1;

                //    if (Request.Files.Count > 0)
                //    {
                //        var file = Request.Files[0];

                //        if (file != null && file.ContentLength > 0)
                //        {
                //            var fileName = Path.GetFileName(file.FileName);
                //            var filePath = Path.Combine(Server.MapPath("~/Video/"), fileName);
                //            file.SaveAs(filePath);

                //            Session.Remove("QuestionAnswerAmount");
                //            Session.Remove("QuestionID");
                //            Session.Remove("Question");

                //            return RedirectToAction("Create", "Questions", new { @area = "Questions" });
                //        }
                //    }
                //}

                return(RedirectToAction("Index"));
            }

            ViewBag.QuestionID = new SelectList(db.Questions, "QuestionID", "Question1", questionAnswer.QuestionID);
            return(View(questionAnswer));
        }
        public ActionResult Create(BigModel bigModels)
        {
            // Loop and insert records.


            foreach (var allSurvey in bigModels.AllSurvey)
            {
                allSurvey.Status     = SurveyStatus.NOT_HAPPENNING_YET;
                allSurvey.CreateDate = DateTime.Now;
                allSurvey.UpdateDate = DateTime.Now.AddDays(7);
                db.Surveys.Add(allSurvey);
                db.SaveChanges();
                int    newIdSurvey = db.Surveys.Max(s => s.SurveyId);
                int    newIdQuest  = 0;
                string titleTemp;
                int    sttQuest = 0;
                for (int i = 0; i < bigModels.Question.Count; i++)
                {
                    bigModels.Question[i].SurveyId = newIdSurvey;
                    db.Questions.Add(bigModels.Question[i]);
                    db.SaveChanges();
                    if (i == 0)
                    {
                        newIdQuest = db.Questions.Max(q => q.Id);
                    }
                    if (bigModels.Question[i].Type == 3)
                    {
                        QaTemp q = new QaTemp();
                        q.Answer = "Other";
                        q.Title  = bigModels.Question[i].Title;
                        bigModels.QaTemps.Add(q);
                    }
                    if (bigModels.Question[i].Type == 4)
                    {
                        QaTemp q = new QaTemp();
                        q.Answer = "Essay";
                        q.Title  = bigModels.Question[i].Title;
                        bigModels.QaTemps.Add(q);
                    }
                    if (i == bigModels.Question.Count - 1)
                    {
                        titleTemp = bigModels.Question[sttQuest].Title;
                        foreach (var qaTemp in bigModels.QaTemps)
                        {
                            QuestionAnswer questionAnswer = new QuestionAnswer();
                            if (!qaTemp.Title.Equals(titleTemp))
                            {
                                titleTemp = qaTemp.Title;
                                newIdQuest++;
                                sttQuest++;
                            }
                            questionAnswer.Answer     = qaTemp.Answer;
                            questionAnswer.QuestionId = newIdQuest;
                            questionAnswer.Answer     = qaTemp.Answer;
                            db.Question_answers.Add(questionAnswer);
                            //bigModels.QaTemps.Remove(qaTemp);
                        }
                    }
                }
            }
            db.SaveChanges();

            return(RedirectToAction("Index"));
        }
 public static QuestionAnswerView ConvertToQuestionAnswerView(this QuestionAnswer answer)
 {
     return(Mapper.Map <QuestionAnswer, QuestionAnswerView>(answer));
 }
        public IActionResult Preview(int id)
        {
            QuestionAnswer questionAnswer = _db.QuestionAnswers.FirstOrDefault(q => q.Id == id);

            return(View(questionAnswer));
        }
        internal static object GetBlob(string objId)
        {
            if (typeof(T) == typeof(List <string>))
            {
                string[]      answerlist = { "1", "2", "3", "4", "5", "6" };
                List <string> al         = new List <string>(answerlist);
                return(al);
            }

            if (typeof(T) == typeof(SurveyAnswer))
            {
                List <QuestionAnswer> answers = new List <QuestionAnswer>();
                QuestionAnswer        answer;
                for (int i = 1; i < 11; i++)
                {
                    answer = new QuestionAnswer()
                    {
                        Answer       = "The answer to question " + i,
                        QuestionText = "Question " + i,
                        QuestionType = QuestionType.SimpleText
                    };
                    answers.Add(answer);
                }

                SurveyAnswer surveyAnswer = new SurveyAnswer()
                {
                    CreatedOn       = DateTime.Now,
                    QuestionAnswers = answers,
                    SlugName        = "SlugName",
                    Tenant          = "Tenant",
                    Title           = "Title"
                };
                return(surveyAnswer);
            }

            if (typeof(T) == typeof(Tenant))
            {
                if (objId.Equals("Adatum"))
                {
                    return(new Tenant
                    {
                        Name = "Adatum",
                        HostGeoLocation = "Anywhere US",
                        WelcomeText = "Adatum is a sample compaany",
                        SubscriptionKind = Models.SubscriptionKind.Premium,
                        IssuerIdentifier = "http://adatum/trust",
                        IssuerUrl = "https://localhost/Adatum.SimulatedIssuer.v2/",
                        IssuerThumbPrint = "f260042d59e14817984c6183fbc6bfc71baf5462",
                        ClaimType = "http://schemas.xmlsoap.org/claims/group",
                        ClaimValue = "Marketing Managers",
                    });
                }
                else if (objId.Equals("Fabrikam"))
                {
                    return(new Tenant
                    {
                        Name = "Fabrikam",
                        HostGeoLocation = "Anywhere US",
                        WelcomeText = "Fabrikam is a sample compaany",
                        SubscriptionKind = Models.SubscriptionKind.Standard,
                        IssuerIdentifier = "http://fabrikam/trust",
                        IssuerUrl = "https://localhost/Fabrikam.SimulatedIssuer.v2/",
                        IssuerThumbPrint = "d2316a731b59683e744109278c80e2614503b17e",
                        ClaimType = "http://schemas.xmlsoap.org/claims/group",
                        ClaimValue = "Marketing Managers",
                    });
                }
                else if (objId.Equals("Contoso"))
                {
                    return(new Tenant
                    {
                        Name = "Contoso",
                        HostGeoLocation = "Anywhere US",
                        WelcomeText = "Contoso is a sample compaany",
                        SubscriptionKind = Models.SubscriptionKind.Premium,
                        IssuerIdentifier = "http://contoso/trust",
                        IssuerUrl = "https://localhost/Contoso.SimulatedIssuer.v2/",
                        IssuerThumbPrint = "e5913a731b59683e744109278c80e2614504a618",
                        ClaimType = "http://schemas.xmlsoap.org/claims/group",
                        ClaimValue = "Marketing Managers",
                    });
                }
                else
                {
                    return(new Tenant()
                    {
                        Name = "tenant",
                        HostGeoLocation = "Anywhere US",
                        WelcomeText = "Another sample compaany",
                        SubscriptionKind = Models.SubscriptionKind.Premium,
                        IssuerIdentifier = "http://another/trust",
                        IssuerUrl = "https://localhost/Another.SimulatedIssuer.v2/",
                        IssuerThumbPrint = "f260042d59e14817984c6183fbc6bfc71baf5462",
                        ClaimType = "http://schemas.xmlsoap.org/claims/group",
                        ClaimValue = "Marketing Managers",
                    });
                }
            }
            return(null);
        }
Exemple #16
0
 public void AddToQuestionAnswer(QuestionAnswer QuestionAnswer)
 {
     this.QuestionAnswer.Add(QuestionAnswer);
 }
Exemple #17
0
    public void Load()
    {
        triviaList.Add("Rizal studied Philosophy and Letters at the University of Santo Tomas and Agriculture at the Ateneo Municipal de Manila. He left for Europe on May 5, 1882. He studied Medicine and Philosophy and Letters in Madrid, and finished these courses in 1884 and 1885.");
        triviaList.Add("Emilio Aguinaldo first studied in San Juan de Letran. He joined the revolution in 1896 as a lieutenant under Gen. Baldomero Aguinaldo and rose to the rank of general in a few months. Conducted campaign against Spain until Pact of Biac-na-Bato was signed in December 1897. Among the provisions of the Pact were: [1] Aguinaldo and his men would leave the Philippines [2]the Spanish government would give them an indemnity of P800,000. Spain sent only P400,000, which was used by the General Committee of Hongkong to finance second revolution.");
        triviaList.Add("Andres Bonifacio was born to Santiago Bonifacio and Catalina de Castro, a Spanish mestiza, in a shack in Tondo, Manila on November 30, 1863. He started his early education in the school of Guillermo Osmeña of Cebu. He reached only primary school. At the age of 14, his father and mother died, forcing him to quit his studies and to look after his younger brothers and sisters. As a means of support, he had them help him make wooden canes and paper fans, which he sold in the streets.");
        triviaList.Add("Emilio Jacinto was only 20 when he joined the Katipunan. He was always thinking and prudent, but vehement and furious when he thinks he is right. This quality was admired by Bonifacio.");
        triviaList.Add("Antonio Luna was the fiery-tempered but brilliant military strategist of Gen Aguinaldo. He was the brother of the famous painter Juan Luna. Antonio Luna studied Bachelor of Arts at the Ateneo Municipal de Manila, studied pharmacy at the Univerity of Santo Tomas, but finished it in Barcelona, Spain. He obtained his Doctor of Medicine at the Central University of Madrid, and studied further in France and Belgium.");
        //5
        triviaList.Add("(Tandang Sora)One of our most famous heroine in Philippine history was born in Banilad, Caloocan on January 6, 1812. Melchora Aquino is better known as Tandang Sora, because she was already old when the revolution broke out in 1896. She had very little education, but she had all the qualities of a literate person.");
        triviaList.Add("Marcelo H. del Pilar started school in the College of Mr. Jose Flores. He transferred to the College of San Jose in Manila. He finished law in 1880. Marcelo H. del Pilar was more popularly known as Plaridel. Multi-talented Plaridel played the violin, the piano and the flute. He was good in fencing. He used to sing in serenades and played beautiful pieces on the violin during Flores de Mayo");
        triviaList.Add("Born of a poor family, Apolinario Mabini was always studious. He was always sad and silent and liked to sit alone to meditate. Mabini studied at San Juan de Letran where he got his Bachelor of Arts degree and Professor of Latin. He also finished Law. He was a spokesman of the Congress, and a notary public.");
        triviaList.Add("The famous and beautiful Banaue or Banawe Rice Terraces is considered by Filipinos as the “8th wonder of the world”. This tourist spot is one of the most admired and most visited tourist attractions in the Philippines. This amazing human achievement was built over 2,000 years ago by the Ifugaos using primitive tools only such as stones and woods. This panoramic beauty is a manifestation of engineering skills and intelligence of native Filipinos.");
        triviaList.Add("Bangui Windmills - is a wind farm in Bangui, Ilocos Norte, Philippines. The wind farm uses 20 units of 70-metre (230 ft) high Vestas V82 1.65 MW wind turbines, arranged on a single row stretching along a nine-kilometer shoreline off Bangui Bay, facing the West Philippine Sea.");
        //10
        triviaList.Add("Paoay Church - The Saint Augustine Church (Spanish: Iglesia de San Agustín de Paoay), commonly known as the Paoay Church, is the Roman Catholic church of the municipality of Paoay, Ilocos Norte in the Philippines. Completed in 1710, the church is famous for its distinct architecture highlighted by the enormous buttresses on the sides and back of the building. It is declared as a National Cultural Treasure by the Philippine government in 1973 and a UNESCO World Heritage Site under the collective group of Baroque Churches of the Philippines in 1993.");
        triviaList.Add("Baclaran Church - The National Shrine of Our Mother of Perpetual Help (Filipino: Pambansáng Dambana ng Ina ng Laging Saklolo) also known as Redemptorist Church and colloquially the Baclaran Church, is a prominent Catholic National shrine along Roxas Boulevard in Baclaran, Parañaque, a city within the southern part of Metro Manila, the capital of the Philippines.");
        triviaList.Add("Leyte Landing Memorial  - The Leyte Landing Memorial in Red Beach, Palo, marks the spot where American liberation forces of General Douglas MacArthur landed.The Battle of Leyte in the Pacific campaign of World War II was the invasion and conquest of Leyte in the Philippines by the United States and Australian forces and allied Filipino guerrillas under the command of General Douglas MacArthur and waged against the Imperial Japanese Army in the Philippines led by General Tomoyuki Yamashita from 17 October 1944 to 31 July 1945. The battle launched the Philippines campaign of 1944-45 for the recapture and liberation of the entire Philippine Archipelago and to end almost three years of Japanese occupation.");
        triviaList.Add("Intramuros - In Latin, Intramuros literally “within the walls”, meaning within the wall enclosure of the city. In 1951, Intramuros was declared a National Historical Monument. There 8 entrances in Intramuros. Most famous destination inside is the For Santiago.");
        triviaList.Add("Rizal Park - Kabalyeros de Rizal (Knights of Rizal), honor guards from the Philippine Marines stands 14-hour days watching. It was designed by a Swiss sculptor Richard Kissling and his design is the Motto Stella or “Guiding Star”. Unveiled on 1913 in the 17th Death Anniversary of Dr. Jose P. Rizal. It is almost been a protocol to lay a wreath and to show respect for visiting dignitaries. It is not merely the statue of the national hero, but also a burial site of his remains. Known as Kilometer 0. It serves as the reference point to all places in the Philippines.");

        triviaList.Add("Chocolate Hills - One of many top sights in the actual Philippines, The Chocolate  Hills are unusual geological formations that include at lowest 1, 268 specific mounds scattered during the entire interior on the island regarding Bohol. The virtually symmetrical along with same-sized formations vary from 98 to be able to 164 ft (30 to be able to 50 meters) high and they are covered within the  green lawn.During the actual dry time of year the your lawn turns brown, consequently the label. There is no consensus about how these large mole slopes were created. One concept holds which the Chocolate Hills are classified as the weathered stone formations of a form of marine limestone on top of an impermeable covering of clay surfaces.");
        triviaList.Add("Barasoain Church - Barasoain Church (also known as Our Lady of Mt. Carmel Parish) is a Roman Catholic church built in 1630 in Malolos, Bulacan. It is about 42 kilometers away from Manila. Having earned the title as the Cradle of Democracy in the East, the most important religious building in the Philippines, and the site of the First Philippine Republic, the church is proverbial for its historical importance among Filipinos.");
        triviaList.Add("Corregidor - In January 1958 a detachment of US Marines from Subic Bay set up a small radar station on Corregidor. They were TDY there for about ten weeks, bivouacking in the remains of the hospital. Actor John Wayne, while filming the movie The Barbarian and the Geisha, took a helicopter to Corregidor for a visit. While there, he had lunch with the marines.");
        triviaList.Add("Fort Santiago (Spanish: Fuerte de Santiago Tagalog: Moog ng Santiago) is a citadel first built by Spanish conquistador, Miguel López de Legazpi for the new established city of Manila in the Philippines. The defense fortress is part of the structures of the walled city of Manila referred to as Intramuros (within the walls).");
        triviaList.Add("EDSA Shrine is a small church of the Roman Catholic Archdiocese of Manila located at the intersection of Ortigas Avenue and Epifanio de los Santos Avenue (EDSA) in Barangay Ugong Norte, Quezon City.");
        //5
        triviaList.Add("Malacañang palace is the official residence and principal workplace of the President of the Philippines.");
        triviaList.Add("Magellan's Cross is a Christian cross planted by Portuguese, and Spanish explorers as ordered by Ferdinand Magellan upon arriving in Cebu in the Philippines ");
        triviaList.Add("Lapu-Lapu (fl. 1521) was a ruler of Mactan in the Visayas. The Philippines regards him as the first Filipino hero because he was the first native to resist Spanish colonization through his victory over the explorer Ferdinand Magellan.");
        triviaList.Add("Considered one of the best examples of Hispanic architecture in the Philippines, the home of the Rizal family in Calamba, Laguna, is now preserved as a historical site. The old stone facades remain, as do the Rizal family heirlooms found inside the house. Steeped in the shadows of the past, you can almost see the ghost of a young Jose Rizal wandering around the corridors or peering at visitors from behind doors.");
        triviaList.Add("VIGAN HERITAGE CITY - Vigan was part of our Ilocos to Pangasinan tour. We first explored Laoag, went up north to Pagudpod to enjoy the serene white beach there, then travelled south to Batac to visit Vigan Heritage Village, Ilocos SurMarcos Museum, Vigan, and finally, Pangasinan.Vigan Heritage Village is where Ilocos region’s rich culture and history are crafted in ornate architecture, furniture and detailed ornaments. For this reason, Vigan Heritage Village was considered a UNESCO Heritage Site to preserve the cultural past of the Ilocandia region.");
        //10
        triviaList.Add("BIAK-NA-BATO - Biyak na Bato is a national park.  It was declared so by President Manuel L. Quezon in 1937. History has it that Filipino revolutionaries like Emilio Aguinaldo used the numerous caves of Biak na Bato as refuge when they fought against the spaniards.The caves of Biak na Bato are no ordinary caves.  The caves are beautifully lined with gigantic stalactites and awesome rock formations.  Some are even teeming with wildlife.  And, there are so many caves to explore!  Aside from the dozen or so famous caves, the guides estimate that there are nearly a hundred caves in Biak na Bato.");
        triviaList.Add("FORT SAN PEDRO - Fuerte de San Pedro is a military defence structure, built by Spanish and indigenous Cebuano labourers under the command of Spanish conquistador, Miguel López de Legazpi and the Spanish Government in Cebu. It is located in the area now called Plaza Indepedencia, in the pier area of the city. The smallest, oldest triangular bastion fort in the country was built in 1738 to repel Muslim raiders. In turn, it served as a stronghold for Filipino revolutionaries near the end of the 19th century. This served as the nucleus of the first Spanish settlement in the Philippines.");
        triviaList.Add("PUGAD LAWIN - The Cry of Pugad Lawin (Filipino: Sigáw ng Pugad Lawin), alternately and originally referred to as the Cry of Balintawak (Filipino: Sigáw ng Balíntawák, Spanish: Grito de Balíntawák) was the beginning of the Philippine Revolution against the Spanish Empire.At the close of August 1896, members of the Katipunan secret society (Katipuneros) led by Andrés Bonifacio rose up in revolt somewhere in an area referred to as Kalookan, wider than the jurisdiction of present-day Caloocan City and overlapping into present-day Quezon City. Originally the term `Cry` referred to the first skirmish between the Katipuneros and the Civil Guards (Guardia Civil). Other definitions of the term have been made over the years, but today it is popularly understood to refer to the tearing of community tax certificates (cédulas personales) by the rebels to mark their separation from Spain. This was literally accompanied by patriotic shouts.");
        triviaList.Add("SANTA ISABEL FORT  - Santa Isabel Fort in Palawan This fort was built in the mid to late 17th century by the Augustinian Recollects who replaced the early Jesuit community. In those days, the church and the military travelled hand-in-hand throughout the Philippines, building small chapels and protecting them with large fortified walls and a military regiment. Both the fort's cannon and its chapel remain intact to this day. Santa Isabel Fort is located in the town of Taytay, eight hours by jeepney from Puerto Princesa.");
        triviaList.Add("AGUINALDO SHRINE  - The Aguinaldo Shrine is the national shrine located in Kawit, Cavite in the Republic of the Philippines, where the independence of the Philippines from Spain was declared on June 12, 1898.[4] To commemorate the event, now known as Araw ng Kalayaan or Independence Day, a national holiday, the Philippine flag is raised here by top government officials on June 12th each year. The house is now a museum.");



        string zeroanswers = "Jose Rizal,Emilio Aguinaldo,Andres Bonifacio,Emilio Jacinto,Antonio Luna,Melchora Aquino,Marcelo Del Pilar,Apolinario mabini";

        string[] questionzeroanswers = zeroanswers.Split(',');
        int      ctr = 0;

        foreach (string s in questionzeroanswers)
        {
            QuestionAnswer qa = new QuestionAnswer();
            qa.answer     = s;
            qa.questionID = 0;
            qa.trivia     = triviaList[ctr];
            questionanswerBank.Add(qa);
            ctr++;
        }
        string oneanswers = "Banaue Rice Terraces,Bangui Windmills,Paoay Church,Baclaran Church,Leyte Landing Memorial,Intramuros,Rizal Park,Chocolate Hills,Barasoain Church,Corregidor,Fort Santiago,Edsa Shrine,Malacanang,MAGELLAN'S CROSS,LAPU-LAPU MONUMENT,RIZAL'S HOUSE,VIGAN HERITAGE CITY,BIAK-NA-BATO,FORT SAN PEDRO,PUGAD LAWIN MONUMENT,SANTA ISABEL FORT,AGUINALDO SHRINE";

        string[] questiononeanswers = oneanswers.Split(',');
        foreach (string s in questiononeanswers)
        {
            QuestionAnswer qa = new QuestionAnswer();
            qa.answer     = s;
            qa.questionID = 1;
            qa.trivia     = triviaList[ctr];
            questionanswerBank.Add(qa);
            ctr++;
        }

        Debug.Log(questionanswerBank.Count + " total answer entries");
    }
        public ActionResult Assessment(AssessmentViewModel assessment)
        {
            int    courseId = _coursesContentService.GetCourseId(Umbraco.AssignedContentItem);
            string username = User.Identity.Name;

            if (!_feedbackService.UserHasSentFeedback(username, courseId))
            {
                return(RedirectToRoute("Feedback", new { courseNiceUrl = Umbraco.AssignedContentItem.UrlName }));
            }

            if (_assessments.GetEligibilityStatus(username, courseId) != AssessmentEligibilityStatus.Eligible)
            {
                return(Redirect(Umbraco.AssignedContentItem.Url));
            }

            if (assessment.AssessmentRequestId == default(int))
            {
                throw new ArgumentException("Assessment Id is missing from Assessment Submission. Cannot evaluate assessment");
            }

            var assessmentRequest = _assessments.GetAssessmentRequest(assessment.AssessmentRequestId);

            IEnumerable <IPublishedContent> questions = Umbraco.TypedContent(assessmentRequest.QuestionIds.Split(',').ToList());
            IPublishedContent assessmentContnet       = Umbraco.TypedContent(assessmentRequest.AssessmentExternalId);
            var requiredCorrectAnswers =
                assessmentContnet.GetPropertyValue <int>(
                    nameof(Models.Umbraco.DocumentTypes.Assessment.RequiredCorrectAnswers));

            if (requiredCorrectAnswers == default(int))
            {
                throw new ArgumentException($"Number of required correct answers is not set for assessment with ID: {assessmentRequest.AssessmentExternalId}");
            }

            AssessmentViewModel      assessmentViewModel = new AssessmentViewModel();
            List <QuestionViewModel> questionViewModel   = new List <QuestionViewModel>();


            _mapper.AddCustomMapping(typeof(IEnumerable <QuestionAnswer>).FullName, UmbracoMapperMappings.MapQuestionAnswer)
            .MapCollection(questions, questionViewModel)
            .Map(assessmentContnet, assessmentViewModel);

            assessmentViewModel.Questions = questionViewModel;
            int correctAnswers = 0;

            foreach (QuestionViewModel questionInDb in assessmentViewModel.Questions)
            {
                QuestionViewModel questionAnswered = assessment.Questions.Single(x => x.Id == questionInDb.Id);
                questionAnswered.QuestionText = questionInDb.QuestionText;
                bool isCorrectlyAnswered = true;
                foreach (QuestionAnswer answerInDb in questionInDb.Answers)
                {
                    QuestionAnswer answer = questionAnswered.Answers.Single(x => x.Index == answerInDb.Index);
                    answer.Text = answerInDb.Text;
                    if (answer.IsCorrect != answerInDb.IsCorrect)
                    {
                        isCorrectlyAnswered = false;
                        break;
                    }
                }

                if (isCorrectlyAnswered)
                {
                    correctAnswers++;
                }
            }

            var submission = new AssessmentSubmission
            {
                CourseId          = courseId,
                AssessmentRequest = assessmentRequest,
                Submission        = JsonConvert.SerializeObject(assessment.Questions)
            };

            if (correctAnswers >= requiredCorrectAnswers)
            {
                submission.IsSuccessful = true;
            }

            Certificate certificate;

            _assessments.CreateAssessmentSubmission(submission, out certificate);

            if (submission.IsSuccessful)
            {
                TempData["SuccessfulSubmission"] = true;
                TempData["CorrectAnswers"]       = correctAnswers;
                TempData["RequiredAnswers"]      = requiredCorrectAnswers;
                return(RedirectToRoute("Certificate", new { certificateCode = certificate.Code }));
            }

            return(View("AssessmentFailure", new AssessmentFailureViewModel
            {
                CorrectAnswers = correctAnswers,
                RequiredAnswers = requiredCorrectAnswers,
                NumberOfQuestions = questions.Count(),
                CourseTitle = Umbraco.AssignedContentItem.Name,
                CourseUrl = Umbraco.AssignedContentItem.Url,
                // ReSharper disable once PossibleInvalidOperationException - This should never be null as we've just done a submission
                NextAttempt = _assessments.GetNextAssessmentAttemptDate(username, courseId).Value
            }));
        }
 private QuestionAnswer GetCountDetails(List <QuestionAnswer> allQuestionAnswer, QuestionAnswer currentQuestion)
 {
     currentQuestion.NoOfQuestions          = allQuestionAnswer.Count();
     currentQuestion.NoOfGroups             = allQuestionAnswer.GroupBy(q => q.Questions.GroupId).Count();
     currentQuestion.NoOfCompletedQuestions = allQuestionAnswer.Select(q => q.AnswerChoices.Any(t => t.IsChecked)).Count();
     return(currentQuestion);
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="resp"></param>
        /// <param name="context"></param>
        /// <param name="list"></param>
        /// <param name="listname"></param>
        private void AddResponseComponentOverride(QuestionResponse resp, CSET_Context context, List <Answer_Components_Base> list, string listname)
        {
            List <QuestionGroup> groupList = new List <QuestionGroup>();
            QuestionGroup        qg        = new QuestionGroup();
            QuestionSubCategory  sc        = new QuestionSubCategory();
            QuestionAnswer       qa        = new QuestionAnswer();

            string symbolType      = null;
            string componentName   = null;
            string curGroupHeading = null;
            string curSubHeading   = null;
            int    prevQuestionId  = 0;
            QuestionSubCategoryComparator comparator = new QuestionSubCategoryComparator();

            int displayNumber = 0;

            //push a new group if component_type, component_name, or question_group_heading changes

            foreach (var dbQ in list)
            {
                if ((dbQ.Symbol_Name != symbolType) ||
                    (dbQ.ComponentName != componentName))
                {
                    qg = new QuestionGroup()
                    {
                        GroupHeadingText  = dbQ.Question_Group_Heading,
                        GroupHeadingId    = dbQ.GroupHeadingId,
                        StandardShortName = listname,
                        Symbol_Name       = dbQ.Symbol_Name,
                        ComponentName     = dbQ.ComponentName,
                        IsOverride        = true
                    };
                    groupList.Add(qg);
                    symbolType    = dbQ.Symbol_Name;
                    componentName = dbQ.ComponentName;

                    curGroupHeading = qg.GroupHeadingText;
                    // start numbering again in new group
                    displayNumber = 0;
                }

                // new subcategory -- break on pairing ID to separate 'base' and 'custom' pairings
                if ((dbQ.Universal_Sub_Category != curSubHeading) || (dbQ.Question_Id == prevQuestionId))
                {
                    sc = new QuestionSubCategory()
                    {
                        GroupHeadingId         = dbQ.GroupHeadingId,
                        SubCategoryId          = dbQ.SubCategoryId,
                        SubCategoryHeadingText = dbQ.Universal_Sub_Category,
                        HeaderQuestionText     = dbQ.Sub_Heading_Question_Description,
                        SubCategoryAnswer      = this.subCatAnswers.Where(x => x.HeadingId == dbQ.heading_pair_id).FirstOrDefault()?.AnswerText
                    };

                    qg.SubCategories.Add(sc);
                    curSubHeading = dbQ.Universal_Sub_Category;
                }
                prevQuestionId = dbQ.Question_Id;
                qa             = new QuestionAnswer()
                {
                    DisplayNumber = (++displayNumber).ToString(),
                    QuestionId    = dbQ.Question_Id,
                    QuestionType  = "Component",
                    QuestionText  = FormatLineBreaks(dbQ.Simple_Question),
                    Answer        = dbQ.Answer_Text,
                    Answer_Id     = dbQ.Answer_Id,
                    AltAnswerText = dbQ.Alternate_Justification,
                    Comment       = dbQ.Comment,
                    MarkForReview = dbQ.Mark_For_Review ?? false,
                    Reviewed      = dbQ.Reviewed ?? false,
                    Feedback      = dbQ.Feedback,
                    ComponentGuid = dbQ.Component_Guid ?? Guid.Empty
                };

                sc.Questions.Add(qa);
            }


            resp.Domains[0].Categories.AddRange(groupList);
            resp.QuestionCount         += list.Count;
            resp.DefaultComponentsCount = list.Count;
        }
        public List <QuestionAnswer> GetAllQuestions()
        {
            var listOfQuestions = new List <QuestionAnswer>();
            var uInfo           = new Repository <Organization>();


            int sectorValue = int.Parse(Utilities.SectorValue);

            var userSectorId = uInfo.Filter(q => q.Id == this.UserId).FirstOrDefault();

            var assessmentDetails = uInfo.AssessmentContext.assessments.Where(q => q.Sector == userSectorId.SectorId).FirstOrDefault();

            if (assessmentDetails == null || assessmentDetails.Sector == 0)
            {
                assessmentDetails = uInfo.AssessmentContext.assessments.Where(q => q.Sector == sectorValue).FirstOrDefault();
            }

            //var details = uInfo.AssessmentContext.UserInfo.Join(uInfo.AssessmentContext.assessments, u => u.SectorId, a => a.Sector, (u, a) => new { u, a }).Where(q => q.u.Id == UserId).FirstOrDefault();

            var questionIds = uInfo.AssessmentContext.assessmentLevelMappings.Where(q => q.AssessmentId == assessmentDetails.Id && q.Level == userSectorId.CurrentAssignmentType).Select(q => q.QuestionId).ToList();
            var lQuestions  = uInfo.AssessmentContext.questions.Where(q => questionIds.Contains(q.Id)).GroupBy(q => q.GroupId).Select(q => new { Questions = q.ToList(), Type = q.Key }).OrderBy(t => t.Type).ToList();

            int i    = 1;
            int slno = 1;

            lQuestions.ForEach(t =>
            {
                t.Questions.ForEach(v =>
                {
                    var question = new QuestionAnswer();

                    question.Questions = new QuestionQuiz()
                    {
                        UIQId = i, QuestionCode = "Q" + i, QuestionId = v.Id, QuestionText = v.QuestionText, GroupId = v.GroupId, Mandatory = v.Mandatory, Slno = slno
                    };

                    question.Questions.GroupText = uInfo.AssessmentContext.groups.Where(q => q.Id == t.Type).FirstOrDefault().Name;
                    question.AssessmentName      = assessmentDetails.Name;

                    var answerChoice = new List <AnswerChoice>();

                    answerChoice.Add(new AnswerChoice()
                    {
                        AnswerChoiceId = 1, Choices = v.Option1
                    });
                    answerChoice.Add(new AnswerChoice()
                    {
                        AnswerChoiceId = 2, Choices = v.Option2
                    });
                    answerChoice.Add(new AnswerChoice()
                    {
                        AnswerChoiceId = 3, Choices = v.Option3
                    });
                    answerChoice.Add(new AnswerChoice()
                    {
                        AnswerChoiceId = 4, Choices = v.Option4
                    });
                    answerChoice.Add(new AnswerChoice()
                    {
                        AnswerChoiceId = 5, Choices = v.Option5
                    });

                    question.AnswerChoices = answerChoice;

                    listOfQuestions.Add(question);
                    i++;
                    slno++;
                });
            });
            return(listOfQuestions);
        }
Exemple #22
0
        private void AddResponse(QuestionResponse resp, CSET_Context context, List <Answer_Components_Base> list, string listname)
        {
            List <QuestionGroup> groupList = new List <QuestionGroup>();
            QuestionGroup        qg        = new QuestionGroup();
            QuestionSubCategory  sc        = new QuestionSubCategory();
            QuestionAnswer       qa        = new QuestionAnswer();

            string curGroupHeading  = null;
            int    curHeadingPairId = 0;


            int displayNumber = 0;


            foreach (var dbQ in list)
            {
                if (dbQ.Question_Group_Heading != curGroupHeading)
                {
                    qg = new QuestionGroup()
                    {
                        GroupHeadingText  = dbQ.Question_Group_Heading,
                        GroupHeadingId    = dbQ.GroupHeadingId,
                        StandardShortName = listname,
                        Symbol_Name       = dbQ.Symbol_Name,
                        ComponentName     = dbQ.ComponentName
                    };
                    groupList.Add(qg);
                    curGroupHeading = qg.GroupHeadingText;
                    // start numbering again in new group
                    displayNumber = 0;
                }

                // new subcategory -- break on pairing ID to separate 'base' and 'custom' pairings
                if (dbQ.heading_pair_id != curHeadingPairId)
                {
                    sc = new QuestionSubCategory()
                    {
                        GroupHeadingId         = dbQ.GroupHeadingId,
                        SubCategoryId          = dbQ.SubCategoryId,
                        SubCategoryHeadingText = dbQ.Universal_Sub_Category,
                        HeaderQuestionText     = dbQ.Sub_Heading_Question_Description,
                        SubCategoryAnswer      = this.subCatAnswers.Where(x => x.HeadingId == dbQ.heading_pair_id).FirstOrDefault()?.AnswerText
                    };

                    qg.SubCategories.Add(sc);

                    curHeadingPairId = dbQ.heading_pair_id;
                }

                qa = new QuestionAnswer()
                {
                    DisplayNumber  = (++displayNumber).ToString(),
                    QuestionId     = dbQ.Question_Id,
                    QuestionText   = FormatLineBreaks(dbQ.Simple_Question),
                    Answer         = dbQ.Answer_Text,
                    Answer_Id      = dbQ.Answer_Id,
                    AltAnswerText  = dbQ.Alternate_Justification,
                    Comment        = dbQ.Comment,
                    MarkForReview  = dbQ.Mark_For_Review ?? false,
                    Reviewed       = dbQ.Reviewed ?? false,
                    Is_Component   = dbQ.Is_Component,
                    ComponentGuid  = dbQ.Component_Guid ?? Guid.Empty,
                    Is_Requirement = dbQ.Is_Requirement,
                    Feedback       = dbQ.Feedback
                };

                sc.Questions.Add(qa);
            }


            var container = new Domain()
            {
                DisplayText = listname
            };

            container.Categories.AddRange(groupList);
            resp.Domains.Add(container);
            resp.QuestionCount         += list.Count;
            resp.DefaultComponentsCount = list.Count;
        }
Exemple #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="assessmentId"></param>
        public object GetMaturityQuestions(int assessmentId)
        {
            // Populate response
            var response = new QuestionResponse
            {
                Domains = new List <Domain>()
            };


            using (var db = new CSET_Context())
            {
                var myModel = db.AVAILABLE_MATURITY_MODELS
                              .Include(x => x.model_)
                              .Where(x => x.Assessment_Id == assessmentId).FirstOrDefault();

                if (myModel == null)
                {
                    return(response);
                }

                // see if any answer options should not be in the list
                var suppressedAnswerOptions = myModel.model_.Answer_Options_Suppressed;
                if (!string.IsNullOrEmpty(suppressedAnswerOptions))
                {
                    var a = suppressedAnswerOptions.Split(',');
                    foreach (string suppress in a)
                    {
                        response.AnswerOptions.Remove(suppress);
                    }
                }


                // The maturity target level is stored similar to a SAL level
                int targetLevel = 0;
                var myLevel     = db.ASSESSMENT_SELECTED_LEVELS.Where(x => x.Assessment_Id == assessmentId && x.Level_Name == "Maturity_Level").FirstOrDefault();
                if (myLevel != null)
                {
                    targetLevel = int.Parse(myLevel.Standard_Specific_Sal_Level);
                }

                // get the level display names
                // (for now assume that the assessment uses a single model)
                var levelNames = new List <MaturityLevel>();
                foreach (var l in db.MATURITY_LEVELS.Where(x => x.Maturity_Model_Id == myModel.model_id)
                         .OrderBy(y => y.Level).ToList())
                {
                    levelNames.Add(new MaturityLevel()
                    {
                        Level      = l.Level,
                        Label      = l.Level_Name,
                        Applicable = l.Level <= targetLevel
                    });
                }


                // Get all maturity questions for the model regardless of level
                // The user can choose to see questions above the target level via filtering.
                var questions = db.MATURITY_QUESTIONS.Where(q =>
                                                            myModel.model_id == q.Maturity_Model_Id).ToList();


                // Get all MATURITY answers for the assessment
                var answers = from a in db.ANSWER.Where(x => x.Assessment_Id == assessmentId && x.Is_Maturity)
                              from b in db.VIEW_QUESTIONS_STATUS.Where(x => x.Answer_Id == a.Answer_Id).DefaultIfEmpty()
                              select new FullAnswer()
                {
                    a = a, b = b
                };



                // CMMC has 17 domains, which correspond to Categories in the
                // MATURITY_QUESTIONS table.
                // TODO:  Eventually they should probably be defined in a new generic
                // MATURITY_DOMAINS table.
                var domains = questions.Select(x => x.Category).Distinct().ToList();

                // build a container for each domain
                foreach (var d in domains)
                {
                    response.Domains.Add(new Domain()
                    {
                        DisplayText = d,
                        DomainText  = d,
                        Levels      = levelNames
                    });
                }

                foreach (var dbR in questions)
                {
                    // Make sure there are no leading or trailing spaces - it will affect the tree structure that is built
                    dbR.Category     = dbR.Category ?? dbR.Category.Trim();
                    dbR.Sub_Category = dbR.Sub_Category ?? dbR.Sub_Category.Trim();

                    // If the Standard_Sub_Category is null (like CSC_V6), default it to the Standard_Category
                    if (dbR.Sub_Category == null)
                    {
                        dbR.Sub_Category = dbR.Category;
                    }


                    var json = JsonConvert.SerializeObject(response);

                    // drop into the domain
                    var targetDomain = response.Domains.Where(cc => cc.DomainText == dbR.Category).FirstOrDefault();
                    if (targetDomain != null)
                    {
                        // find or create a Category
                        var targetCat = targetDomain.Categories.Where(c => c.GroupHeadingText == dbR.Category).FirstOrDefault();
                        if (targetCat == null)
                        {
                            targetCat = new QuestionGroup()
                            {
                                GroupHeadingText = dbR.Category
                            };
                            targetDomain.Categories.Add(targetCat);
                        }


                        // find or create a Subcategory
                        var targetSubcat = targetCat.SubCategories.Where(sc => sc.SubCategoryHeadingText == dbR.Sub_Category).FirstOrDefault();
                        if (targetSubcat == null)
                        {
                            targetSubcat = new QuestionSubCategory()
                            {
                                SubCategoryId          = 0,
                                SubCategoryHeadingText = dbR.Sub_Category,
                                // GroupHeadingId = g.GroupHeadingId
                            };

                            targetCat.SubCategories.Add(targetSubcat);
                        }



                        FullAnswer answer = answers.Where(x => x.a.Question_Or_Requirement_Id == dbR.Mat_Question_Id).FirstOrDefault();

                        var qa = new QuestionAnswer()
                        {
                            DisplayNumber  = dbR.Question_Title,
                            QuestionId     = dbR.Mat_Question_Id,
                            QuestionText   = dbR.Question_Text.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>"),
                            Answer         = answer?.a.Answer_Text,
                            AltAnswerText  = answer?.a.Alternate_Justification,
                            Comment        = answer?.a.Comment,
                            Feedback       = answer?.a.Feedback,
                            MarkForReview  = answer?.a.Mark_For_Review ?? false,
                            Reviewed       = answer?.a.Reviewed ?? false,
                            MaturityLevel  = dbR.Maturity_Level,
                            SetName        = string.Empty,
                            Is_Maturity    = answer?.a.Is_Maturity ?? true,
                            Is_Component   = answer?.a.Is_Component ?? false,
                            Is_Requirement = answer?.a.Is_Requirement ?? false
                        };
                        if (answer != null)
                        {
                            TinyMapper.Bind <VIEW_QUESTIONS_STATUS, QuestionAnswer>();
                            TinyMapper.Map(answer.b, qa);
                        }

                        qa.ParmSubs = null;

                        targetSubcat.Questions.Add(qa);
                    }
                }

                return(response);
            }
        }
Exemple #24
0
        /// <summary>
        /// Recursive method that builds subgroupings for the specified group.
        /// It also attaches any questions pertinent to this group.
        /// </summary>
        private void BuildSubGroupings(MaturityGrouping g, int?parentID,
                                       List <MATURITY_GROUPINGS> allGroupings,
                                       List <MATURITY_QUESTIONS> questions,
                                       List <FullAnswer> answers)
        {
            var mySubgroups = allGroupings.Where(x => x.Parent_Id == parentID).OrderBy(x => x.Sequence).ToList();

            if (mySubgroups.Count == 0)
            {
                return;
            }

            foreach (var sg in mySubgroups)
            {
                var newGrouping = new MaturityGrouping()
                {
                    GroupingID   = sg.Grouping_Id,
                    GroupingType = sg.Type.Grouping_Type_Name,
                    Title        = sg.Title,
                    Description  = sg.Description
                };


                g.SubGroupings.Add(newGrouping);


                // are there any questions that belong to this grouping?
                var myQuestions = questions.Where(x => x.Grouping_Id == newGrouping.GroupingID).ToList();

                var parentQuestionIDs = myQuestions.Select(x => x.Parent_Question_Id).Distinct().ToList();

                foreach (var myQ in myQuestions)
                {
                    FullAnswer answer = answers.Where(x => x.a.Question_Or_Requirement_Id == myQ.Mat_Question_Id).FirstOrDefault();

                    var qa = new QuestionAnswer()
                    {
                        DisplayNumber     = myQ.Question_Title,
                        QuestionId        = myQ.Mat_Question_Id,
                        ParentQuestionId  = myQ.Parent_Question_Id,
                        QuestionType      = "Maturity",
                        QuestionText      = myQ.Question_Text.Replace("\r\n", "<br/>").Replace("\n", "<br/>").Replace("\r", "<br/>"),
                        Answer            = answer?.a.Answer_Text,
                        AltAnswerText     = answer?.a.Alternate_Justification,
                        Comment           = answer?.a.Comment,
                        Feedback          = answer?.a.Feedback,
                        MarkForReview     = answer?.a.Mark_For_Review ?? false,
                        Reviewed          = answer?.a.Reviewed ?? false,
                        Is_Maturity       = true,
                        MaturityLevel     = myQ.Maturity_LevelNavigation.Level,
                        MaturityLevelName = myQ.Maturity_LevelNavigation.Level_Name,
                        IsParentQuestion  = parentQuestionIDs.Contains(myQ.Mat_Question_Id),
                        SetName           = string.Empty
                    };

                    if (answer != null)
                    {
                        TinyMapper.Bind <VIEW_QUESTIONS_STATUS, QuestionAnswer>();
                        TinyMapper.Map(answer.b, qa);
                    }

                    newGrouping.Questions.Add(qa);
                }

                // Recurse down to build subgroupings
                BuildSubGroupings(newGrouping, newGrouping.GroupingID, allGroupings, questions, answers);
            }
        }
 public static int Add(int stdID, int examID, QuestionAnswer answer)
 {
     return(Convert.ToInt32(DBLayer.ExecuteScalar(string.Format("insert into Student_Exam_Question values('{0},{1},{2},{3},{4},{5}');select @@identity", stdID, examID, 0, false, answer, 0))));
 }
Exemple #26
0
        /// <summary>
        /// Zeichnet den verlauf einer einzelnen runde und gibt zurück ob diese die letzte ist
        /// </summary>
        /// <param name="round"></param>
        /// <returns></returns>
        private bool RenderRound(Round round)
        {
            bool flag = true;

            if (round.Questions == null)
            {
                Vector size = StateManager.GetStringSize("DU BIST DRAN");
                StateManager.SetColor(Color.DarkOrange);
                StateManager.FillRoundRect(Size.X / 4 - size.X / 2, 25 / 2f, size.X, size.Y);
                StateManager.SetColor(Color.White);
                StateManager.DrawCenteredString("DU BIST DRAN", Size.X / 4, 25);
                return(false);
            }
            float offset = 0;

            for (int i = 0; i < round.Questions.Length; i++)
            {
                QuestionAnswer question = round.Questions[i];
                if (question.AnswerPlayer == -1)
                {
                    Vector size = StateManager.GetStringSize("DU BIST DRAN");
                    StateManager.SetColor(Color.DarkOrange);
                    StateManager.FillRoundRect(Size.X / 4 - size.X / 2, 25 / 2f, size.X, size.Y);
                    StateManager.SetColor(Color.White);
                    StateManager.DrawCenteredString("DU BIST DRAN", Size.X / 4, 25);
                    flag = false;
                    break;
                }
                bool right = question.AnswerPlayer == 0;
                StateManager.SetColor(right ? Color.LawnGreen : Color.Red);
                float width = 25;
                StateManager.FillRoundRect(Size.X / 4 - width * 2 + offset, width / 2, width, width);
                offset += width;
            }
            offset = 0;
            for (int i = 0; i < round.Questions.Length; i++)
            {
                QuestionAnswer question = round.Questions[i];
                if (question.AnswerRemotePlayer == -1)
                {
                    if (!flag)
                    {
                        return(false);
                    }
                    Vector size = StateManager.GetStringSize("Warte auf " + game.RemotePlayer.Name);
                    StateManager.SetColor(Color.DarkOrange);
                    StateManager.FillRoundRect(Size.X / 4 * 3 - size.X / 2, 25 / 2f, size.X, size.Y);
                    StateManager.SetColor(Color.White);
                    StateManager.DrawCenteredString("Warte auf " + game.RemotePlayer.Name, Size.X / 4 * 3, 25);
                    return(false);
                }
                if (question.AnswerPlayer == -1)
                {
                    return(false);
                }
                bool right = question.AnswerRemotePlayer == 0;
                StateManager.SetColor(right ? Color.LawnGreen : Color.Red);
                float width = 25;
                StateManager.FillRoundRect(Size.X / 4 * 3 - width + offset, width / 2, width, width);
                offset += width;
            }
            return(flag);
        }
 public static ResponseModel Create(Response r, QuestionAnswer a) =>
Exemple #28
0
        public async Task <IActionResult> ReplyToQ(FileReply model, string returnUrl = null)
        {
            var us = await GetCurrentUserAsync();

            if (ModelState.IsValid)
            {
                // {   Console.WriteLine(model.Reply);
                AnswerModel qt = new AnswerModel {
                    // Reply=model.Reply,
                    // QId = model.QId,
                    // Time = DateTime.Now,
                    // ApplicationUser = us,
                    // RefAId = model.RefAId

                    Reply    = model.Reply,
                    QId      = model.QId,
                    Time     = DateTime.Now,
                    UserName = us.UserName,
                    RefAId   = model.RefAId
                };

                // var size=model.File.Length;



                // static string filePath = IHostingEnvironment.ContentRootPath + "\\wwwroot\\files\\"+ fileName;

                // if (model.File==null){
                //     Console.WriteLine("Nothing!");
                // }
                // model.File.SaveAs(IHostingEnvironment.ContentRootPath + "\\wwwroot\\files\\"+ fileName);
                if (model.File != null && model.File.Length != 0)
                {
                    var fileName = ContentDispositionHeaderValue
                                   .Parse(model.File.ContentDisposition)
                                   .FileName.Trim('"');
                    var path = Path.Combine(
                        "files",
                        fileName);

                    using (var stream = new FileStream(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/", path), FileMode.Create))
                    {
                        await model.File.CopyToAsync(stream);
                    }
                    qt.FilePath     = path;
                    qt.FileName     = fileName;
                    qt.FileUploaded = true;
                }



                db.Answers.Add(qt);
                db.SaveChanges();
                //return RedirectToAction("QuestionPage","Question", new { QId = qt.QId });
            }



            QuestionAnswer _model = new QuestionAnswer();

            _model.Answers  = db.Answers.ToList();
            _model.UserName = us.UserName;
            _model.QId      = model.QId;

            var fa = from i in db.Questions where i.QId == model.QId select i;
            var fe = fa.ToList <QuestionModel>().FirstOrDefault();

            _model.QuestionTitle   = fe.Title;
            _model.QuestionContent = fe.Description;
            //_model.Time=fe.Time;
            return(PartialView("QuestionPage", _model));



            // AnswerModel am=new AnswerModel();
            // am.RefAId=model.AnswerId;
            // am.QId=model.QId;
            // am.ApplicationUser=us;
            // return (am);
        }
        private void SaveAnswers()
        {
            foreach (Control control in pnlQuestions.Controls)
            {
                HtmlGenericControl convertedControl = control as HtmlGenericControl;

                //check this is a question container and not a spacer
                if (convertedControl as HtmlGenericControl != null && convertedControl.Attributes["class"] == "settingrow")
                {
                    IQuestion question = (IQuestion)control.Controls[0];
                    if (!String.IsNullOrEmpty(question.Answer))
                    {
                        QuestionAnswer answer = new QuestionAnswer(question.QuestionGuid, ResponseGuid);
                        answer.Answer = question.Answer;
                        answer.Save();
                    }
                }
            }
        }
Exemple #30
0
        public IActionResult Post(IncidentChatMessage chatMessage)
        //public IActionResult Post([FromBody] JsonElement body)
        {
            //var chatMessage = JsonConvert.DeserializeObject<IncidentChatMessage>(body.GetRawText());

            ChatReplyRawContent replyData;

            _logger.LogInformation("Chat Message Received!", chatMessage);
            var chatReply = new IncidentChatReply();

            chatReply.IncidentId       = chatMessage.IncidentId;
            chatReply.QuestionId       = chatMessage.QuestionId;
            chatReply.EquipmentId      = chatMessage.EquipmentId;
            chatReply.NetworkId        = chatMessage.NetworkId;
            chatReply.AnswerId         = chatMessage.AnswerId;
            chatReply.SessionCompleted = chatMessage.SessionCompleted;

            if (chatMessage.SessionCompleted)
            {
                chatReply.ReplyContent = "The chat session has ended!";
                return(Ok(chatReply));
            }

            int replyNumber;

            if (!int.TryParse(chatMessage.MessageContent, out replyNumber))
            {
                chatReply.IsError      = true;
                chatReply.ErrorMessage = "Invalid entry, please retart incident!";
                chatReply.ReplyContent = "Invalid entry, please retart incident!!!";

                return(Ok(chatReply));
            }
            var id = chatMessage.QuestionIDs.FirstOrDefault(i => i.Key == replyNumber.ToString()).Value;

            replyNumber = int.Parse(id);

            //var iDs = chatMessage.QuestionIDs;

            if (chatMessage.Stage == 2)
            {
                replyData              = InitUserNetworkEquipments(replyNumber);
                chatReply.NetworkId    = replyNumber;
                chatReply.ReplyContent = replyData.ChatText;
                chatReply.QuestionIDs  = replyData.QuestionIDs;

                return(Ok(chatReply));
            }

            if (chatMessage.Stage == 3)
            {
                replyData              = InitIncidentTypes();
                chatReply.EquipmentId  = replyNumber;
                chatReply.ReplyContent = replyData.ChatText;
                chatReply.QuestionIDs  = replyData.QuestionIDs;

                return(Ok(chatReply));
            }

            Incident incident;

            if (chatMessage.Stage == 4)
            {
                incident = new Incident
                {
                    IncidentTypeId         = replyNumber,
                    UserNetworkEquipmentId = chatMessage.EquipmentId,
                    IncidentDate           = DateTime.UtcNow
                };
                _dbContext.Incidents.Add(incident);
                _dbContext.SaveChanges();

                chatReply.IncidentId   = incident.IncidentId;
                chatMessage.IncidentId = incident.IncidentId;

                //return Ok(chatReply);
            }
            else
            {
                incident = _dbContext.Incidents.FirstOrDefault(i => i.IncidentId == chatMessage.IncidentId);
            }


            if (chatReply.IncidentId == 0)
            {
                //Restart CHat Request
                replyData              = InitUserNetworkEquipments(replyNumber);
                chatReply.NetworkId    = replyNumber;
                chatReply.ReplyContent = replyData.ChatText;
                chatReply.QuestionIDs  = replyData.QuestionIDs;

                return(Ok(chatReply));
            }

            Question       nextQuestion     = new Question();
            QuestionAnswer lastAnswer       = new QuestionAnswer();
            var            sessionCompleted = false;

            //var currentIncident = _dbContext.Incidents.FirstOrDefault(i=>i.IncidentId == chatMessage.IncidentId);

            //var incidentQuestions = _dbContext.IncudentTypeQuestions.Where(i => i.IncidentId == incident.IncidentId).ToList();

            if (chatMessage.QuestionId != 0)
            {
                var incidentTypeQuestion = new IncidentTypeQuestion {
                    AnswerId   = replyNumber,
                    IncidentId = incident.IncidentId,
                    QuestionId = chatMessage.QuestionId
                };
                _dbContext.IncidentTypeQuestions.Add(incidentTypeQuestion);
                _dbContext.SaveChanges();
            }

            if (!_dbContext.IncidentTypeQuestions.Any(i => i.IncidentId == incident.IncidentId))
            {
                nextQuestion = _dbContext.Questions.FirstOrDefault(q => q.IncidentTypeId == incident.IncidentTypeId);
            }
            else
            {
                var incidentQuestions = _dbContext.IncidentTypeQuestions.Where(i => i.IncidentId == incident.IncidentId).ToArray();
                lastAnswer = _dbContext.QuestionAnswers.FirstOrDefault(a => a.QuestionAnswerId == incidentQuestions[incidentQuestions.Length - 1].AnswerId);

                if (lastAnswer.NextQuestionId == 0)
                {
                    sessionCompleted = true;
                }
                else
                {
                    nextQuestion = _dbContext.Questions.FirstOrDefault(q => q.QuestionId == lastAnswer.NextQuestionId);
                }
            }

            if (sessionCompleted)
            {
                if (!string.IsNullOrWhiteSpace(lastAnswer?.Troubleshooting))
                {
                    chatReply.ReplyContent = "<strong>Troubleshooting:</strong><br />" + _getTroubleshootText(lastAnswer.Troubleshooting);
                }

                if (!string.IsNullOrWhiteSpace(lastAnswer?.Mitigation))
                {
                    //chatReply.ReplyContent += _getTroubleshootText(lastAnswer.Mitigation);
                    chatReply.ReplyContent += _getFinalMessage(incident);
                }


                chatReply.ReplyContent += "<br /><br />The chat session has ended!";

                chatReply.SessionCompleted = true;
                return(Ok(chatReply));
            }

            chatReply.QuestionId   = nextQuestion.QuestionId;
            replyData              = InitChatQuestionAnswer(nextQuestion);
            chatReply.ReplyContent = replyData.ChatText;
            chatReply.QuestionIDs  = replyData.QuestionIDs;


            _logger.LogInformation("Chat Reply Sent!", chatReply);

            return(Ok(chatReply));
        }
Exemple #31
0
 private bool HasAnsweredPreviously(QuestionAnswer questionAnswer)
 {
     return(questionAnswer != null);
 }
Exemple #32
0
        /// <summary>
        /// Constructs a response containing the applicable questions with their answers.
        /// </summary>
        /// <returns></returns>
        private QuestionResponse BuildResponse()
        {
            List <QuestionGroup> groupList = new List <QuestionGroup>();
            QuestionGroup        qg        = new QuestionGroup();
            QuestionSubCategory  sc        = new QuestionSubCategory();
            QuestionAnswer       qa        = new QuestionAnswer();

            int curGroupId   = 0;
            int curPairingId = 0;


            int displayNumber = 0;

            foreach (var dbQ in this.questions.OrderBy(x => x.QuestionGroupHeading)
                     .ThenBy(x => x.UniversalSubCategory)
                     .ThenBy(x => x.QuestionId))
            {
                if (dbQ.QuestionGroupHeadingId != curGroupId)
                {
                    qg = new QuestionGroup()
                    {
                        GroupHeadingId    = dbQ.QuestionGroupHeadingId,
                        GroupHeadingText  = dbQ.QuestionGroupHeading,
                        StandardShortName = "Standard Questions",
                        SetName           = dbQ.SetName
                    };

                    groupList.Add(qg);

                    curGroupId   = qg.GroupHeadingId;
                    curPairingId = 0;

                    // start numbering again in new group
                    displayNumber = 0;
                }



                // new subcategory -- break on pairing ID to separate 'base' and 'custom' pairings
                if (dbQ.PairingId != curPairingId)
                {
                    sc = new QuestionSubCategory()
                    {
                        GroupHeadingId         = qg.GroupHeadingId,
                        SubCategoryId          = dbQ.UniversalSubCategoryId,
                        SubCategoryHeadingText = dbQ.UniversalSubCategory,
                        HeaderQuestionText     = dbQ.SubHeadingQuestionText,
                        SubCategoryAnswer      = this.subCatAnswers.Where(sca => sca.GroupHeadingId == qg.GroupHeadingId &&
                                                                          sca.SubCategoryId == dbQ.UniversalSubCategoryId)
                                                 .FirstOrDefault()?.AnswerText
                    };

                    qg.SubCategories.Add(sc);

                    curPairingId = dbQ.PairingId;
                }

                FullAnswer answer = this.Answers.Where(x => x.a.Question_Or_Requirement_Id == dbQ.QuestionId).FirstOrDefault();

                qa = new QuestionAnswer()
                {
                    DisplayNumber  = (++displayNumber).ToString(),
                    QuestionId     = dbQ.QuestionId,
                    QuestionType   = dbQ.QuestionType,
                    QuestionText   = FormatLineBreaks(dbQ.SimpleQuestion),
                    Answer         = answer?.a?.Answer_Text,
                    Answer_Id      = answer?.a?.Answer_Id,
                    AltAnswerText  = answer?.a?.Alternate_Justification,
                    Comment        = answer?.a?.Comment,
                    Feedback       = answer?.a?.Feedback,
                    MarkForReview  = answer?.a.Mark_For_Review ?? false,
                    Reviewed       = answer?.a.Reviewed ?? false,
                    Is_Component   = answer?.a.Is_Component ?? false,
                    ComponentGuid  = answer?.a.Component_Guid ?? Guid.Empty,
                    Is_Requirement = answer?.a.Is_Requirement ?? false
                };
                if (answer != null)
                {
                    TinyMapper.Bind <VIEW_QUESTIONS_STATUS, QuestionAnswer>();
                    TinyMapper.Map(answer.b, qa);
                }

                sc.Questions.Add(qa);
            }

            QuestionResponse resp = new QuestionResponse
            {
                Domains         = new List <Domain>(),
                ApplicationMode = this.applicationMode
            };

            // create a dummy Domain to house all Categories
            var dummyDomain = new Domain()
            {
                DisplayText = "",
                Categories  = groupList
            };

            resp.Domains.Add(dummyDomain);

            resp.QuestionCount    = this.NumberOfQuestions();
            resp.RequirementCount = new RequirementsManager(this.assessmentID).NumberOfRequirements();

            return(resp);
        }
Exemple #33
0
        public static List<QuestionAnswer> getListAll(string connString)
        {
            #region code
            List<QuestionAnswer> lists = new List<QuestionAnswer>();
            using (SqlConnection conn = new SqlConnection(connString))
            {
                try
                {
                    conn.Open();
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = "sony_sp_get_all_faq";

                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                QuestionAnswer qa = new QuestionAnswer();
                                qa.Id = (int)reader["id"];
                                qa.Question = reader["question"].ToString();
                                qa.Answer = reader["answer"].ToString();
                                lists.Add(qa);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    WriteLog("", "Get All QuestionAnswer Error: " + ex.Message, connString);
                    return new List<QuestionAnswer>();
                }
            }
            return lists;
            #endregion
        }
        private void PopulateAnswer(IQuestion question)
        {
            //QuestionAnswer answer = new QuestionAnswer(question.QuestionGuid, ResponseGuid);
            QuestionAnswer answer = new QuestionAnswer(question.QuestionGuid, ResponseGuid);

            if (!String.IsNullOrEmpty(answer.Answer))
            {
                question.Answer = answer.Answer;
            }
        }
Exemple #35
0
 public AnswerEvaluation(QuestionAnswer answer, bool isCorrect)
 {
     FullAnswer           = answer;
     SubmissionWasCorrect = isCorrect;
 }
        public QuestionAnswerDTO Get(int id)
        {
            QuestionAnswer questionAnswer = _unitOfWork.QuestionAnswers.Get(id);

            return(Mapper.Map <QuestionAnswerDTO>(questionAnswer));
        }
Exemple #37
0
        public async Task <IActionResult> AnswerQuestion(int score, QuestionViewModel model)
        {
            if (ModelState.IsValid)
            {
                var question = await _context.Question
                               .Include(x => x.TestModule)
                               .SingleOrDefaultAsync(x => x.Id == model.Id);

                if (question == null)
                {
                    return(NotFound());
                }

                if (model.Type != question.Type)
                {
                    return(NotFound());
                }

                QuestionAnswer qAnswer = new QuestionAnswer
                {
                    Type     = question.Type,
                    Task     = question.Task,
                    Answers1 = question.Answers1,
                    Answers2 = question.Answers2,
                    Question = question,
                    Student  = await _userManager.GetUserAsync(User)
                };

                if (model.Type == "Input")
                {
                    if (model.Answers1[0] == question.Answers1)
                    {
                        score++;
                    }
                    qAnswer.StudentAnswer = model.Answers1[0];
                }
                else if (model.Type == "Choose")
                {
                    var answers = question.Answers1.Split('&').ToList();
                    if (answers.Count == model.Answers1.Count)
                    {
                        bool flag = true;
                        for (int i = 0; i < answers.Count; i++)
                        {
                            if (!answers.Contains(model.Answers1[i]))
                            {
                                flag = false;
                            }
                        }

                        if (flag)
                        {
                            score++;
                        }
                    }

                    string s = "";
                    for (int i = 0; i < model.Answers1.Count; i++)
                    {
                        s += model.Answers1[i] + "&";
                    }
                    if (model.Answers1.Count > 0)
                    {
                        s = s.Remove(s.Length - 1);
                    }
                    qAnswer.StudentAnswer = s;
                }
                else if (model.Type == "Mapping")
                {
                    var answers = question.Answers2.Split('&').ToList();
                    if (answers.Count == model.Answers2.Count)
                    {
                        bool flag = true;
                        for (int i = 0; i < answers.Count; i++)
                        {
                            if (answers[i] != model.Answers2[i])
                            {
                                flag = false;
                            }
                        }

                        if (flag)
                        {
                            score++;
                        }

                        string s = "";
                        for (int i = 0; i < model.Answers2.Count; i++)
                        {
                            s += model.Answers2[i] + "&";
                        }
                        if (model.Answers2.Count > 0)
                        {
                            s = s.Remove(s.Length - 1);
                        }
                        qAnswer.StudentAnswer = s;
                    }
                }
                else
                {
                    return(NotFound());
                }

                var existingAnswer = await _context.QuestionAnswer
                                     .Include(x => x.Question)
                                     .Include(x => x.Student)
                                     .SingleOrDefaultAsync(x => x.Question.Id == question.Id && x.Student.Id == _userManager.GetUserId(User));

                if (existingAnswer == null)
                {
                    _context.QuestionAnswer.Add(qAnswer);
                }
                else
                {
                    existingAnswer.Type          = qAnswer.Type;
                    existingAnswer.Task          = qAnswer.Task;
                    existingAnswer.Answers1      = qAnswer.Answers1;
                    existingAnswer.Answers2      = qAnswer.Answers2;
                    existingAnswer.StudentAnswer = qAnswer.StudentAnswer;

                    _context.QuestionAnswer.Update(existingAnswer);
                }

                await _context.SaveChangesAsync();

                if (_context.Question.Any(x => x.SerialNum == model.SerialNum + 1))
                {
                    return(RedirectToAction("AnswerQuestion", new { score, moduleId = model.TestModuleId, serialNum = model.SerialNum + 1 }));
                }
                else
                {
                    TestScore testScore = new TestScore
                    {
                        Score = score,
                        ApplicationStudent = await _userManager.GetUserAsync(User),
                        TestDate           = DateTime.Now,
                        TestModule         = question.TestModule
                    };

                    _context.TestScore.Add(testScore);

                    await _context.SaveChangesAsync();

                    return(RedirectToAction("TestResults", new { id = testScore.Id }));
                }
            }
            return(RedirectToAction("Details", "TestModules", new { id = model.TestModuleId }));
        }
 private void UpdateProfileQuestionAnswersWithoutSave(User aUser, IEnumerable<string> aQuestions, QuestionAnswer aQuestionAnswer)
 {
     foreach (string aQuestion in aQuestions) {
         UserProfileQuestionAnswer myUserProfileQuestion = GetProfileQuesitonAnswerForUser(aUser, aQuestion);
         if (myUserProfileQuestion == null) {
             myUserProfileQuestion = UserProfileQuestionAnswer.CreateUserProfileQuestionAnswer(0, aUser.Id, aQuestion, (int)aQuestionAnswer);
             theEntities.AddToUserProfileQuestionAnswers(myUserProfileQuestion);
         } else {
             myUserProfileQuestion.Answer = (int)aQuestionAnswer;
             theEntities.ApplyCurrentValues(myUserProfileQuestion.EntityKey.EntitySetName, myUserProfileQuestion);
         }
     }
 }
Exemple #39
0
        protected void btnAnswersAdd_Click(object sender, EventArgs e)
        {
            try
            {
                //Save each Answer
                if (txtAnswer1.Text != "")
                {
                    //Add Answer text to database...
                    Answer a1 = new Answer()
                    {
                        AnswerText = txtAnswer1.Text
                    };
                    tdm.Answer.Add(a1);

                    QuestionAnswer qa1 = new QuestionAnswer()
                    {
                        QuestionId    = Convert.ToInt32(ddlQuestions.SelectedValue),
                        Answer        = a1,
                        CorrectAnswer = cbAnswer1.Checked
                    };
                    tdm.QuestionAnswer.Add(qa1);

                    //Add Documentation to file system...
                    //File.Copy(fuAnswer1.FileName, "/Documentation/" + fuAnswer1.FileName);
                    if (fuAnswer1.FileName != "")
                    {
                        fuAnswer1.SaveAs(Request.PhysicalApplicationPath + @"\Documentation\" + fuAnswer1.FileName);
                    }
                }

                if (txtAnswer2.Text != "")
                {
                    Answer a2 = new Answer()
                    {
                        AnswerText = txtAnswer2.Text
                    };
                    tdm.Answer.Add(a2);

                    QuestionAnswer qa2 = new QuestionAnswer()
                    {
                        QuestionId    = Convert.ToInt32(ddlQuestions.SelectedValue),
                        Answer        = a2,
                        CorrectAnswer = cbAnswer2.Checked
                    };
                    tdm.QuestionAnswer.Add(qa2);
                }

                if (txtAnswer3.Text != "")
                {
                    Answer a3 = new Answer()
                    {
                        AnswerText = txtAnswer3.Text
                    };
                    tdm.Answer.Add(a3);

                    QuestionAnswer qa3 = new QuestionAnswer()
                    {
                        QuestionId    = Convert.ToInt32(ddlQuestions.SelectedValue),
                        Answer        = a3,
                        CorrectAnswer = cbAnswer3.Checked
                    };
                    tdm.QuestionAnswer.Add(qa3);
                }
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
            }
            finally
            {
                //Save changes to the database
                tdm.SaveChanges();
            }
        }