Inheritance: ExtensibleDataObject
Exemplo n.º 1
0
        public void deleteQuestion(Question question)
        {
            logger.Debug("deleteQuestion()");

            MysqlConnector mysql = new MysqlConnector(CurrentUserInfo.USERNAME,
             CurrentUserInfo.PASSWORD,
             CurrentUserInfo.HOSTNAME,
             CurrentUserInfo.PORT,
             CurrentUserInfo.DATABASE);

            string query = "delete from question where id = " + question.Id + ";";
            string answersIDs = "";
            foreach (Answer answer in question.AnswerList)
                answersIDs += answer.Id.ToString() + ",";

            if (!String.IsNullOrEmpty(answersIDs))
                answersIDs = answersIDs.Substring(0, answersIDs.Length - 1);

            mysql.initializeConnection();
            mysql.openMysqlConnection();

            using (MySqlCommand cmd = new MySqlCommand(query, mysql.MysqlConnection))
                cmd.ExecuteNonQuery();

            query = "delete from answer where id in (" + answersIDs + ");";

            if (!String.IsNullOrEmpty(answersIDs))
                using (MySqlCommand cmd = new MySqlCommand(query, mysql.MysqlConnection))
                    cmd.ExecuteNonQuery();

            mysql.closeMysqlConnection();

            logger.Info("Question With ID " + question.Id + " Deleted");
        }
Exemplo n.º 2
0
        public IHttpActionResult Post(JObject data)
        {
            dynamic json = data;
            var result = Captcha.Check((string)json.Captcha);

            Question question = new Question()
            {
                Author = json.Author,
                Email = json.Email,
                Message = json.Message,
                Topic = json.Topic
            };

            if (question.Author == "" || question.Email == "" || question.Message == "" || question.Topic == "")
            {
                return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Заполните обязательные поля!"));
            }
            else
            {
                if (result == true)
                {
                    Emailer.QuestionNotificate(question);
                    return Ok("Спасибо! Ваш запрос успешно отправлен.");
                }
                else
                {
                    return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Заполните капчу!"));
                }

            }
        }
Exemplo n.º 3
0
 public Question GetNextQuestion(Question prevQuestion, Answer prevAnswer)
 {
     int qId = logic.GetQuestionId(prevQuestion, prevAnswer);
     Question q = new Question();
     q.Id = qId;
     return q;
 }
Exemplo n.º 4
0
        public static FireAnswer Create(
            FireRiskAssessmentChecklist fireRiskAssessmentChecklist,
            Question question,
            YesNoNotApplicableEnum? yesNoNotApplicableResponse,
            string additionalInfo,
            UserForAuditing user)
        {
            var fireAnswer = new FireAnswer
                                 {
                                     FireRiskAssessmentChecklist = fireRiskAssessmentChecklist,
                                     Question = question,
                                     YesNoNotApplicableResponse = yesNoNotApplicableResponse,
                                     AdditionalInfo = additionalInfo,
                                     CreatedOn = DateTime.Now,
                                     CreatedBy = user
                                 };

            if (yesNoNotApplicableResponse == YesNoNotApplicableEnum.No)
            {
                var significantFinding = SignificantFinding.Create(fireAnswer, user);
                fireAnswer.SignificantFinding = significantFinding;
            }

            return fireAnswer;
        }
 public Answer GetAnswer(Question question)
 {
     if(question.ContainsTokensInFollowingOrder(DateOrTimeToken, CityOrTimezoneToken, CityOrTimezoneToken))
         return GetAnswerToWhenTimeInKnownCityWhatTimeInUnknownCity(question);
     else
         return GetAnswerToWhatTimeInUnknownCityWhenTimeInKnownCity(question);
 }
Exemplo n.º 6
0
        public ActionResult AskQuestion(string question, string data)
        {
            // UserCategory category = _dbContext.UserCategories.Find(categoryId);
            //  UserCategoryViewModel userCategoryViewModel = Mapper.Map<UserCategoryViewModel>(category);
            // category.Id = categoryId;

            if (!User.Identity.IsAuthenticated)
            {
                return Json(new { success = false });
            }
            else
            {
                Question userQuestion = new Question();
                var deserialiseList = JsonConvert.DeserializeObject<List<UserCategoryViewModel>>(data);
                var user = _dbContext.Users.Where(u => u.Email == User.Identity.Name).FirstOrDefault();
                if (user != null)
                {
                    userQuestion.Id = Guid.NewGuid();
                    userQuestion.UserId = user.Id;
                    userQuestion.UserQuestion = question;
                    _dbContext.Questions.Add(userQuestion);

                    foreach (var category in deserialiseList)
                    {
                        UserCategory retriveCategory = _dbContext.UserCategories.Find(category.data);
                        userQuestion.UserCategories.Add(retriveCategory);
                    }
                    _dbContext.SaveChanges();
                    return Json(new { success = true });
                }
            }

            return View();
        }
Exemplo n.º 7
0
        public void Execute(ResultExecutionContext context)
        {
            var questionDialog = context.ServiceLocator.GetInstance<IQuestionDialog>();
            var windowManager = context.ServiceLocator.GetInstance<IWindowManager>();

            var question = new Question(
                Text,
                _possibleAnswers
                );

            questionDialog.Setup(
                Caption,
                new[] {question}
                );

            questionDialog.Deactivated += (s,e) => {
                if (!e.WasClosed)
                    return;

                if(_handleResult != null)
                    _handleResult(question.Answer);
                else if(question.Answer == Answer.No || question.Answer == Answer.Cancel)
                {
                    Completed(this, new ResultCompletionEventArgs {WasCancelled = true});
                    return;
                }

                Completed(this, new ResultCompletionEventArgs());
            };

            windowManager.ShowDialog(questionDialog, null);
        }
Exemplo n.º 8
0
        protected IList<Question> GetQuestions(string questionSuffix, int firstQuestion = 1, int lastQuestion = 1)
        {
            string qSearchFlag = firstQuestion + questionSuffix;
            string[] rawLines = _rawtxt.Split('\n');

            Dictionary<int, Question> lineToQ = new Dictionary<int, Question>();

            for (int i = 0; i < rawLines.Length; i++)
            {
                if (rawLines[i].Contains(qSearchFlag))
                {
                    Question tmpQuestion = new Question() { QuestionNumber = firstQuestion };
                    lineToQ[i] = tmpQuestion;

                    rawLines[i] = rawLines[i].Replace(qSearchFlag, "");
                    firstQuestion++;
                }
            }

            foreach (int key in lineToQ.Keys)
            {
                for (int i = key; i < rawLines.Length; i++)
                {
                    if (ContainsAnswers(rawLines[i]))
                        break;
                    else
                        lineToQ[key].QText += rawLines[i];
                }
            }

            return lineToQ.Values.ToList();
        }
