IQuestionModelObject IQuestionMapper.CreateQuestion(IQuestion question) { if (question.GetType() == typeof(UrQuestionnaire.Web.Api.Models.OpenEndedQuestion)) { return new UrQustionnaire.Data.OpenEndedQuestion() { Id = ((UrQuestionnaire.Web.Api.Models.OpenEndedQuestion)question).Id, Text = ((UrQuestionnaire.Web.Api.Models.OpenEndedQuestion)question).Text, Description = ((UrQuestionnaire.Web.Api.Models.OpenEndedQuestion)question).Description }; } if (question.GetType() == typeof (UrQuestionnaire.Web.Api.Models.CloseEndedQuestion)) { return new UrQustionnaire.Data.CloseEndedQuestion() { Id = ((UrQuestionnaire.Web.Api.Models.CloseEndedQuestion) question).Id, Text = ((UrQuestionnaire.Web.Api.Models.CloseEndedQuestion) question).Text, Description = ((UrQuestionnaire.Web.Api.Models.CloseEndedQuestion) question).Description, Choices = string.Join("|", ((UrQuestionnaire.Web.Api.Models.CloseEndedQuestion) question).Choices.ToArray()) }; } throw new Exception(string.Format("Unknown question type {0} has no corresponding mapping", question.GetType())); }
public Trainer(IQuestion[] questions, TType trainingType) { _questions = new List<IQuestion>(questions); _trainingType = trainingType; _isFinished = false; _isStarted = false; }
static void Main(string[] args) { IQuestion[] questions = new IQuestion[] { // Intro new CompareBinaryToHex(), new SwapMinMax(), // Chapters new Q01_1(), new Q01_2(), new Q01_3(), new Q01_4(), new Q01_5(), new Q01_6(), new Q01_7(), new Q01_8(), new Q02_1(), new Q02_2(), new Q02_3(), new Q02_4(), new Q02_5(), new Q02_6(), new Q02_7(), new Q03_1_A(), new Q03_1_B(), new Q03_2(), new Q03_3(), new Q03_4(), new Q03_5(), new Q03_6(), new Q03_7(), new Q04_1(), new Q04_2(), new Q04_3(), new Q04_4(), new Q04_5(), new Q04_6(), new Q04_7(), new Q04_8(), new Q04_9(), new Q05_1(), new Q05_2(), new Q07_6(), new Q09_6(), new Q11_1(), new Q11_2(), new Q17_3(), new Q17_4(), new Q17_11(), new Q17_12(), new Q18_1(), new Q18_2(), new Q18_9(), new Q18_10(), new Q18_11() }; foreach (IQuestion q in questions) { Console.WriteLine(string.Format("{0}{1}", Environment.NewLine, Environment.NewLine)); Console.WriteLine(string.Format("// Executing: {0}", q.GetType().ToString())); Console.WriteLine("// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----"); q.Run(); } Console.WriteLine(string.Format("{0}{1}", Environment.NewLine, Environment.NewLine)); Console.WriteLine("Press [Enter] to quit"); Console.ReadLine(); }
public IAnswer AskAnswer(IQuestion question) { var j = 0; var choices = new Dictionary<char,IChoice>(); question.Choices.ForEach(c => choices.Add((char)('a' + j++), c)); var answerChar = '\0'; do { Console.Clear(); Console.WriteLine("Question: {0}", question.QuestionString); foreach (var choice in choices) { Console.WriteLine("{0}. {1}", choice.Key, choice.Value.ChoiceText); } Console.Write("\nAnswer: "); var readLine = Console.ReadLine(); if (readLine == null) continue; if (new[] { "back", "b", "oops", "p", "prev" }.Contains(readLine.ToLower())) { return question.CreateAnswer(Choice.PREVIOUS_ANSWER); } answerChar = readLine[0]; } while (!choices.ContainsKey(answerChar)); return question.CreateAnswer(choices[answerChar]); }
public QuestionInputViewContainer(IQuestion question, View view, SurveyPageAppearance appearance) { view.HorizontalOptions = LayoutOptions.FillAndExpand; var errorLabel = new Label { Style = appearance.QuestionErrorLabelStyle, Text = String.Empty, IsVisible = false, HorizontalOptions = LayoutOptions.FillAndExpand }; question.PropertyChanged += (sender, e) => { if (e.PropertyName == "HasError") { if (question.HasError) { errorLabel.Text = question.ErrorMessage; errorLabel.IsVisible = true; } else { errorLabel.IsVisible = false; } } }; Content = new StackLayout { Orientation = StackOrientation.Vertical, Style = appearance.QuestionInputViewContainerLayoutStyle, Children = { view, errorLabel } }; }
void ShowQuestion (IQuestion question) { ShowViewModel<QuestionsViewModel> (new { questionsJson = JsonConvert.SerializeObject (Questions), index = Questions.IndexOf (question), }); }
private void MakeAnswerBestAnswer(IQuestion question, IAnswer answer) { this.RemoveCurrentAnswerFromDatabase(question, answer); var bestAnswer = new BestAnswer(answer.Id, answer.Body, answer.Author); this.AddBestAnswerToDatabase(question, bestAnswer); }
public void GetoutQuestion(string questionString, IQuestion question) { this.Forum.Output.AppendLine(string.Format(Messages.Header, questionString, question.Id)); this.Forum.Output.AppendLine(string.Format(Messages.Author, question.Author.Username)); this.Forum.Output.AppendLine(string.Format(Messages.Title, questionString, question.Title)); this.Forum.Output.AppendLine(string.Format(Messages.Body, questionString, question.Body)); this.Forum.Output.AppendLine(string.Format(Messages.EquelsSeparator)); }
public Test(TType type, IQuestion[] questions, DateTime timeToStart, string description) { _type = type; _questions=new List<IQuestion>(questions); _isStarted = false; _isFinished = false; _timeToStart = timeToStart; _description = description; }
public Quiz RemoveQuestion(IQuestion question) { if (_questions.Contains(question)) { _questions.Remove(question); } return this; }
public Lesson(string name, string description, IQuestion[] images) { _name = name; _description = description; _images = new List<IQuestion>(images); _isFinished = false; _isStarted = false; _tests=new List<Test>(); }
public void Tagged_ShouldReturnCorrectValue(IQuestion <object> question, string tag) { // arrange // act var actual = question.Tagged(tag); // assert var expected = Questions.CreateTagged(question.Name, (tag, question)); actual.Should().BeEquivalentTo(expected, o => o.RespectingRuntimeTypes()); }
public ExaminationController(IExamination examinationBL, IUser userBL, IExampaper exampaperBL, IDepartment department, IQuestion questionBL, IExamTest examTestBL) { _examinationBL = examinationBL; _userBL = userBL; _exampaperBL = exampaperBL; _departmentBL = department; _questionBL = questionBL; _examTestBL = examTestBL; }
protected virtual void WirePlaceHolders(IQuestion question) { foreach (var p in question.GetPlaceholders()) { var behaviour = p.GetComponent <PlaceholderBehaviour>(); behaviour.Placeholder = new DragNDropPlaceholder(); behaviour.Placeholder.SetQuestion(question); placeholdersList.Add(behaviour); } }
public void TestDesafio6() { QuestionFactory <IQuestion> .Register(6, () => new SixthQuestion("SKY")); IQuestion question = QuestionFactory <IQuestion> .Create(6); var result = question.Execute(); Assert.AreEqual(10, result.ListResultsInt[0], "Válido"); }
public void TestDesafio3() { QuestionFactory <IQuestion> .Register(3, () => new ThirdQuestion()); IQuestion question = QuestionFactory <IQuestion> .Create(3); var result = question.Execute(); Assert.AreEqual(10946, result.ListResultsInt[0], "Válido"); }
public void Add(IQuestion q, IChoice c) { var rec = new AnswerRecord() { Question = q, Choice = c }; _questionsAnswers.Add(rec); NewRecord(rec); }
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; } }
#pragma warning disable CS0618 // Type or member is obsolete public TAnswer AsksForWithAbility <TAnswer, TAbility>(IQuestion <TAnswer, TAbility> question) { var targeted = question as ITargeted; if (question is IQuestion <TAnswer, WebBrowser> webBrowserQuestion && targeted != null) { return(Actor.AsksForWithAbility(new SlowSeleniumQuestion <TAnswer>(webBrowserQuestion, DelayMilliseconds, targeted))); } return(Actor.AsksForWithAbility(question)); }
public BaseQuestion(IQuestion question) { StringId = question.StringId; Title = question.Title; Description = question.Description; Date = question.Date; Answer = question.Answer; QuestionOf = question.QuestionOf; RelatedItem = question.RelatedItem; }
public void NewQuestion(IQuestion question, IModerator moderator) { var viewModel = _questionViewModelFactory.Create(moderator, question); var page = new QuestionPage { BindingContext = viewModel }; _app.MainPage = page; }
public void TestDesafio2() { QuestionFactory <IQuestion> .Register(2, () => new SecondQuestion(new int[] { 1, 2, 3, 4, 5 })); IQuestion question = QuestionFactory <IQuestion> .Create(2); var result = question.Execute(); Assert.AreEqual(55, result.ListResultsInt[0], "Válido"); }
public void CreateATimedQuestionMethodShouldCreateATypeOfQuestion() { var questionText = "Are we testing now the type of the created object?"; var categoryType = CategoryType.Movies; var timeForAnswer = 10; var factory = new Factory(); IQuestion timedQuestion = factory.CreateTimedQuestion(questionText, DifficultyLevel.Hard, categoryType, timeForAnswer); Assert.IsInstanceOfType(timedQuestion, typeof(Question)); }
public void CreateABonusQuestionShouldReturnAQuestionInTheProperCategory() { var questionText = "Who wrote \"The Great Gatsby\"?"; var categoryType = CategoryType.Literature; var pointsMultiplier = 5; var factory = new Factory(); IQuestion bonusQuestion = factory.CreateBonusQuestion(questionText, DifficultyLevel.Hard, categoryType, pointsMultiplier); Assert.AreEqual(categoryType, bonusQuestion.CategoryType); }
public QuestionInfo(IQuestion question) { QuestionId = question.Id; Name = question.Name; Description = question.Description; foreach (var item in question.AnswerForQuestionEntity) { Answers.Add(new AnswerDTO.AnswerDTO(item.Answer)); } }
private static void PackQuestion(IQuestion question, CreateHITRequest request) { var serializer = new XmlSerializer(question.GetType()); using (var sw = new Utf8StringWriter()) { serializer.Serialize(sw, question); request.Question = sw.ToString(); } }
public TestController(IUser userStore, IUserRole userRoleStore, ITest testStore, IQuestion questionStore, IStudentAnswer studentAnswerStore, IToken tokenStore) { _userStore = userStore; _userRoleStore = userRoleStore; _testStore = testStore; _questionStore = questionStore; _studentAnswerStore = studentAnswerStore; _tokenStore = tokenStore; }
public void Select_ShouldReturnCorrectResult(IQuestion <string> question, Func <string, object> selector) { // act var actual = question.Select(selector); // assert var expected = new SelectQuestion <string, object>(question, selector); actual.Should().BeOfType <SelectQuestion <string, object> >(); actual.Should().BeEquivalentTo(expected); }
public frmQuestion() { this.questionBO = this.questionBO ?? new QuestionBO(); this.departmentBO = this.departmentBO ?? new DepartmentBO(); InitializeComponent(); QuestionBO q = new QuestionBO(); gridControl1.DataSource = q.GetDepartmentnameFromDepartmentID(1); }
//Constructor public SurveyBusiness(IUser userDAL, ISurvey surveyDAL, IQuestion questionDAL, ITextAnswers textAnswerDAL, IOptionChoice optionChoiceDAL, IAnswers answerDAL, IInputType inputTypeDAL) { this.userDAL = userDAL; this.surveyDAL = surveyDAL; this.questionDAL = questionDAL; this.textAswersDAL = textAnswerDAL; this.optionChoiceDAL = optionChoiceDAL; this.answerDAL = answerDAL; this.inputTypeDAL = inputTypeDAL; }
public void CreateATimedQuestionShouldReturnAQuestionInTheProperCategory() { var questionText = "So now we are testing the category, right?"; var categoryType = CategoryType.Movies; var timeForAnswer = 12; var factory = new Factory(); IQuestion timedQuestion = factory.CreateTimedQuestion(questionText, DifficultyLevel.Easy, categoryType, timeForAnswer); Assert.AreEqual(categoryType, timedQuestion.CategoryType); }
public void CreateATimedQuestionShouldReturnTheTimedQuestionWithTheProperText() { var questionText = "Are we testing the timed question now?"; var categoryType = CategoryType.Random; var timeForAnswer = 10; var factory = new Factory(); IQuestion timedQuestion = factory.CreateTimedQuestion(questionText, DifficultyLevel.Easy, categoryType, timeForAnswer); Assert.AreEqual("Are we testing the timed question now?", timedQuestion.QuestionText); }
public void CreateABonusQuestionMethodShouldCreateATypeOfQuestion() { var questionText = "Who wrote \"The Great Gatsby\"?"; var categoryType = CategoryType.Literature; var pointsMultiplier = 5; var factory = new Factory(); IQuestion bonusQuestion = factory.CreateBonusQuestion(questionText, DifficultyLevel.Hard, categoryType, pointsMultiplier); Assert.IsInstanceOfType(bonusQuestion, typeof(Question)); }
public void GivenRealPerformanceMonitorShouldInterceptAndLogEntry() { LogFake logFake = new LogFake(); UnityProxy <IQuestion> unityProxy = new UnityProxy <IQuestion>(new PerformanceMonitor(logFake)); IQuestion question = unityProxy.Intercept(new AopUnityFizzBuzzSpike.Questions.FizzBuzz()); question.String(1); logFake.LogEntries.Count.Should().Be(1); }
public void Edit(string id, IQuestion question) { var query = Query.EQ("_id", new ObjectId(id)); var update = Update <Question> .Set(q => q.Text, question.Text) .Set(q => q.ImageUrl, question.ImageUrl) .Set(q => q.ThumbUrl, question.ThumbUrl) .Set(q => q.Choices, question.Choices); _collection.Update(query, update); }
public async Task <int> DeleteAsync(IQuestion question) { try { return(await Repository.DeleteAsync <QuestionEntity>(AutoMapper.Mapper.Map <QuestionEntity>(question))); } catch (Exception ex) { throw ex; } }
/// <summary> /// Creates a new instance of <see cref="WaitUntilQuestionIsAnswered{TAnswer}"/> /// </summary> /// <param name="question">The question to answer</param> /// <param name="isAnswered">A predicate returning wether the answer is satisfying</param> /// <param name="timeout">The duration during which the question must be asked</param> public WaitUntilQuestionIsAnswered( IQuestion <TAnswer> question, Predicate <TAnswer> isAnswered, TimeSpan timeout) { Guard.ForNull(question, nameof(question)); Guard.ForNull(isAnswered, nameof(isAnswered)); _question = question; _isAnswered = isAnswered; _timeout = timeout; }
public async Task<int> UpdateAsync(IQuestion question) { try { return await Repository.UpdateAsync<QuestionEntity>(AutoMapper.Mapper.Map<QuestionEntity>(question)); } catch (Exception ex) { throw ex; } }
/// <summary> /// Returns all question data in the database in the form of a list of objects /// </summary> /// /// <returns>The list of question objects</returns> public void PopulateListFromTable() { if (Database.TableExists(Database.TableName)) { for (int i = 1; i <= Database.RetrieveNumberOfRowsInTable(); i++) { IQuestion questionToAdd = SetRowToObject(i); QuestionPackQuestions.Add(questionToAdd); } } }
/// <summary> /// Verifies the answer of the given question using a NUnit constraint /// </summary> /// <typeparam name="T">The answer type</typeparam> /// /// <param name="verifies">The <see cref="IVerifies"/> instance</param> /// <param name="question">The question to verify the answer from</param> /// <param name="constraint">A NUnit constraint that encapsulate the expected result</param> /// <param name="message">The message to return when the assertion fails</param> /// <param name="args">Arguments to add to the message</param> /// <returns>The answer, when the verification succeeds</returns> public static T Then <T>( this IVerifies verifies, IQuestion <T> question, IResolveConstraint constraint, string message, params object[] args) { ValidateArguments(verifies, question, constraint, message, args); return(verifies.Then(question, answer => Assert.That(answer, constraint, message, args))); }
public void RemoveQuestion(IQuestion question) { Validator.CheckIfNull(question, string.Format(GlobalConstants.ObjectCannotBeNull, "Question")); if (!this.quizzardQuestions.Contains(question)) { throw new ArgumentException("Question not found!"); } quizzardQuestions.Remove(question); }
protected override void GenerateAndStoreAnswerSubmissionsForQuestion(IQuestion question) { EditableAnswerSubmission newAnswerSubmission = new EditableAnswerSubmission { Question = question, Answer = null, State = AnswerSubmissionState.NO_ANSWER, ValidatedByUser = false }; _answerSubmissions.Add(newAnswerSubmission); }
private void GetNextQuestion() { //Get next translation currentQuestion = session.Next(); txtAnswer.Text = String.Empty; if (currentQuestion != null) { lblQuestion.Text = currentQuestion.Question; return; } this.Close(); }
public Quiz AddQuestion(IQuestion question) { if (question == null) { throw new ArgumentException("Question must not be null"); } if (_questions.Contains(question)) { throw new QuizException(); } _questions.Add(question); return this; }
private static void Test(IQuestion qs) { Console.WriteLine(qs.Question); var q = qs.Question; q = q.Replace("pluss", "+"). Replace("minus", "-"). Replace("ganger", "*"). Replace("delt på", "/"). Replace("Hva er", ""); Console.WriteLine(q); var context = new ExpressionContext(); context.Imports.AddType(typeof (Math)); var eDynamic = context.CompileDynamic(q); var res = eDynamic.Evaluate(); Assert.IsTrue(qs.Run("" + res)); }
private static void OnClientResponse(SPWeb web, int teamId, IQuestion question, DownloadStringCompletedEventArgs args) { var team = web.Lists["Teams"].GetItemById(teamId); int points; string result; if (args.Error != null || args.Cancelled) { if (args.Error != null) Log.InfoFormat("Request failed for team {0}! {1} - {2}", team.Title, args.Error.Message, args.Error.InnerException); else Log.InfoFormat("Request cancelled for team {0}", team.Title); points = -(int) (question.Level * 1.5); result = "Server error"; } else { result = args.Result; Log.DebugFormat("Got result {0}", result); if (string.IsNullOrEmpty(result)) points = -(question.Level/2); else points = question.Run(result) ? question.Level : -question.Level; Log.DebugFormat("Points : {0}", points); } var stats = web.Lists["Stats"]; var statsItem = stats.AddItem(); statsItem["Team"] = team; statsItem["Author"] = team["Author"]; statsItem["Time"] = DateTime.Now; statsItem["Question"] = question.Question; statsItem["Answer"] = result; statsItem["Points"] = points; statsItem["Level"] = question.Level; statsItem.Update(); int currentScore; if (!int.TryParse("" + team["Score"], out currentScore)) { Log.WarnFormat("Unable to format {0} to int for teamscore of team {1}", team["Score"], team.Title); currentScore = 0; } currentScore += points; team["Score"] = currentScore; team.Update(); }
public static void Request(SPListItem team, IQuestion question, DownloadStringCompletedEventHandler callback) { var host = "" + team["Host"]; using (var client = new WebClient()) { var query = string.Format("q={0}", question.Question); var url = new UriBuilder(host) {Query = query}.Uri; try { Log.DebugFormat("Sending request to {0}", url); client.DownloadStringAsync(url); client.DownloadStringCompleted += callback; } catch (Exception e) { Log.Error("Request to team " + team.Title, e); } } }
public static string PrintQuestion(IQuestion question) { StringBuilder sb = new StringBuilder(); sb.AppendFormat("[ Question ID: {0} ]", question.Id) .AppendLine() .AppendFormat("Posted by: {0}", question.Author.Username) .AppendLine() .AppendFormat("Question Title: {0}", question.Title) .AppendLine() .AppendFormat("Question Body: {0}", question.Body) .AppendLine() .AppendLine("===================="); if (question.Answers.Count > 0) { sb.AppendLine("Answers:"); var bestAnswer = question as Question; if (bestAnswer != null && bestAnswer.BestAnswerId != 0) { var answer = bestAnswer.Answers.First(s => s.Id == bestAnswer.BestAnswerId); sb.AppendLine("********************") .AppendFormat("[ Answer ID: {0} ]", answer.Id) .AppendLine() .AppendFormat("Posted by: {0}", answer.Author.Username) .AppendLine() .AppendFormat("Answer Body: {0}", answer.Body) .AppendLine() .AppendLine("--------------------") .AppendLine("********************"); } var otherAnswers = question.Answers.Where(s => s.Id != bestAnswer.BestAnswerId); foreach (var otherAnswer in otherAnswers.OrderBy(s => s.Id)) { sb.AppendLine(PrintAnswer(otherAnswer)); } } else { sb.AppendLine("No answers"); } return sb.ToString(); }
public QuestionViewModel (IQuestion question, int index) : this () { ID = question.ID; Text = question.Text; Answer = question.Answer; PassCriteria = question.PassCriteria; Comment = question.Comment; Author = question.Author; Source = question.Source; Index = index; HasPicture = !string.IsNullOrEmpty (question.Picture); Picture = "http://db.chgk.info/images/db/" + question.Picture; Gearbox = question.Gearbox; HasComments = !string.IsNullOrEmpty (Comment); HasAuthor = !string.IsNullOrEmpty (Author); HasSource = !string.IsNullOrEmpty (Source); HasPassCriteria = !string.IsNullOrEmpty (PassCriteria); HasGearbox = !string.IsNullOrEmpty(Gearbox); }
public async Task<int> UpdateQuestionAsync(IQuestion question, IAnswerChoice[] choices) { if (choices.Sum(c => c.Points) == 0) { throw new ArgumentException("Points"); } var existingQuestion = await questionRepository.GetQuestionWithChoicesAndPicuresAsync(question.Id); var collectionForInsert = choices.Where(choice => existingQuestion.AnswerChoices.SingleOrDefault(c => c.Id == choice.Id) == null).ToArray(); var collectionForUpdate = choices.Where(choice => existingQuestion.AnswerChoices.SingleOrDefault(c => c.Id == choice.Id) != null).ToArray(); var collectionForDelete = existingQuestion.AnswerChoices.Where(choice => choices.SingleOrDefault(c => c.Id == choice.Id) == null).Select(c => c.Id).ToArray(); var unitOfWork = questionRepository.GetUnitOfWork(); await this.AddChoiceRangeForDeleteAsync(unitOfWork, collectionForDelete); await this.AddChoiceRangeForUpdateAsync(unitOfWork, collectionForUpdate); await this.AddChoiceRangeForInsertAsync(unitOfWork, question.Id, collectionForInsert); await questionRepository.AddForUpdateAsync(unitOfWork, question); return await unitOfWork.CommitAsync(); }
public async Task<int> InsertAsync(IQuestion question, IAnswerChoice[] answerChoices, string examId) { var questionId = Guid.NewGuid().ToString(); question.Id = questionId; if (String.IsNullOrEmpty(examId)) { throw new ArgumentException("Exam"); } var correctAnswers = 0; foreach (var choice in answerChoices) { if (choice.Points > 0) { correctAnswers++; } } if (correctAnswers == 0) { throw new ArgumentException("AnswerChoice"); } var examQuestion = new ExamQuestion(); examQuestion.ExamId = examId; examQuestion.QuestionId = questionId; examQuestion.Id = Guid.NewGuid().ToString(); examQuestion.Number = await examRepository.GetNumberOfQuestionsAsync(examQuestion.ExamId) + 1; var unitOfWork = questionRepository.GetUnitOfWork(); await questionRepository.AddForInsertAsync(unitOfWork, question); await examRepository.AddExamQuestionForInsert(unitOfWork, examQuestion); foreach(var choice in answerChoices) { choice.QuestionId = questionId; choice.Id = Guid.NewGuid().ToString(); await answerChoiceRepository.AddForInsertAsync(unitOfWork, choice); } return await unitOfWork.CommitAsync(); }
/// <summary> /// Renders the vertical option buttons. /// </summary> /// <param name="question">The question.</param> /// <param name="style">The style.</param> /// <returns>A control containing the question and answer choice(s).</returns> private static Control RenderVerticalOptionButtons(IQuestion question, string style) { var rbl = new RadioButtonList { RepeatColumns = 1, RepeatDirection = RepeatDirection.Vertical, RepeatLayout = RepeatLayout.Table, ID = question.RelationshipKey.ToString() }; rbl.Attributes.Add("RelationshipKey", question.RelationshipKey.ToString()); if (string.IsNullOrEmpty(style)) { rbl.CssClass = CssClassAnswerVertical; } else { rbl.Attributes.Add("style", style); } foreach (IAnswer answer in question.GetAnswers()) { //// 1 to skip the blank entry var li = new ListItem(answer.Text, answer.Text); li.Attributes.Add("RelationshipKey", answer.RelationshipKey.ToString()); rbl.Items.Add(li); // preselect answer, if needed if (question.Responses != null) { if (string.Equals(answer.Text, question.FindResponse(answer).AnswerValue, StringComparison.InvariantCultureIgnoreCase)) { li.Selected = true; } } } return rbl; }
/// <summary> /// Renders the small input field. /// </summary> /// <param name="question">The question.</param> /// <param name="style">The style.</param> /// <returns>A control containing the question and input field.</returns> private static Control RenderSmallInputField(IQuestion question, string style) { var tb = new TextBox { TextMode = TextBoxMode.SingleLine, MaxLength = 256 }; if (string.IsNullOrEmpty(style)) { tb.CssClass = CssClassAnswerVertical; } else { tb.Attributes.Add("style", style); } // make these a designer variable? tb.Attributes.Add("RelationshipKey", question.RelationshipKey.ToString()); tb.ID = question.RelationshipKey.ToString(); // pre-select if needed if (question.Responses != null && question.Responses.Count == 1) { tb.Text = question.Responses[0].AnswerValue; } return tb; }
/// <summary> /// Renders the large text input field. /// </summary> /// <param name="question">The question.</param> /// <param name="style">The style.</param> /// <returns>A control containing the question and answer choice(s).</returns> private static Control RenderLargeTextInputField(IQuestion question, string style) { var tb = new TextBox { TextMode = TextBoxMode.MultiLine, MaxLength = 256, Columns = 25 }; if (string.IsNullOrEmpty(style)) { tb.CssClass = CssClassAnswerVertical; } else { tb.Attributes.Add("style", style); } tb.Attributes.Add("RelationshipKey", question.RelationshipKey.ToString()); tb.ID = question.RelationshipKey.ToString(); // pre-select if needed if (question.Responses != null && question.Responses.Count == 1) { tb.Text = question.Responses[0].AnswerValue; } return tb; }
/// <summary> /// Renders the drop down list. /// </summary> /// <param name="question">The question.</param> /// <param name="style">The style.</param> /// <param name="defaultOptionText">The text for the default option (signifying no choice).</param> /// <returns> /// A control containing the question and answer choice(s). /// </returns> private static Control RenderDropDownList(IQuestion question, string style, string defaultOptionText) { var ddl = new DropDownList(); if (string.IsNullOrEmpty(style)) { ddl.CssClass = CssClassAnswerVertical; } else { ddl.Attributes.Add("style", style); } ddl.Items.Add(new ListItem(defaultOptionText, string.Empty)); ddl.Attributes.Add("RelationshipKey", question.RelationshipKey.ToString()); ddl.ID = question.RelationshipKey.ToString(); foreach (IAnswer answer in question.GetAnswers()) { var li = new ListItem(answer.Text, answer.Text); li.Attributes.Add("RelationshipKey", answer.RelationshipKey.ToString()); ddl.Items.Add(li); // preselect the answer, if needed if (question.Responses != null) { if (string.Equals(question.FindResponse(answer).AnswerValue, answer.Text)) { li.Selected = true; } } } return ddl; }
/// <summary> /// Renders the check box list. /// </summary> /// <param name="question">The question.</param> /// <param name="readOnly">if set to <c>true</c> [read only].</param> /// <param name="style">The style.</param> /// <param name="limitReachedErrorFormat">The <see cref="string.Format(System.IFormatProvider,string,object[])"/>-style message for when the maximum number of options has been exceeded</param> /// <returns>A control containing the question and answer choice(s).</returns> private static Control RenderCheckBoxList(IQuestion question, bool readOnly, string style, string limitReachedErrorFormat) { var container = new HtmlGenericControl("SPAN") { ID = "CheckBoxSpan" + question.QuestionId }; if (string.IsNullOrEmpty(style)) { container.Attributes["class"] = CssClassAnswerVertical; } else { container.Attributes.Add("style", style); } if (question.SelectionLimit > 0) { // TODO: Localize limit reached text var limitDiv = new HtmlGenericControl("DIV"); limitDiv.Attributes["class"] = "limit-reached"; limitDiv.InnerText = string.Format(CultureInfo.CurrentCulture, limitReachedErrorFormat, question.SelectionLimit); limitDiv.Style.Add("display", "none"); container.Controls.Add(limitDiv); } foreach (IAnswer answer in question.GetAnswers()) { var cb = new CheckBox(); cb.Attributes.Add("RelationshipKey", answer.RelationshipKey.ToString()); cb.ID = answer.RelationshipKey.ToString(); cb.Enabled = !readOnly; cb.Text = answer.FormattedText; container.Controls.Add(cb); // preselect answer, if needed if (question.Responses != null) { if (string.Equals(question.FindResponse(answer).AnswerValue, bool.TrueString, StringComparison.InvariantCultureIgnoreCase)) { cb.Checked = true; } } if (question.SelectionLimit > 0) { cb.Attributes.Add(HtmlTextWriterAttribute.Onclick.ToString(), "return CheckSelectedCount(this);"); } } return container; }
/// <summary> /// Create a web control for the survey renderer. /// </summary> /// <param name="question">The question.</param> /// <param name="readOnly">if set to <c>true</c> [read only].</param> /// <param name="style">The style.</param> /// <param name="localizer">Localizes text.</param> /// <returns> /// A Div with controls in it. /// </returns> public static Control CreateWebControl(IQuestion question, bool readOnly, string style, ILocalizer localizer) { WebControl control; switch (question.ControlType) { case ControlType.DropDownChoices: control = (WebControl)RenderDropDownList(question, style, localizer.Localize("DefaultDropDownOption.Text")); break; case ControlType.HorizontalOptionButtons: control = (WebControl)RenderHorizontalOptionButtons(question, style); break; case ControlType.VerticalOptionButtons: control = (WebControl)RenderVerticalOptionButtons(question, style); break; case ControlType.LargeTextInputField: control = (WebControl)RenderLargeTextInputField(question, style); break; case ControlType.SmallTextInputField: control = (WebControl)RenderSmallInputField(question, style); break; case ControlType.Checkbox: return RenderCheckBoxList(question, readOnly, style, localizer.Localize("CheckBoxLimitExceeded.Format")); default: control = new Label { Text = "No control info found for ControlType: " + question.ControlType }; break; } control.Enabled = !readOnly; return control; }
// ------------------------------------------------------------------------------------- /// <summary> /// Add QuestionControl as child control to the TemplateControl. /// Controls appeared by layout specified by IQestion.QuestionLayout property /// </summary> /// <param name="question">Question to add</param> /// <returns>Added question control</returns> // ------------------------------------------------------------------------------------- private IQuestionControl CreateQuestionControl(IQuestion question) { Panel itemPanel = new Panel(); m_QuestionPanel.Controls.Add(itemPanel); ToolTip toolTip = new ToolTip(); toolTip.AutoPopDelay = 5000; toolTip.InitialDelay = 1000; toolTip.ReshowDelay = 500; toolTip.ShowAlways = true; toolTip.SetToolTip(itemPanel, question.QuestionDescription); // --- Add question text QuestionLabelControl questionLabel = new QuestionLabelControl(); questionLabel.Text = question.Question; questionLabel.AutoSize = true; itemPanel.Controls.Add(questionLabel); toolTip.SetToolTip(questionLabel, question.QuestionDescription); // --- Create control by Layout QuestionLayout layout = question.QuestionLayout; IQuestionControl controlToAdd = null; switch (layout) { case QuestionLayout.Check: controlToAdd = new QuestionCheckControl(); break; case QuestionLayout.Combo: controlToAdd = new QuestionListControl(); break; case QuestionLayout.Radio: controlToAdd = new QuestionRadioControl(); break; case QuestionLayout.Text: controlToAdd = new QuestionTextControl(); break; case QuestionLayout.MultiLineText: controlToAdd = new QuestionTextControl(); break; } ((Control) controlToAdd).Name = "IQuestionControl" + question.QuestionInternalID; ((Control) controlToAdd).Tag = questionLabel; controlToAdd.IQuestion = (IQuestion) question; controlToAdd.State = State; itemPanel.Controls.Add((Control) controlToAdd); controlToAdd.DisplayControl(); return controlToAdd; }
private void Add(IQuestion newQuestion) { Questions.Add(newQuestion); }
public void ReadQuestion(IQuestion question) { Console.Clear(); Console.WriteLine("Question {0}:\n{1}", 0, question.QuestionString); Console.WriteLine(); }