Exemplo n.º 9
0
 public static List<Question> GetQuestionaire(int AssessmentID, int userid)
 {
     List<Question> lstQuestions = new List<Question>();
     Question Obj = new Question(1);
     lstQuestions = Obj.GetAssessmentQuestions(AssessmentID, 1);
     return lstQuestions;
 }
        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            bool error = false;
            string msg = "";
            if (String.IsNullOrWhiteSpace(this.textBoxQuestion.Text))
            {
                error = true;
                msg += "A question is required.  ";
            }
            if (String.IsNullOrWhiteSpace(this.textBoxAnswer.Text))
            {
                error = true;
                msg += "A answer is required.";
            }
            if (error)
            {
                MessageBox.Show(msg, "Missing Required Fields", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            this.Canceled = false;
            this.Question =  new Question(this.textBoxQuestion.Text, this.textBoxAnswer.Text);

            this.Close();
        }
 public Answer GetAnswer(Question question)
 {
     var cityToken = question.GetToken<CityToken>();
     var dateToken = question.GetToken<DateToken>();
     int? year = null;
     if (dateToken != null) year = dateToken.Year;
     DaylightSavingInformation daylightSavingInfo;
     if (year.HasValue)
     {
         var firstDateInTheYear = new LocalDateTime(year.Value, 1, 1, 0, 0).InZone(DateTimeZoneProviders.Tzdb[cityToken.City.Timezone], Resolvers.LenientResolver);
         var firstZoneIntervalInTheYear = firstDateInTheYear.GetZoneInterval();
         if (firstZoneIntervalInTheYear.IsoLocalEnd.Year > 10000) {
             daylightSavingInfo = DaylightSavingInformation.CreateWithNoDaylightSavings();
         }
         else
         {
             var firstDateInTheNextZoneInterval = firstDateInTheYear.Plus(firstZoneIntervalInTheYear.Duration).Plus(Duration.FromMilliseconds(1));
             daylightSavingInfo = GetDaylightSavingInfo(firstDateInTheNextZoneInterval);
         }
     }
     else
     {
         daylightSavingInfo = GetDaylightSavingInfo(cityToken.GetCurrentTime());
     }
     var answerText = GetFormattedDaylightSavingInfo(daylightSavingInfo, cityToken.City);
     return new Answer(question, true, true, answerText);
 }
 internal void FillContents(Question question)
 {
     Question = question;
     QuestionContents = question.QuestionContents;
     QuestionData = question.QuestionData;
     Index = 1;
 }
Exemplo n.º 13
0
 public Question GetNextQuestion(Test test, Question prevQuestion, ITestLogic logic)
 {
     this.logic = logic;
     int qId = logic.GetQuestionId(test, prevQuestion, uow);
     Question q = uow.Questions.GetById(qId);
     return q;
 }
        public void TokenizeTheQuestion(Question question)
        {
            var matches = Regex.Matches(question.QuestionText, @"(^|\s)(in|at)\s(the\s)?", RegexOptions.IgnoreCase);

            foreach (Match match in matches)
            {
                Group group = match.Groups[0];
                var startPosition = (group.Index + group.Length );
                var cityName = question.QuestionText.Substring(startPosition);
                var endPosition = question.QuestionText.Length;

                var possibleEarlierTerminations = Regex.Matches(cityName, @"(^|\s)(when|what('?s?)|\d|(on|in|at|a|right|now|if|then|\?)(\s|$))", RegexOptions.IgnoreCase);
                if(possibleEarlierTerminations.Count > 0)
                {
                    Group terminationGroup = GetEarlierOccurrenceOfGroup(possibleEarlierTerminations);
                    endPosition = startPosition + terminationGroup.Index;
                }

                cityName = question.QuestionText.Substring(startPosition, endPosition - startPosition);
                if(cityName.Replace(" ","").Length == 0) continue;

                var tokenResult = new CityToken(cityName, startPosition);
                question.AddToken(tokenResult);
            }
        }
        public void EditQuestion(Question question)
        {
            using (SqlConnection conn = CreateConnection())
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("appSchema.usp_EditQuestion", conn);
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("@QuestionID", SqlDbType.Int, 4).Value = question.QuestionID;
                    cmd.Parameters.Add("@Question", SqlDbType.VarChar, 100).Value = question.QuestionTitle;
                    cmd.Parameters.Add("@AnswerOption1", SqlDbType.VarChar, 50).Value = question.AnswerOption1;
                    cmd.Parameters.Add("@AnswerOption2", SqlDbType.VarChar, 50).Value = question.AnswerOption2;
                    cmd.Parameters.Add("@AnswerOption3", SqlDbType.VarChar, 50).Value = question.AnswerOption3;
                    cmd.Parameters.Add("@AnswerOption4", SqlDbType.VarChar, 50).Value = question.AnswerOption4;
                    cmd.Parameters.Add("@CorrectAnswer", SqlDbType.VarChar, 50).Value = question.CorrectAnswer;

                    conn.Open();

                    cmd.ExecuteNonQuery();
                }
                catch
                {
                    throw new ApplicationException("An error occured in the data access layer.");
                }
            }
        }
 internal void FillContents(Question question, QuestionContents contents, QuestionData data, int idx)
 {
     Question = question;
     QuestionContents = contents;
     QuestionData = data;
     Index = idx;
 }
        public void Given_employee_is_assignee_then__dont_return__task_due_in_2days()
        {
            //GIVEN

            var employee = new Employee() { Id = Guid.NewGuid(), NotificationType = NotificationType.Daily };
            var furthcontrolmersuretasks = new FireRiskAssessmentFurtherControlMeasureTask() { TaskAssignedTo = employee, TaskStatus = TaskStatus.Outstanding, TaskCompletionDueDate = DateTime.Now.AddDays(2) };
            var significantFinding = new SignificantFinding() { };
            significantFinding.FurtherControlMeasureTasks.Add(furthcontrolmersuretasks);
            furthcontrolmersuretasks.SignificantFinding = significantFinding;
            var riskAssessement = FireRiskAssessment.Create("this is the title", "the ref", 1312, null, new UserForAuditing { Id = Guid.NewGuid() });

            var user = new UserForAuditing();
            var fireRiskAssessmentChecklist = riskAssessement.FireRiskAssessmentChecklists[0];
            var question = new Question();

            var fireAnswer = FireAnswer.Create(fireRiskAssessmentChecklist, question, YesNoNotApplicableEnum.No, "Additional Info", user);
            fireAnswer.SignificantFinding = significantFinding;
            significantFinding.FireAnswer = fireAnswer;

            riskAssessement.FireRiskAssessmentChecklists[0].Answers = new List<FireAnswer>() { fireAnswer };

            _fireRiskAssessments.Add(riskAssessement);

            var target =
                new GetDueFireRiskAssessmentFurtherControlMeasureTasksForEmployeeQuery(
                    _queryableWrapper.Object);

            //WHEN
            var result = target.Execute(employee.Id, null);

            //THEN
            Assert.That(result.Count, Is.EqualTo(0));

        }
 public QuestionInQuestionnaireManagementContainer(ProgressingQuestionnaireQuestion question, Question questionLevel, Visibility showLevelHeader)
     : this()
 {
     this.QuestionnaireQuestion = question;
     this.QuestionLevel = questionLevel;
     this.ShowLevelHeader = showLevelHeader;
 }
Exemplo n.º 19
0
        public void LazyTrueloadTest()
        {
            Question question;
            using (var repo = RepositoryContext.GetRepository())
            {
                question = new Question() { Name = "question1123", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now };

                var addAnswer1 = new Answer() { Name = "answer1", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now, Question = question };
                var addAnswer2 = new Answer() { Name = "answer2", CreatedOn = DateTime.Now, UpdatedOn = DateTime.Now, Question = question };
                question.Answers.Add(addAnswer1);
                question.Answers.Add(addAnswer2);

                repo.Add(question);

                repo.SaveChanges();
            }

            using (var repo = RepositoryContext.GetRepository())
            {
                //SELECT * FROM [Question]
                var question1 = repo.GetAll<Question>().FirstOrDefault();
                //SELECT * FROM [Answer] answers0_ WHERE answers0_.Question_ID='59B9C112-2A62-4E41-8220-7A518D829449';
                var count = question1.Answers.Count;
                var beforeLoad = question1.GetAnswersSet();
                //Assert.IsTrue(beforeLoad == null || beforeLoad.Count == 0, "组合子实体被立即加载!");
                //Assert.AreEqual(question.Answers.Count, 0);
                var afterLoad = question1.Answers;
                Assert.IsTrue(beforeLoad != null && beforeLoad.Count > 0, "组合子实体未被加载出来!");
            }
        }
Exemplo n.º 20
0
 public Quiz createSimpleQuiz(String question, String[] answers, int[] correctAnswers)
 {
     string tmp = question;
     string[] answ = answers;
     Question tmpQuestion = new Question();
     tmpQuestion.Value = tmp;
     tmpQuestion.ID = 0;
     tmpQuestion.Type = QuestionType.ONLY_TEXT;
     writeQuestion(tmpQuestion);
     Quiz tmpQuiz = new Quiz();
     tmpQuiz.ID = 0;
     tmpQuiz.LevelID = 0;
     tmpQuiz.QuestionID = 0;
     tmpQuiz.QuestionType = QuestionType.ONLY_TEXT;
     tmpQuiz.TipType = TipType.ONLY_TEXT;
     tmpQuiz.AnswerType = AnswerType.ONLY_TEXT;
     int tmpId = 0;
     foreach (string tmpString in answ)
     {
         tmpQuiz.Answers.Add(tmpId);
         Answer answer = new Answer(tmpId, tmpString, AnswerType.ONLY_TEXT);
         writeAnswer(answer);
         tmpId++;
     }
     foreach (int tmpC in correctAnswers)
     {
         tmpQuiz.CorrectAnswers.Add(tmpC);
     }
     writeQuiz(tmpQuiz);
     return tmpQuiz;
 }
        private IList<Token> GetHyphenAndSlashFormattedDates(Question question)
        {
            var tokens = new List<Token>();
            var matches = Regex.Matches(question.QuestionText, @"(?<first_number>\d{1,2})(-|/)(?<second_number>\d{1,2})(-|/)(?<year>\d{2,4})", RegexOptions.IgnoreCase);
            foreach (Match match in matches)
            {
                Group group = match.Groups[0];
                var yearMatch = match.Groups["year"];
                var firstNumberMatch = match.Groups["first_number"];
                var secondNumberMatch = match.Groups["second_number"];

                int? year = int.Parse(yearMatch.Value);
                var firstNumber = int.Parse(firstNumberMatch.Value);
                var secondNumber = int.Parse(secondNumberMatch.Value);
                int day = secondNumber;
                int month = firstNumber;
                if(firstNumber > 12 && secondNumber <= 12){
                    day = firstNumber;
                    month = secondNumber;
                }
                year = MakeYearInThisCenturyIfOnly2Digits(year);
                var tokenResult = new DateToken(group.Value, yearMatch.Index, day, month, year);
                tokens.Add(tokenResult);
            }
            return tokens;
        }
Exemplo n.º 22
0
 /// <summary>
 /// Construtor for Answer question
 /// </summary>
 /// <param name="referencedQuestion">Question that was asked</param>
 /// <param name="player">player who answered</param>
 /// <param name="answer">answer given to that question</param>
 /// <param name="_turnAnswered"> turn question was answered</param>
 public AnsweredQuestion(Question referencedQuestion, Player player, string answer, int turnanswered)
 {
     _question = referencedQuestion;
     _player = player;
     _answer = answer;
     this._turnAnswered = turnanswered;
 }
Exemplo n.º 23
0
        /// <summary>
        /// Answers the question with the score provided. Also saves the question.
        /// </summary>
        /// <param name="question"></param>
        /// <param name="score"></param>
        public static void AnswerQuestion(Question question, int score)
        {
            // Calculate the dates
            question.AskCount++;
            question.ResponseQuality = score;
            SetEasinessFactor(question);
            SetInterval(question);

            // If the quality response was lower than 3 then start repetitions for the item from the beginning
            // without changing the E-Factor (i.e. use intervals I(1), I(2) etc. as if the item was memorized anew).
            if (question.ResponseQuality < 3)
            {
                question.Interval = 1;
            }

            // If it's the first ask use Today. Otherwise use the LastAsked, which may not necessarily be today.
            if (question.LastAsked == DateTime.MinValue)
                question.NextAskOn = DateTime.Today.AddDays(question.Interval);
            else
                question.NextAskOn = question.LastAsked.AddDays(question.Interval);

            question.LastAsked = DateTime.Today;
            //question.LastAsked = question.NextAskOn; // for debugging

            string format = "[{0}][{1}]\tScore:{2}\tEF:{3}\tNext ask: {4}\tLast ask:{5}\tPrevious interval: {6}\tNew interval: {7}";
            Logger.Info(format, question.Category,
                                        DateTime.Now.ToString(),
                                        question.ResponseQuality,
                                        question.EasinessFactor,
                                        question.NextAskOn.ToShortDateString(),
                                        question.LastAsked.ToShortDateString(),
                                        question.PreviousInterval,
                                        question.Interval);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Calculates how long the interval should be until the next ask.
        /// </summary>
        private static void SetInterval(Question question)
        {
            /// [1] = 1 day
            /// [2] = 6 days later
            /// for n>2 I(n):=I(n-1)*EF
            ///
            /// In C#:
            /// interval[n] = interval[n-1] * EF

            int newPreviousInterval = question.Interval;

            // Zero is where it hasn't been asked yet, just added
            if (question.PreviousInterval < 1)
            {
                question.Interval = 1;	// first ask
            }
            else if (question.PreviousInterval == 1)
            {
                question.Interval = 6;	// 2nd ask
            }
            else if (question.PreviousInterval >= 6)
            {
                question.Interval = (int)Math.Round(question.PreviousInterval * question.EasinessFactor, MidpointRounding.AwayFromZero); // school rounding
            }

            question.PreviousInterval = newPreviousInterval;
        }
Exemplo n.º 25
0
        public void Given_a_existing_yes_answer_but_update_no_and_have_a_deleted_significant_finding_When_answer_updated_Then_should_set_properties_as_expected()
        {
            // Given
            var user = new UserForAuditing();
            var fireRiskAssessmentChecklist = new FireRiskAssessmentChecklist();
            var question = new Question();

            var target = FireAnswer.Create(fireRiskAssessmentChecklist, question, YesNoNotApplicableEnum.Yes, "Additional Info", user);
            target.SignificantFinding = new SignificantFinding()
                                            {
                                                Deleted = true
                                            };
            
            // When
            target.Update(YesNoNotApplicableEnum.No, "Additional Info", user);

            // Then
            Assert.That(target.SignificantFinding, Is.Not.Null);
            Assert.That(target.SignificantFinding.Deleted, Is.False);
            Assert.That(target.FireRiskAssessmentChecklist, Is.EqualTo(fireRiskAssessmentChecklist));
            Assert.That(target.YesNoNotApplicableResponse, Is.EqualTo(YesNoNotApplicableEnum.No));
            Assert.That(target.AdditionalInfo, Is.EqualTo("Additional Info"));
            Assert.That(target.LastModifiedOn.Value.ToShortDateString(), Is.EqualTo(DateTime.Now.ToShortDateString()));
            Assert.That(target.LastModifiedBy, Is.EqualTo(user));
        }
Exemplo n.º 26
0
 public InputQuestion(int i, Question q, bool ip)
 {
     base.domain = q.Domain;
     base.id = i;
     isProgram = ip;
     t = new TextBox();
     t.TextMode = TextBoxMode.MultiLine;
     t.Rows = 4;
     base.l.Text = q.Domain + ") " + q.QuestionText;
     answer = q.Answer;
     if (q.Link.Length>0)
     {
         fh.Text = q.Link;
         fh.NavigateUrl = "~/Lectii.aspx#" + q.Link;
     }
     else
     {
         fh.Text = "Lectiile";
         fh.NavigateUrl = "~/Lectii.aspx";
     }
     if (isProgram)
     {
         t.Rows = 10;
         pcount++;
     }
     else
     {
         icount++;
     }
 }
        public void TokenizeTheQuestion(Question question)
        {
            var timezoneRegex = new StringBuilder();
            timezoneRegex.Append("(");
            var isFirstIteration = true;
            foreach (var timezone in Timezones.GetAllTimezones())
            {
                if (!isFirstIteration)
                    timezoneRegex.Append("|");
                if(timezone.TokenizeOnAbbreviation)
                    timezoneRegex.Append(String.Format("{0}|{1}", timezone.Name, timezone.Abbreviation));
                else
                    timezoneRegex.Append(timezone.Name);
                isFirstIteration = false;
            }

            timezoneRegex.Append(")");
            var matches = Regex.Matches(question.QuestionText, @"(^|\s)" + timezoneRegex.ToString() + @"(\s|$|,)", RegexOptions.IgnoreCase);
            foreach (Match match in matches)
            {
                Group group = match.Groups[0];
                var token = new TimezoneToken(group.Value, group.Index);
                question.AddToken(token);
            }
        }
Exemplo n.º 28
0
 public QueueManager(Stack<Question> next, Stack<Question> previous, Question startItem)
 {
     Controller = new Stack<Question>();
     Controller.Push(startItem);
     NextQueue = next;
     PreviousQueue = previous;
 }
Exemplo n.º 29
0
 ///<summary>Inserts one Question into the database.  Provides option to use the existing priKey.</summary>
 internal static long Insert(Question question,bool useExistingPK)
 {
     if(!useExistingPK && PrefC.RandomKeys) {
         question.QuestionNum=ReplicationServers.GetKey("question","QuestionNum");
     }
     string command="INSERT INTO question (";
     if(useExistingPK || PrefC.RandomKeys) {
         command+="QuestionNum,";
     }
     command+="PatNum,ItemOrder,Description,Answer,FormPatNum) VALUES(";
     if(useExistingPK || PrefC.RandomKeys) {
         command+=POut.Long(question.QuestionNum)+",";
     }
     command+=
              POut.Long  (question.PatNum)+","
         +    POut.Int   (question.ItemOrder)+","
         +"'"+POut.String(question.Description)+"',"
         +"'"+POut.String(question.Answer)+"',"
         +    POut.Long  (question.FormPatNum)+")";
     if(useExistingPK || PrefC.RandomKeys) {
         Db.NonQ(command);
     }
     else {
         question.QuestionNum=Db.NonQ(command,true);
     }
     return question.QuestionNum;
 }
Exemplo n.º 30
0
 ///<summary>Inserts one Question into the database.  Returns the new priKey.</summary>
 internal static long Insert(Question question)
 {
     if(DataConnection.DBtype==DatabaseType.Oracle) {
         question.QuestionNum=DbHelper.GetNextOracleKey("question","QuestionNum");
         int loopcount=0;
         while(loopcount<100){
             try {
                 return Insert(question,true);
             }
             catch(Oracle.DataAccess.Client.OracleException ex){
                 if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
                     question.QuestionNum++;
                     loopcount++;
                 }
                 else{
                     throw ex;
                 }
             }
         }
         throw new ApplicationException("Insert failed.  Could not generate primary key.");
     }
     else {
         return Insert(question,false);
     }
 }
Exemplo n.º 31
0
        public List <Booklet> LoadBooklets(PlayerIndex playerIndex)
        {
            this.WaitOnOperation();
            List <Booklet> booklets = new List <Booklet>();

            foreach (string bookletName in _nameWrapper.BookletNames)
            {
                FindCabinet(playerIndex, CabinetMode.Open, bookletName);
                this.WaitOnOperation();
                booklets.Add(_currentBooklet);
            }

            //Hack for initialization with no booklets
            if (booklets.Count == 0)
            {
                Booklet math = new Booklet("Math");
                //Booklet history = new Booklet("History");

                Quiz mqz1 = new Quiz("Test Quiz 1");
                Quiz mqz2 = new Quiz("Test Quiz 2");

/*				Quiz mqz3 = new Quiz("Test Quiz 3");
 *                              Quiz mqz4 = new Quiz("Test Quiz 4");
 *                              Quiz mqz5 = new Quiz("Test Quiz 5");
 *                              Quiz mqz6 = new Quiz("Test Quiz 6");
 *                              Quiz mqz7 = new Quiz("Test Quiz 7");*/
                //Quiz hqz1 = new Quiz("Test Quiz 1 second");
                //Quiz hqz2 = new Quiz("Test Quiz 2 second");

                Question mq11 = new Question("What is 1+1?", new List <Answer> {
                    new Answer("2", true), new Answer("1", false), new Answer("4", false), new Answer("3", false)
                });
                Question mq12 = new Question("What is 1+5?", new List <Answer> {
                    new Answer("6", true), new Answer("5", false), new Answer("12", false), new Answer("7", false)
                });
                Question mq13 = new Question("What is 13-2?", new List <Answer> {
                    new Answer("11", true), new Answer("12", false), new Answer("10", false), new Answer("3", false)
                });

                Question mq21 = new Question("What is 1*1?", new List <Answer> {
                    new Answer("1", true), new Answer("2", false), new Answer("4", false), new Answer("3", false)
                });
                Question mq22 = new Question("What is 1*5?", new List <Answer> {
                    new Answer("6", false), new Answer("5", true), new Answer("12", false), new Answer("7", false)
                });
                Question mq23 = new Question("What is 14/2?", new List <Answer> {
                    new Answer("7", true), new Answer("12", false), new Answer("10", false), new Answer("3", false)
                });

/*
 *
 *                              Question mq31 = new Question("What is 1*1?", new List<Answer> { new Answer("1", true), new Answer("2", false), new Answer("4", false), new Answer("3", false) });
 *                              Question mq32 = new Question("What is 1*5?", new List<Answer> { new Answer("6", false), new Answer("5", true), new Answer("12", false), new Answer("7", false) });
 *                              Question mq33 = new Question("What is 14/2?", new List<Answer> { new Answer("7", true), new Answer("12", false), new Answer("10", false), new Answer("3", false) });
 *
 *                              Question mq41 = new Question("What is 1*1?", new List<Answer> { new Answer("1", true), new Answer("2", false), new Answer("4", false), new Answer("3", false) });
 *                              Question mq42 = new Question("What is 1*5?", new List<Answer> { new Answer("6", false), new Answer("5", true), new Answer("12", false), new Answer("7", false) });
 *                              Question mq43 = new Question("What is 14/2?", new List<Answer> { new Answer("7", true), new Answer("12", false), new Answer("10", false), new Answer("3", false) });
 *
 *                              Question mq51 = new Question("What is 1*1?", new List<Answer> { new Answer("1", true), new Answer("2", false), new Answer("4", false), new Answer("3", false) });
 *                              Question mq52 = new Question("What is 1*5?", new List<Answer> { new Answer("6", false), new Answer("5", true), new Answer("12", false), new Answer("7", false) });
 *                              Question mq53 = new Question("What is 14/2?", new List<Answer> { new Answer("7", true), new Answer("12", false), new Answer("10", false), new Answer("3", false) });
 *
 *                              Question mq61 = new Question("What is 1*1?", new List<Answer> { new Answer("1", true), new Answer("2", false), new Answer("4", false), new Answer("3", false) });
 *                              Question mq62 = new Question("What is 1*5?", new List<Answer> { new Answer("6", false), new Answer("5", true), new Answer("12", false), new Answer("7", false) });
 *                              Question mq63 = new Question("What is 14/2?", new List<Answer> { new Answer("7", true), new Answer("12", false), new Answer("10", false), new Answer("3", false) });
 *
 *                              Question mq71 = new Question("What is 1*1?", new List<Answer> { new Answer("1", true), new Answer("2", false), new Answer("4", false), new Answer("3", false) });
 *                              Question mq72 = new Question("What is 1*5?", new List<Answer> { new Answer("6", false), new Answer("5", true), new Answer("12", false), new Answer("7", false) });
 *                              Question mq73 = new Question("What is 14/2?", new List<Answer> { new Answer("7", true), new Answer("12", false), new Answer("10", false), new Answer("3", false) });
 */

                mqz1.AddItem(mq11);
                mqz1.AddItem(mq12);
                mqz1.AddItem(mq13);

                mqz2.AddItem(mq21);
                mqz2.AddItem(mq22);
                mqz2.AddItem(mq23);

/*				mqz3.AddItem(mq31);
 *                              mqz3.AddItem(mq32);
 *                              mqz3.AddItem(mq33);
 *
 *                              mqz4.AddItem(mq41);
 *                              mqz4.AddItem(mq42);
 *                              mqz4.AddItem(mq43);
 *
 *                              mqz5.AddItem(mq51);
 *                              mqz5.AddItem(mq52);
 *                              mqz5.AddItem(mq53);
 *
 *                              mqz6.AddItem(mq61);
 *                              mqz6.AddItem(mq62);
 *                              mqz6.AddItem(mq63);
 *
 *                              mqz7.AddItem(mq71);
 *                              mqz7.AddItem(mq72);
 *                              mqz7.AddItem(mq73);*/


                //math.AddItem(mqz7);
                //math.AddItem(mqz6);
                //math.AddItem(mqz5);
                //math.AddItem(mqz4);
                //math.AddItem(mqz3);
                math.AddItem(mqz2);
                math.AddItem(mqz1);
                //history.AddItem(hqz1);
                //history.AddItem(hqz2);

                booklets.Add(math);
                //booklets.Add(history);
            }
            return(booklets);
        }
Exemplo n.º 32
0
        ///<summary>Updates one Question in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.  Returns true if an update occurred.</summary>
        public static bool Update(Question question, Question oldQuestion)
        {
            string command = "";

            if (question.PatNum != oldQuestion.PatNum)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "PatNum = " + POut.Long(question.PatNum) + "";
            }
            if (question.ItemOrder != oldQuestion.ItemOrder)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "ItemOrder = " + POut.Int(question.ItemOrder) + "";
            }
            if (question.Description != oldQuestion.Description)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Description = " + DbHelper.ParamChar + "paramDescription";
            }
            if (question.Answer != oldQuestion.Answer)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Answer = " + DbHelper.ParamChar + "paramAnswer";
            }
            if (question.FormPatNum != oldQuestion.FormPatNum)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "FormPatNum = " + POut.Long(question.FormPatNum) + "";
            }
            if (command == "")
            {
                return(false);
            }
            if (question.Description == null)
            {
                question.Description = "";
            }
            OdSqlParameter paramDescription = new OdSqlParameter("paramDescription", OdDbType.Text, POut.StringParam(question.Description));

            if (question.Answer == null)
            {
                question.Answer = "";
            }
            OdSqlParameter paramAnswer = new OdSqlParameter("paramAnswer", OdDbType.Text, POut.StringParam(question.Answer));

            command = "UPDATE question SET " + command
                      + " WHERE QuestionNum = " + POut.Long(question.QuestionNum);
            Db.NonQ(command, paramDescription, paramAnswer);
            return(true);
        }
Exemplo n.º 33
0
 ///<summary>Inserts one Question into the database.  Returns the new priKey.  Doesn't use the cache.</summary>
 public static long InsertNoCache(Question question)
 {
     return(InsertNoCache(question, false));
 }
Exemplo n.º 34
0
 /// <summary>
 /// Creates a question updater.
 /// </summary>
 public virtual IQuestionUpdater CreateQuestionUpdater(Question question, IModelErrorCollection errors)
 {
     return(question.Accept(this, errors));
 }
Exemplo n.º 35
0
        public IResult QuestionFile(string pathArchiv)
        {
            List <string> stagesArchiv = Directory.GetDirectories
                                             (pathArchiv).ToList();
            Result result = new Result()
            {
                Success = true
            };
            int nomerStage = 0;

            foreach (var stage in configSection.StageItems)
            {
                List <string> substatages = new List <string>();

                if (stagesArchiv.Count >= stage.StageNumber)
                {
                    substatages = Directory.GetDirectories
                                      (stagesArchiv[stage.StageNumber - 1]).ToList();
                }

                int i             = 0;
                int nomerSubStage = 0;

                foreach (var subStage in stage.SubStageItems)
                {
                    List <string> topicThems = new List <string>();

                    if (substatages.Count - 1 >= i)
                    {
                        topicThems = Directory.GetDirectories
                                         (substatages[i]).ToList();
                    }
                    int nomerTopic = 0;
                    for (int k = 0; k < subStage.TopicsCount; k++)
                    {
                        List <string> questions = new List <string>();
                        List <string> sf        = topicThems;

                        if (topicThems.Count - 1 >= k)
                        {
                            questions = Directory.GetDirectories
                                            (topicThems[k]).ToList();
                        }

                        foreach (var s in questions)
                        {
                            List <IQuestion> listQuestion  = new List <IQuestion>();
                            List <string>    topicQuestion =
                                Directory.GetDirectories(s).ToList();

                            List <string> files =
                                Directory.GetFiles(topicQuestion[0]).ToList();
                            IQuestion question = new Question();

                            foreach (var ques in files)
                            {
                                if (ques.Contains(".txt"))
                                {
                                    question.Text = SaveTextFile(ques);
                                }
                                else
                                {
                                    question.FileContent = SaveImageFile(ques);
                                    question.FilePath    = ques;
                                }
                            }

                            listQuestion.Add(question);

                            GameEntityHolder.Game.ChildItemss[nomerStage].
                            ChildItemss[nomerSubStage].ChildItemss[nomerTopic].ChildItemss = listQuestion;
                            nomerTopic++;
                        }
                    }

                    i++;
                    nomerSubStage++;
                }

                nomerStage++;
            }

            return(result);
        }
        /// <summary>
        /// Gets DNSType
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string GetDnsRecord(string uri, DnsQType type)
        {
            string   result = string.Empty;
            Request  req    = new Request();
            Question q      = new Question(uri, type, DnsClass.IN);

            req.AddQuestion(q);
            try
            {
                Response r = Resolver.Lookup(req, GetDnsServer());
                foreach (Answer a in r.Answers)
                {
                    switch (a.Type)
                    {
                    case DnsType.A:
                        result += string.Format("{0} has IPv4 address {1} (ttl: {2}){3}",
                                                a.Domain, a.Record, a.Ttl, Environment.NewLine);
                        break;

                    case DnsType.NS:
                        result += string.Format("{0} nameserver {1}; ttl: {2}{3}",
                                                a.Domain, a.Record, a.Ttl, Environment.NewLine);
                        break;

                    case DnsType.CNAME:
                        result += string.Format("{0} alias of {1} (ttl: {2}){3}",
                                                a.Domain, a.Record, a.Ttl, Environment.NewLine);
                        break;

                    case DnsType.SOA:
                        result += string.Format("typeid:\t\t{0}\nttl:\t\t{1}\ndata:\t\t{2}\ndomain:\t\t{3}\nserial:\t\t{4}\nrefresh:\t\t{5}\nretry:" +
                                                "\t\t{6}\nexpiry:\t\t{7}\nminttl:\t\t{8}\nresponsible:\t{9}\n\n", a.Type, a.Ttl,
                                                ((Bdev.Net.Dns.Records.SoaRecord)a.Record).PrimaryNameServer, uri,
                                                ((Bdev.Net.Dns.Records.SoaRecord)a.Record).Serial, ((Bdev.Net.Dns.Records.SoaRecord)a.Record).Refresh,
                                                ((Bdev.Net.Dns.Records.SoaRecord)a.Record).Retry, ((Bdev.Net.Dns.Records.SoaRecord)a.Record).Expire,
                                                ((Bdev.Net.Dns.Records.SoaRecord)a.Record).DefaultTtl, ((Bdev.Net.Dns.Records.SoaRecord)a.Record).ResponsibleMailAddress);
                        break;

                    case DnsType.MX:
                        result += string.Format("\n{0} mailserver {1} (pri={2}); ttl: {3}", a.Domain,
                                                ((Bdev.Net.Dns.Records.MXRecord)a.Record).DomainName, ((Bdev.Net.Dns.Records.MXRecord)a.Record).Preference, a.Ttl);
                        break;

                    case DnsType.TXT:
                        result += string.Format("{0}:\t{1} (ttl: {2}){3}",
                                                a.Domain, a.Record, a.Ttl, Environment.NewLine);
                        break;

                    case DnsType.AAAA:
                        result += string.Format("{0} has IPv6 address {1} (ttl: {2}){3}",
                                                a.Domain, a.Record, a.Ttl, Environment.NewLine);
                        break;

                    case DnsType.SRV:
                        result += string.Format("{0}:\t{1} (ttl: {2}){3}",
                                                a.Domain, a.Record, a.Ttl, Environment.NewLine);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                if (type == DnsQType.A)
                {
                    return(GetDnsRecord(uri, DnsQType.CNAME));
                }

                return(uri + ": " + ex.Message + Environment.NewLine);
            }
            return(result);
        }
Exemplo n.º 37
0
 public void DeleteQuestion(Question question)
 {
     _context.Questions.Remove(question);
 }
Exemplo n.º 38
0
        public MainPage()
        {
            this.Resources.Add(StyleSheet.FromAssemblyResource
                                   (IntrospectionExtensions.GetTypeInfo(typeof(MainPage)).Assembly,
                                   "ChernivtsiGuide.mystyles.css"));

            confirmButton.Clicked += delegate { OnConfirmButtonClicked(selectedPlaces); };

            NavigationPage.SetTitleView(this, new Image()
            {
                Source = "smart_che.png", HorizontalOptions = LayoutOptions.FillAndExpand
            });

            Question generalQuestion      = App.questionRepository.GetQuestion(1);
            Label    generalQuestionLebel = new Label()
            {
                Text = generalQuestion.Question_content, HorizontalTextAlignment = TextAlignment.Center, FontSize = 20, FontFamily = "TimesNewRoman"
            };

            IEnumerable <General_type> general_Types = App.generalTypeRepository.GetItems();
            StackLayout generalTypesStack            = new StackLayout();

            foreach (General_type general_Type in general_Types)
            {
                Button generalButton = new Button()
                {
                    Text = general_Type.General_name, WidthRequest = 200, HeightRequest = 50
                };
                generalButton.Clicked += delegate { OnGeneralButtonClicked(general_Type.General_id, general_Type.General_question); };
                Image generalImage = new Image {
                    Source = general_Type.General_type_logo
                };
                StackLayout generalImageButton = new StackLayout();
                generalImageButton.Children.Add(generalButton);
                generalImageButton.Children.Add(generalImage);
                generalTypesStack.Children.Add(generalImageButton);
            }
            generalTypesStack.Orientation = StackOrientation.Horizontal;

            ScrollView generalTypeScrollView = new ScrollView()
            {
                Content     = generalTypesStack,
                Orientation = ScrollOrientation.Horizontal,
            };

            StackLayout confirmStackLayout = new StackLayout()
            {
                Children = { confirmButton }
            };

            //Content
            StackLayout ContentStackLayout = new StackLayout()
            {
                Children = { generalQuestionLebel, generalTypeScrollView, placeTypeLabel, placeTypeScrollView, placeAttribute1Label, placeAttribute1ScrollView, placeAttribute2Label, placeAttribute2ScrollView, confirmStackLayout }
            };

            ScrollView contentScrollView = new ScrollView()
            {
                HorizontalOptions = LayoutOptions.Fill,
                VerticalOptions   = LayoutOptions.FillAndExpand,
                Orientation       = ScrollOrientation.Vertical,
                Content           = ContentStackLayout,
                BackgroundColor   = Color.FromRgb(185, 221, 210)
            };

            this.Content = contentScrollView;
        }
Exemplo n.º 39
0
        //
        // GET: /Questions/
        public ActionResult Index()
        {
            Question q = new Question();

            return(View(q.getTitles()));
        }
Exemplo n.º 40
0
 public QuestionCreated(Question question)
 {
     Question = question;
 }
Exemplo n.º 41
0
        public void WhenRefreshWhitelist_AndInactivePeersInWhitelist_ThenWhitelistDoesNotContainInactivePeers()
        {
            // Arrange.
            var mockDateTimeProvider = new Mock <IDateTimeProvider>();

            var mockLogger        = new Mock <ILogger>();
            var mockLoggerFactory = new Mock <ILoggerFactory>();

            mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);
            ILoggerFactory loggerFactory = mockLoggerFactory.Object;

            mockDateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 8, 30, 1, 2, 3))).Verifiable();
            IDateTimeProvider dateTimeProvider = mockDateTimeProvider.Object;

            int inactiveTimePeriod = 3000;

            IPAddress activeIpAddressOne = IPAddress.Parse("::ffff:192.168.0.1");
            var       activeEndpointOne  = new IPEndPoint(activeIpAddressOne, 80);

            IPAddress activeIpAddressTwo = IPAddress.Parse("::ffff:192.168.0.2");
            var       activeEndpointTwo  = new IPEndPoint(activeIpAddressTwo, 80);

            IPAddress activeIpAddressThree = IPAddress.Parse("::ffff:192.168.0.3");
            var       activeEndpointThree  = new IPEndPoint(activeIpAddressThree, 80);

            IPAddress activeIpAddressFour = IPAddress.Parse("::ffff:192.168.0.4");
            var       activeEndpointFour  = new IPEndPoint(activeIpAddressFour, 80);

            var activeTestDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >()
            {
                new Tuple <IPEndPoint, DateTimeOffset> (activeEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(10)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(20)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(30)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointFour, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(40))
            };

            IPAddress inactiveIpAddressOne = IPAddress.Parse("::ffff:192.168.100.1");
            var       inactiveEndpointOne  = new IPEndPoint(inactiveIpAddressOne, 80);

            IPAddress inactiveIpAddressTwo = IPAddress.Parse("::ffff:192.168.100.2");
            var       inactiveEndpointTwo  = new IPEndPoint(inactiveIpAddressTwo, 80);

            IPAddress inactiveIpAddressThree = IPAddress.Parse("::ffff:192.168.100.3");
            var       inactiveEndpointThree  = new IPEndPoint(inactiveIpAddressThree, 80);

            var inactiveTestDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >()
            {
                new Tuple <IPEndPoint, DateTimeOffset> (inactiveEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-10)),
                new Tuple <IPEndPoint, DateTimeOffset>(inactiveEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-20)),
                new Tuple <IPEndPoint, DateTimeOffset>(inactiveEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(-30))
            };

            IPeerAddressManager peerAddressManager = this.CreateTestPeerAddressManager(activeTestDataSet.Concat(inactiveTestDataSet).ToList());

            IMasterFile spiedMasterFile = null;
            var         mockDnsServer   = new Mock <IDnsServer>();

            mockDnsServer.Setup(d => d.SwapMasterfile(It.IsAny <IMasterFile>()))
            .Callback <IMasterFile>(m =>
            {
                spiedMasterFile = m;
            })
            .Verifiable();

            NodeSettings nodeSettings = NodeSettings.Default();
            DnsSettings  dnsSettings  = new Mock <DnsSettings>().Object;

            dnsSettings.DnsPeerBlacklistThresholdInSeconds = inactiveTimePeriod;
            dnsSettings.DnsHostName = "stratis.test.com";
            ConnectionManagerSettings connectionSettings = new ConnectionManagerSettings(nodeSettings);

            var whitelistManager = new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, mockDnsServer.Object, connectionSettings, dnsSettings, this.peerBanning);

            // Act.
            whitelistManager.RefreshWhitelist();

            // Assert.
            spiedMasterFile.Should().NotBeNull();

            var question = new Question(new Domain(dnsSettings.DnsHostName), RecordType.A);
            IList <IResourceRecord> resourceRecords = spiedMasterFile.Get(question);

            resourceRecords.Should().NotBeNullOrEmpty();

            IList <IPAddressResourceRecord> ipAddressResourceRecords = resourceRecords.OfType <IPAddressResourceRecord>().ToList();

            ipAddressResourceRecords.Should().HaveSameCount(activeTestDataSet);

            foreach (Tuple <IPEndPoint, DateTimeOffset> testData in activeTestDataSet)
            {
                ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().NotBeNull("the ip address is active and should be in DNS");
            }

            foreach (Tuple <IPEndPoint, DateTimeOffset> testData in inactiveTestDataSet)
            {
                ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().BeNull("the ip address is inactive and should not be returned from DNS");
            }
        }
Exemplo n.º 42
0
 public void Add(Question question)
 {
     _dbContext.Questions.Add(question);
     _dbContext.SaveChanges();
 }
Exemplo n.º 43
0
        public void WhenRefreshWhitelist_AndActivePeersAvailable_ThenWhitelistContainsActivePeers()
        {
            // Arrange.
            var mockDateTimeProvider = new Mock <IDateTimeProvider>();

            var mockLogger        = new Mock <ILogger>();
            var mockLoggerFactory = new Mock <ILoggerFactory>();

            mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);
            ILoggerFactory loggerFactory = mockLoggerFactory.Object;

            mockDateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 8, 30, 1, 2, 3))).Verifiable();
            IDateTimeProvider dateTimeProvider = mockDateTimeProvider.Object;

            int inactiveTimePeriod = 2000;

            IPAddress activeIpAddressOne = IPAddress.Parse("::ffff:192.168.0.1");
            var       activeEndpointOne  = new IPEndPoint(activeIpAddressOne, 80);

            IPAddress activeIpAddressTwo = IPAddress.Parse("::ffff:192.168.0.2");
            var       activeEndpointTwo  = new IPEndPoint(activeIpAddressTwo, 80);

            IPAddress activeIpAddressThree = IPAddress.Parse("::ffff:192.168.0.3");
            var       activeEndpointThree  = new IPEndPoint(activeIpAddressThree, 80);

            IPAddress activeIpAddressFour = IPAddress.Parse("::ffff:192.168.0.4");
            var       activeEndpointFour  = new IPEndPoint(activeIpAddressFour, 80);

            IPAddress activeIpAddressFive = IPAddress.Parse("2607:f8b0:4009:80e::200e");
            var       activeEndpointFive  = new IPEndPoint(activeIpAddressFive, 80);

            var testDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >()
            {
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(10)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(20)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(30)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointFour, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(40)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointFive, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(50))
            };

            // PeerAddressManager does not support IPv4 addresses that are not represented as embedded IPv4 addresses in an IPv6 address.
            IPeerAddressManager peerAddressManager = this.CreateTestPeerAddressManager(testDataSet);

            IMasterFile spiedMasterFile = null;
            var         mockDnsServer   = new Mock <IDnsServer>();

            mockDnsServer.Setup(d => d.SwapMasterfile(It.IsAny <IMasterFile>()))
            .Callback <IMasterFile>(m =>
            {
                spiedMasterFile = m;
            })
            .Verifiable();

            NodeSettings nodeSettings = NodeSettings.Default();
            DnsSettings  dnsSettings  = new Mock <DnsSettings>().Object;

            dnsSettings.DnsPeerBlacklistThresholdInSeconds = inactiveTimePeriod;
            dnsSettings.DnsHostName = "stratis.test.com";
            ConnectionManagerSettings connectionSettings = new ConnectionManagerSettings(nodeSettings);

            var whitelistManager = new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, mockDnsServer.Object, connectionSettings, dnsSettings, this.peerBanning);

            // Act.
            whitelistManager.RefreshWhitelist();

            // Assert.
            spiedMasterFile.Should().NotBeNull();

            // Check for A records (IPv4 embedded in IPv6 and IPv4 addresses).
            var question4 = new Question(new Domain(dnsSettings.DnsHostName), RecordType.A);
            IList <IResourceRecord> resourceRecordsIpv4 = spiedMasterFile.Get(question4);

            resourceRecordsIpv4.Should().NotBeNullOrEmpty();

            IList <IPAddressResourceRecord> ipAddressResourceRecords4 = resourceRecordsIpv4.OfType <IPAddressResourceRecord>().ToList();

            ipAddressResourceRecords4.Should().HaveCount(4);

            // Check for AAAA records (IPv6 addresses).
            var question6 = new Question(new Domain(dnsSettings.DnsHostName), RecordType.AAAA);
            IList <IResourceRecord> resourceRecordsIpv6 = spiedMasterFile.Get(question6);

            resourceRecordsIpv6.Should().NotBeNullOrEmpty();

            IList <IPAddressResourceRecord> ipAddressResourceRecords6 = resourceRecordsIpv6.OfType <IPAddressResourceRecord>().ToList();

            ipAddressResourceRecords6.Should().HaveCount(1);

            foreach (Tuple <IPEndPoint, DateTimeOffset> testData in testDataSet)
            {
                if (testData.Item1.Address.IsIPv4MappedToIPv6)
                {
                    ipAddressResourceRecords4.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().NotBeNull();
                }
                else
                {
                    ipAddressResourceRecords6.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address)).Should().NotBeNull();
                }
            }
        }
Exemplo n.º 44
0
        public void WhenRefreshWhitelist_AndOwnIPInPeers_AndAreRunningFullNode_ThenWhitelistDoesContainOwnIP()
        {
            // Arrange.
            var mockDateTimeProvider = new Mock <IDateTimeProvider>();

            var mockLogger        = new Mock <ILogger>();
            var mockLoggerFactory = new Mock <ILoggerFactory>();

            mockLoggerFactory.Setup(l => l.CreateLogger(It.IsAny <string>())).Returns(mockLogger.Object);
            ILoggerFactory loggerFactory = mockLoggerFactory.Object;

            mockDateTimeProvider.Setup(d => d.GetTimeOffset()).Returns(new DateTimeOffset(new DateTime(2017, 8, 30, 1, 2, 3))).Verifiable();
            IDateTimeProvider dateTimeProvider = mockDateTimeProvider.Object;

            int inactiveTimePeriod = 5000;

            IPAddress activeIpAddressOne = IPAddress.Parse("::ffff:192.168.0.1");
            var       activeEndpointOne  = new IPEndPoint(activeIpAddressOne, 80);

            IPAddress activeIpAddressTwo = IPAddress.Parse("::ffff:192.168.0.2");
            var       activeEndpointTwo  = new IPEndPoint(activeIpAddressTwo, 80);

            IPAddress activeIpAddressThree = IPAddress.Parse("::ffff:192.168.0.3");
            var       activeEndpointThree  = new IPEndPoint(activeIpAddressThree, 80);

            IPAddress externalIPAdress = IPAddress.Parse("::ffff:192.168.99.99");
            int       externalPort     = 80;
            var       externalEndpoint = new IPEndPoint(externalIPAdress, externalPort);

            var activeTestDataSet = new List <Tuple <IPEndPoint, DateTimeOffset> >()
            {
                new Tuple <IPEndPoint, DateTimeOffset> (activeEndpointOne, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(10)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointTwo, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(20)),
                new Tuple <IPEndPoint, DateTimeOffset>(activeEndpointThree, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(30)),
                new Tuple <IPEndPoint, DateTimeOffset> (externalEndpoint, dateTimeProvider.GetTimeOffset().AddSeconds(-inactiveTimePeriod).AddSeconds(40))
            };

            IPeerAddressManager peerAddressManager = this.CreateTestPeerAddressManager(activeTestDataSet);

            var args = new string[] {
                $"-dnspeeractivethreshold={inactiveTimePeriod.ToString()}",
                $"-externalip={externalEndpoint.Address.ToString()}",
                $"-port={externalPort.ToString()}",
            };

            IMasterFile spiedMasterFile = null;
            var         mockDnsServer   = new Mock <IDnsServer>();

            mockDnsServer.Setup(d => d.SwapMasterfile(It.IsAny <IMasterFile>()))
            .Callback <IMasterFile>(m =>
            {
                spiedMasterFile = m;
            })
            .Verifiable();

            Network     network      = KnownNetworks.StratisTest;
            var         nodeSettings = new NodeSettings(network, args: args);
            DnsSettings dnsSettings  = new Mock <DnsSettings>().Object;

            dnsSettings.DnsFullNode = true;
            dnsSettings.DnsPeerBlacklistThresholdInSeconds = inactiveTimePeriod;
            dnsSettings.DnsHostName = "stratis.test.com";
            ConnectionManagerSettings connectionSettings = new ConnectionManagerSettings(nodeSettings);

            var whitelistManager = new WhitelistManager(dateTimeProvider, loggerFactory, peerAddressManager, mockDnsServer.Object, connectionSettings, dnsSettings, this.peerBanning);

            // Act.
            whitelistManager.RefreshWhitelist();

            // Assert.
            spiedMasterFile.Should().NotBeNull();

            var question = new Question(new Domain(dnsSettings.DnsHostName), RecordType.A);
            IList <IResourceRecord> resourceRecords = spiedMasterFile.Get(question);

            resourceRecords.Should().NotBeNullOrEmpty();

            IList <IPAddressResourceRecord> ipAddressResourceRecords = resourceRecords.OfType <IPAddressResourceRecord>().ToList();

            ipAddressResourceRecords.Should().HaveSameCount(activeTestDataSet);

            foreach (Tuple <IPEndPoint, DateTimeOffset> testData in activeTestDataSet)
            {
                ipAddressResourceRecords.SingleOrDefault(i => i.IPAddress.Equals(testData.Item1.Address.MapToIPv4())).Should().NotBeNull();
            }
        }
Exemplo n.º 45
0
 public void Add(Question question)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 46
0
 public void Update(Question updatedQuestion)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 47
0
    /// <summary>
    /// 创建答题列表
    /// </summary>
    /// <param name="n">列表题数</param>
    /// <param name="errorQts">上次答错题集合</param>
    public void randomQuestion(int n)
    {
        bool          tmpFlag    = true;
        List <string> loadedSign = new List <string>();
        XmlDocument   xmlDoc     = new XmlDocument();

        xmlDoc = Vesal_DirFiles.loadXml(BankScriControl.currentQaPath, GlobalVariable.bankName + ".xml");
        //#if UNITY_EDITOR
        //        n = 1000;
        //        tmpFlag = false;
        //        if (editXmlDoc == null)
        //        {
        //            editXmlDoc = xmlDoc;
        //        }
        //#endif
        Debug.Log("------" + GlobalVariable.bankName);
        Debug.Log("------" + GlobalVariable.libName);
        Question.LibId = ((XmlElement)xmlDoc.SelectSingleNode("//library[@name='" + GlobalVariable.libName + "']")).GetAttribute("id");
        Debug.Log(Question.LibId);
        //试卷答全部题
        if (GlobalVariable.bankName.StartsWith("classId"))
        {
            n = xmlDoc.SelectNodes("//library[@name='" + GlobalVariable.libName + "']/Question").Count;
            Debug.Log("=========总题数" + n);
            GlobalVariable.questionCount = n;
        }



        List <string>   idLists  = QaDao.instance.getTopErrorQaId(Mathf.FloorToInt(n * GlobalVariable.errorReappear), GlobalVariable.bankName, GlobalVariable.libName);
        List <Question> errorQts = new List <Question>();
        string          tmpStr;
        string          xPath;
        XmlElement      xe;
        Question        tmpQues;

        Debug.Log(idLists.Count);
        if (tmpFlag)
        {
            for (int m = 0; m < idLists.Count; m++)
            {
                tmpStr = idLists[m];
                xPath  = "//library[@name='" + GlobalVariable.libName + "']/Question[grade <=" + CurrentMaxGrade + " and @qid = \"" + tmpStr + "\"]";
                xe     = (XmlElement)xmlDoc.SelectSingleNode(xPath);
                Debug.Log(tmpStr);
                if (xe != null)
                {
                    tmpQues = new Question(xe);
                    //                    if (tmpQues.modelName != "null") {
                    //                        ScenceData.loadModel(tmpQues.abName, tmpQues.modelName, tmpQues.questionType == Question.QuestionType.thumbtack?true:false);
                    //                    }
                    //                    if (tmpQues.questionType == Question.QuestionType.thumbtack) {
                    ////                        initThumbtack(ref tmpQues, ref loadedSign);
                    //                    }
                    errorQts.Add(tmpQues);
                }
            }
        }
        Debug.Log(loadedSign.Count);
        // hasModels = false;
        //int max = int.Parse(maxDropDown.transform.Find("maxLabel").GetComponent<Text>().text);
        xPath = "//library[@name='" + GlobalVariable.libName + "']/Question[grade <=" + CurrentMaxGrade + "]";
        //and grade >= "+currentMinGrade+"]";
        //Question[grade<4 and grade>2]
        ////Question[contains("23",grade)]
        if (xmlDoc == null)
        {
            return;
        }
        //SelectSingleNode(xPath).ChildNodes;
        XmlNodeList node = xmlDoc.SelectNodes(xPath);

        if (n > node.Count)
        {
            n = node.Count;
        }
        Debug.Log(n);
        ScenceData.questions = new Question[n];
        int i = 0;

        //添加错题并记录错题里问题排重
        List <string> ques = new List <string>();

        if (tmpFlag)
        {
            if (errorQts.Count != 0)
            {
                while (i < errorQts.Count)
                {
                    ScenceData.questions[i] = errorQts[i];
                    //if (ScenceData.questions[i].modelName != null && ScenceData.questions[i].modelName != "null")
                    //{
                    //    hasModels = true;
                    //}
                    ques.Add(errorQts[i].qid);
                    i++;
                }
            }
        }

        if (i != n)
        {
            int tmpIndex = 0;

            Question[] tmpQs;
            if (errorQts != null && errorQts.Count != 0)
            {
                Debug.Log(node.Count + "--" + errorQts.Count);
                tmpQs = new Question[node.Count - errorQts.Count];
            }
            else
            {
                tmpQs = new Question[node.Count];
            }
            Debug.Log(tmpQs.Length);
            foreach (XmlElement nodeList in node)
            {
                if (nodeList["q"] != null && !ques.Contains(nodeList.GetAttribute("qid")))
                {
                    tmpQs[tmpIndex] = new Question(nodeList);
                    tmpIndex++;
                }
            }
            if (tmpFlag)
            {
                if (tmpQs.Length > 2)
                {
                    //打乱数组中元素顺序
                    int y; Question tmp;
                    for (int m = 0; m < tmpQs.Length; m++)
                    {
                        do
                        {
                            y = UnityEngine.Random.Range(0, tmpQs.Length);
                        } while (y == m);
                        tmp      = tmpQs[m];
                        tmpQs[m] = tmpQs[y];
                        tmpQs[y] = tmp;
                    }
                }
            }
            tmpIndex = 0;

            while (i <= n - 1)
            {
                //Debug.Log(i+"_"+tmpIndex+ "--tmpQs-"+ tmpQs.Length);
                ScenceData.questions[i] = tmpQs[tmpIndex];
                tmpIndex++;
                if (ScenceData.questions[i] == null)
                {
                    break;
                }
                //                if (ScenceData.questions[i].modelName != null && ScenceData.questions[i].modelName != "null")
                //                {
                //                    //hasModels = true;
                //                    //ScenceData.loadModel(ScenceData.questions[i].abName, ScenceData.questions[i].modelName, ScenceData.questions[i].questionType == Question.QuestionType.thumbtack ? true : false);
                //                    if (ScenceData.questions[i].questionType == Question.QuestionType.thumbtack) {

                ////                        initThumbtack(ref ScenceData.questions[i],ref loadedSign);
                //                    }
                //                }
                i++;
            }
        }
        //初始化本波次错题记录
        ScenceData.errorQts = new List <Question>();
        Debug.Log("end RandomQuestion");
    }
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new BotRepositoryContext(
                       serviceProvider.GetRequiredService <DbContextOptions <BotRepositoryContext> >()))
            {
                if (context.Answers.Any())
                {
                    //return;
                }

                var answers = new Answer[]
                {
                    new Answer {
                        Message = "Привет", MessageType = "HelloType"
                    },
                    new Answer {
                        Message = "Здравствуйте", MessageType = "HelloType"
                    },
                    new Answer {
                        Message = "Пока", MessageType = "ByeType"
                    },
                    new Answer {
                        Message = "До свидания", MessageType = "ByeType"
                    },
                    new Answer {
                        Message = "Шарпик", MessageType = "NameType"
                    },
                    new Answer {
                        Message = "Приходит муж домой, а там жена!", MessageType = "Anecdote"
                    },
                    new Answer {
                        Message = "Купил мужик шляпу, а она ему как раз", MessageType = "Anecdote"
                    },
                    new Answer {
                        Message     = "Если тебе тяжело, значит ты поднимаешься в гору. Если тебе легко, значит ты летишь в пропасть.",
                        MessageType = "Aphorism"
                    },
                    new Answer {
                        Message = "Шутку, как и соль, должно употреблять с умеренностью.", MessageType = "Aphorism"
                    },
                    new Answer {
                        Message = "Не происходит изменений лишь с высшей мудростью и низшей глупостью.", MessageType = "Aphorism"
                    },
                };

                context.Answers.AddRange(answers);
                context.SaveChanges();


                var questions = new Question[]
                {
                    new Question {
                        Message = "привет", MessageType = "HelloType"
                    },
                    new Question {
                        Message = "здравствуй", MessageType = "HelloType"
                    },
                    new Question {
                        Message = "добрый день", MessageType = "HelloType"
                    },
                    new Question {
                        Message = "добрый вечер", MessageType = "HelloType"
                    },
                    new Question {
                        Message = "доброе утро", MessageType = "HelloType"
                    },
                    new Question {
                        Message = "анекдот", MessageType = "Anecdote"
                    },
                    new Question {
                        Message = "как тебя зовут", MessageType = "NameType"
                    },
                    new Question {
                        Message = "пока", MessageType = "ByeType"
                    },
                    new Question {
                        Message = "до свидания", MessageType = "ByeType"
                    },
                    new Question {
                        Message = "который час", MessageType = "TimeType"
                    },
                    new Question {
                        Message = "сколько времени", MessageType = "TimeType"
                    },
                };

                context.Questions.AddRange(questions);
                context.SaveChanges();
            }
        }
Exemplo n.º 49
0
 public QuestionViewModel()
 {
     Question = new Question();
 }
Exemplo n.º 50
0
        public void AddQuestion(Question question)
        {
            string sqlExpression = "sp_InsertQuestion";

            using (var connection = GetConnection())
            {
                connection.Open();
                SqlCommand command = new SqlCommand(sqlExpression, connection);
                command.CommandType = CommandType.StoredProcedure;


                SqlParameter idSubject = new SqlParameter
                {
                    ParameterName = "@IDSubject",
                    Value         = question.IdSubject
                };
                command.Parameters.Add(idSubject);

                SqlParameter authorQuestion = new SqlParameter
                {
                    ParameterName = "@Author",
                    Value         = question.Author
                };
                command.Parameters.Add(authorQuestion);

                SqlParameter textQuestion = new SqlParameter
                {
                    ParameterName = "@Text",
                    Value         = question.Text
                };
                command.Parameters.Add(textQuestion);

                SqlParameter VariantsOfAnswersQuestion = new SqlParameter
                {
                    ParameterName = "@VariantsOfAnswers",
                    Value         = question.VariantsOfAnswer
                };
                command.Parameters.Add(VariantsOfAnswersQuestion);

                SqlParameter themeQuestion = new SqlParameter
                {
                    ParameterName = "@Theme",
                    Value         = question.Theme
                };
                command.Parameters.Add(themeQuestion);

                SqlParameter complexityQuestion = new SqlParameter
                {
                    ParameterName = "@Complexity",
                    Value         = question.Complexity
                };
                command.Parameters.Add(complexityQuestion);

                SqlParameter scoreQuestion = new SqlParameter
                {
                    ParameterName = "@Score",
                    Value         = question.Score
                };
                command.Parameters.Add(scoreQuestion);

                SqlParameter correctAnswerQuestion = new SqlParameter
                {
                    ParameterName = "@CorrectAnswer",
                    Value         = question.CorrectAnswer
                };
                command.Parameters.Add(correctAnswerQuestion);

                command.ExecuteNonQuery();
            }
        }
Exemplo n.º 51
0
 public void Remove(Question question) => _context.Questions.Remove(question);
Exemplo n.º 52
0
 public QuestionViewModel(Question q)
 {
     Question = q ?? new Question();
 }
Exemplo n.º 53
0
 public void Add(Question question) => _context.Questions.Add(question);
Exemplo n.º 54
0
 public void Update(Question question) => _context.Questions.Update(question);
Exemplo n.º 55
0
 public int AddQuestion(Question question)
 {
     return(_questionRepository.Add(question));
 }
Exemplo n.º 56
0
        /// <summary>
        /// Handles a DNS request received by the UDP client.
        /// </summary>
        /// <param name="udpRequest">The DNS request received from the UDP client.</param>
        private async Task HandleRequestAsync(Tuple <IPEndPoint, byte[]> udpRequest)
        {
            Request request = null;

            try
            {
                // Get request from received message (would use 3rd party library Request.FromArray but it doesn't handle additional record
                // flag properly, which dig requests).
                Header header = Header.FromArray(udpRequest.Item2);
                if (header.Response)
                {
                    throw new ArgumentException("Request message is actually flagged as a response.");
                }

                if (header.QuestionCount == 0)
                {
                    throw new ArgumentException("Request message contains no questions.");
                }

                if (header.ResponseCode != ResponseCode.NoError)
                {
                    throw new ArgumentException($"Request message contains a non-error response code of {header.ResponseCode}.");
                }

                // Resolve request against masterfile.
                request = new Request(header, Question.GetAllFromArray(udpRequest.Item2, header.Size, header.QuestionCount));
                IResponse response = this.Resolve(request);

                // Send response.
                await this.udpClient.SendAsync(response.ToArray(), response.Size, udpRequest.Item1).WithCancellationTimeout(UdpTimeout);
            }
            catch (SocketException e)
            {
                this.logger.LogError(e, "Socket error {0} whilst sending DNS response to {1}", e.ErrorCode, udpRequest.Item1);
            }
            catch (OperationCanceledException e)
            {
                this.logger.LogError(e, "Sending DNS response to {0} timed out.", udpRequest.Item1);
            }
            catch (ResponseException e)
            {
                this.logger.LogError(e, "Received error {0} when sending DNS response to {1}, trying again.", e.Response.ResponseCode, udpRequest.Item1);

                // Try and send response one more time.
                IResponse response = e.Response;
                if (response == null)
                {
                    response = Response.FromRequest(request);
                }

                try
                {
                    await this.udpClient.SendAsync(response.ToArray(), response.Size, udpRequest.Item1).WithCancellationTimeout(UdpTimeout);
                }
                catch (SocketException ex)
                {
                    this.logger.LogError(ex, "Socket error {0} whilst sending DNS response to {1}", ex.ErrorCode, udpRequest.Item1);
                }
                catch (OperationCanceledException ex)
                {
                    this.logger.LogError(ex, "Sending DNS response to {0} timed out.", udpRequest.Item1);
                }
            }
        }
Exemplo n.º 57
0
 public bool UpdateQuestion(Question question)
 {
     return(_questionRepository.Edit(question));
 }
Exemplo n.º 58
0
        public void Can_replicate_to_sql_when_document_is_updated()
        {
            CreateRdbmsSchema();

            using (var session = documentStore.OpenSession())
            {
                session.Store(new IndexReplicationDestination
                {
                    Id             = "Raven/IndexReplication/Questions/Votes",
                    ColumnsMapping =
                    {
                        { "Title",     "Title"     },
                        { "UpVotes",   "UpVotes"   },
                        { "DownVotes", "DownVotes" },
                        { "Date",      "Date"      },
                    },
                    ConnectionStringName = ConnectionString.Name,
                    PrimaryKeyColumnName = "Id",
                    TableName            = "QuestionSummaries"
                });
                session.SaveChanges();
            }
            using (var session = documentStore.OpenSession())
            {
                var q = new Question
                {
                    Id    = "questions/1",
                    Title = "How to replicate to SQL Server?",
                    Votes = new[]
                    {
                        new Vote {
                            Up = true, Comment = "Good!"
                        },
                        new Vote {
                            Up = false, Comment = "Nah!"
                        },
                        new Vote {
                            Up = true, Comment = "Nice..."
                        },
                    }
                };
                session.Store(q);
                session.SaveChanges();
            }

            using (var session = documentStore.OpenSession())
            {
                session.Advanced.LuceneQuery <Question>("Questions/Votes")
                .WaitForNonStaleResults()
                .SelectFields <QuestionSummary>("__document_id", "Title", "UpVotes", "DownVotes")
                .ToList();
            }

            using (var session = documentStore.OpenSession())
            {
                var q = new Question
                {
                    Id    = "questions/1",
                    Title = "How to replicate to SQL Server!?",
                    Votes = new[]
                    {
                        new Vote {
                            Up = true, Comment = "Good!"
                        },
                        new Vote {
                            Up = false, Comment = "Nah!"
                        },
                        new Vote {
                            Up = true, Comment = "Nice..."
                        },
                        new Vote {
                            Up = false, Comment = "No!"
                        },
                    }
                };
                session.Store(q);
                session.SaveChanges();
            }

            using (var session = documentStore.OpenSession())
            {
                session.Advanced.LuceneQuery <Question>("Questions/Votes")
                .WaitForNonStaleResults()
                .SelectFields <QuestionSummary>("__document_id", "Title", "UpVotes", "DownVotes")
                .ToList();
            }

            var providerFactory = DbProviderFactories.GetFactory(ConnectionString.ProviderName);

            using (var con = providerFactory.CreateConnection())
            {
                con.ConnectionString = ConnectionString.ConnectionString;
                con.Open();

                using (var dbCommand = con.CreateCommand())
                {
                    dbCommand.CommandText = "SELECT * FROM QuestionSummaries";
                    using (var reader = dbCommand.ExecuteReader())
                    {
                        Assert.True(reader.Read());

                        Assert.Equal("questions/1", reader["Id"]);
                        Assert.Equal("How to replicate to SQL Server!?", reader["Title"]);
                        Assert.Equal(2, reader["UpVotes"]);
                        Assert.Equal(2, reader["DownVotes"]);
                        Assert.Equal(new DateTime(2000, 1, 1), reader["Date"]);
                    }
                }
            }
        }
Exemplo n.º 59
0
 public Question UpdateQuestion(Question question)
 {
     throw new NotImplementedException();
 }
 public void removeQuestion(Question q)
 {
     itmsQuestions.Items.Remove(q);
 }