Пример #1
0
        public void ToNewlineStringTest()
        {
            TestInfrastructure.DebugLineStart(TestContext);
            if (TestInfrastructure.IsActive(TestContext))
            {
                using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser))
                {
                    ICard  card  = writeLM.Cards.AddNew();
                    IWords words = card.Question;

                    for (int i = 0; i < TestInfrastructure.Random.Next(10, 50); i++)
                    {
                        IWord word = words.CreateWord("Word " + i.ToString(), WordType.Word, true);
                        words.AddWord(word);
                    }

                    string newLineStringClone = string.Empty;
                    foreach (IWord var in words.Words)
                    {
                        newLineStringClone += var.Word + "\r\n";
                    }
                    newLineStringClone = newLineStringClone.Substring(0, newLineStringClone.Length - 2);

                    Assert.AreEqual <string>(newLineStringClone, words.ToNewlineString(), "IWords.ToNewlineStringTest does not match with expected output.");
                }
            }
            TestInfrastructure.DebugLineEnd(TestContext);
        }
Пример #2
0
        public void AddWordsListTest()
        {
            TestInfrastructure.DebugLineStart(TestContext);
            if (TestInfrastructure.IsActive(TestContext))
            {
                using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser))
                {
                    IChapter chapter = writeLM.Chapters.AddNew();
                    chapter.Title = "A chapter";

                    ICard card = writeLM.Cards.AddNew();
                    card.Chapter = chapter.Id;
                    List <IWord> wordList = new List <IWord>();

                    for (int i = 0; i < TestInfrastructure.Random.Next(10, 50); i++)
                    {
                        IWord word = card.Question.CreateWord("Word " + i.ToString(), WordType.Word, true);
                        wordList.Add(word);
                    }

                    card.Question.AddWords(wordList);

                    for (int i = 0; i < wordList.Count; i++)
                    {
                        Assert.AreEqual <string>("Word " + i.ToString(), writeLM.Cards.Get(card.Id).Question.Words[i].Word, "IWords.AddWords(List) does not add a list of words.");
                    }
                }
            }
            TestInfrastructure.DebugLineEnd(TestContext);
        }
Пример #3
0
        public void AddWord(IWord word)
        {
            if (!(word is PreviewWord))
                throw new Exception("Only Preview word objects can be added.");

            words.Add(word);
        }
Пример #4
0
        public async Task <IReadOnlyList <IProposal> > ProposeAsync(IWord word)
        {
            var query = word.Text;
            var json  = await GetJsonAsync(query).ConfigureAwait(false);

            var res       = JsonConvert.DeserializeObject <WikiApiResult>(json);
            var proposals = new List <IProposal>();

            foreach (var pgEntry in res.query.pages)
            {
                if (!(Int32.TryParse(pgEntry.Key, out int pgid) && pgid > 0))
                {
                    continue;
                }
                var pg = pgEntry.Value;
                if (!string.IsNullOrWhiteSpace(pg.extract))
                {
                    var prop = new Proposal();
                    var ann  = new Annotation(word);
                    ann.Content      = pg.extract.Replace("\n", "\r\n");;
                    prop.Annotation  = ann;
                    prop.Description = $"wiki:{LanguageCode} {pg.title}";
                    proposals.Add(prop);
                }
            }

            return(proposals);
        }
Пример #5
0
        private IDajare connectWithDoshi(IWord doshi)
        {
            if (doshi.GetHinshi() != Hinshi.Doshi)
            {
                throw new Exception();
            }
            IDajare       res = new Dajare();
            WordEvaluator we  = WordEvaluator.GetInstance();

            IWord[] 助詞s =
            {
                new Word("を", Hinshi.Joshi),
                new Word("へ", Hinshi.Joshi),
                new Word("が", Hinshi.Joshi)
            };
            IWord best助詞 = null;
            long  max    = 0;

            foreach (IWord j in 助詞s)
            {
                long e1   = we.Evaluate(meishi.ToKanji() + j.ToKanji());
                long e2   = we.Evaluate(j.ToKanji() + doshi.ToKanji());
                long eval = e1 * e1 + e2 * e2;
                if (max > eval)
                {
                    max    = eval;
                    best助詞 = j;
                }
            }
            res.Add(this.meishi);
            res.Add(best助詞);
            res.Add(doshi);
            return(res);
        }
Пример #6
0
 public HangmanEngine(IDrawable drawManager, IReader reader, IWord word, IPlayer player)
     : base(drawManager, reader)
 {
     this.word           = word;
     this.player         = player;
     this.historyLetters = new HashSet <char>();
 }
Пример #7
0
        public Syllable[] GetOrderedSyllables(IWord word)
        {
            var syllableStrings = _syllablesToStringConverter.Parse(word.Pronunciation);

            if (syllableStrings == null)
            {
                return(null);
            }

            var syllArray = syllableStrings.ToArray();

            var sylls       = new List <Syllable>();
            var chineseOnly = word.OriginalWord.ToArray();

            var chineseCharsCount = 0;

            foreach (var character in chineseOnly)
            {
                var isChineseChar = IsChineseCharacter(character);

                if (isChineseChar)
                {
                    sylls.Add(GetSyllable(character, syllArray[chineseCharsCount]));
                    chineseCharsCount++;
                }
                else
                {
                    sylls.Add(new Syllable(character));
                }
            }
            return(sylls.ToArray());
        }
Пример #8
0
        private void HideAndBlackListMenuItemClick(object sender, EventArgs e)
        {
            IWord word = GetWordUnderMouse();

            RemoveFromControl(word);
            AddToBlacklist(word.Text);
        }
Пример #9
0
        /// <summary>
        /// Get all the ids for the parts of this word.
        /// If the part already exists, get the id, otherwise we will insert and then get the id.
        /// </summary>
        /// <param name="word"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private async Task <IList <long> > GetOrInsertParts(IWord word, CancellationToken token)
        {
            // get the parts.
            var parts = word.Parts;

            // if we have not words... then move on.
            if (!parts.Any())
            {
                return(new List <long>());
            }

            Contract.Assert(_partsHelper != null);
            Contract.Assert(_partsSearchHelper != null);

            // try and insert the values and get the ids.
            // the return values are string+id
            // if the id is -1, then we had an error
            var partValuesAndIds = await _partsHelper.InsertAndGetAsync(parts.ToList(), token).ConfigureAwait(false);

            // then add it to the helpers.
            await _partsSearchHelper.InsertAsync(partValuesAndIds.Where(v => v.Id != -1).ToList(), token).ConfigureAwait(false);

            // get all the non -1 ids
            var partIds = partValuesAndIds.Where(v => v.Id != -1).Select(p => p.Id).ToList();

            // and log all the ids that did not work.
            foreach (var partValue in partValuesAndIds.Where(v => v.Id == -1).Select(p => p.Value))
            {
                _logger.Error($"There was an issue adding part: {partValue} to persister");
            }

            // return all the ids that we either
            // added or that already exist.
            return(partIds);
        }
Пример #10
0
 void GetCustomWordsInCommandRecursive(IWord currentWord)
 {
     if (currentWord.AllWordType == AllWordTypes.Table && !currentWord.Initializing)
     {
         TablesInCommand.Add((TableWord)currentWord);
     }
     else if (currentWord.AllWordType == AllWordTypes.Column && !currentWord.Initializing)
     {
         ColumnsInCommand.Add((ColumnWord)currentWord);
     }
     else if (currentWord.AllWordType == AllWordTypes.CustomCustom && !currentWord.Initializing)
     {
         CustomCustomsInCommand.Add((CustomCustomWord)currentWord);
     }
     if (currentWord.Children.Count > 0 && currentWord is IOperation)
     {
         OperationsInCommand.Add((IOperation)currentWord);
     }
     else
     {
         foreach (IWord child in currentWord.Children)
         {
             GetCustomWordsInCommandRecursive(child);
         }
     }
 }
Пример #11
0
        /**
         * /// Add a Node that represents the theory that a given word was spoken over a given period of time.
         *
         * /// @param word
         * /// @param beginTime
         * /// @param endTime
         * /// @return the new Node
         */
        public Node addNode(IWord word, int beginTime, int endTime)
        {
            Node n = new Node(word, beginTime, endTime);

            addNode(n);
            return(n);
        }
Пример #12
0
        public void addElementaryAttribut(string word, string notOperation, IWord inWord)
        {
            ElementaryAttribut attribut = new ElementaryAttribut(notOperation, word, inWord);

            attributSequence.Add(attribut);
            parentEp.getString();
        }
Пример #13
0
        public WordEditor(int byteCount, bool includeSign)
        {
            mWord                  = new Word(byteCount);
            mIncludeSign           = includeSign;
            mReadOnly              = false;
            mLastRenderedMagnitude = unrendered;
            mLastRenderedSign      = Word.Signs.Positive;

            mSignButton = new Button
            {
                Location  = new Point(0, 0),
                Name      = "SignButton",
                Size      = new Size(18, 21),
                TabIndex  = 0,
                TabStop   = false,
                Text      = "" + mWord.Sign.ToChar(),
                FlatStyle = FlatStyle.Flat,
                Enabled   = !ReadOnly
            };
            mSignButton.Click    += MSignButton_Click;
            mSignButton.KeyPress += Editor_KeyPress;
            mSignButton.KeyDown  += This_KeyDown;

            InitializeComponent();
        }
Пример #14
0
        /// <exception cref="InvalidOperationException">Too many adjectives.</exception>
        public void MakeAdjective(IWord word, ISourceLine location)
        {
            var nw = (NewParserWord)word;

            if (!nw.HasClass(adjClass))
            {
                ZilFix value;
                if (ctx.ZEnvironment.ZVersion < 4)
                {
                    if (nextAdjective == 0)
                    {
                        throw new InterpreterError(
                                  InterpreterMessages.Too_Many_0_Only_1_Allowed_In_This_Vocab_Format,
                                  "adjectives",
                                  255);
                    }

                    value = new ZilFix(nextAdjective--);
                }
                else
                {
                    value = null;
                }

                NewAddWord(
                    nw.Atom,
                    ctx.GetStdAtom(StdAtom.TADJ),
                    value,
                    ZilFix.Zero);
            }
        }
Пример #15
0
        private Cursor CreateTargetWithWord(IWord word)
        {
            var cursor = new Cursor();

            cursor.NextWord(1, word);
            return(cursor);
        }
Пример #16
0
        public string Interpret(string instruction)
        {
            string[] instrucs = instruction.Split(';');

            foreach (var word in instrucs)
            {
                if (word.Trim() == "")
                {
                    break;
                }
                string[] words = word.Split(' ');

                _instruction = new Instruction(new Course(double.Parse(words[0])),
                                               new Speed(double.Parse(words[1])),
                                               new Movement(words[2]),
                                               new Voyage(double.Parse(words[3])));

                if (_word == null)
                {
                    _word = _instruction;
                }
                else
                {
                    _word = new Semicolon(_word, _instruction);
                }
            }

            return(_word.Interpret());
        }
Пример #17
0
 public Memento(IWord word, List <string> answers, int score, int counter)
 {
     this.word    = word;
     this.answers = answers;
     this.score   = score;
     this.counter = counter;
 }
Пример #18
0
 public SizedWord(IWord word, int size, FontFamily font, Rectangle rectangle)
 {
     Text      = word.Text;
     Font      = font;
     Rectangle = rectangle;
     Size      = size;
 }
Пример #19
0
 public Instruction(IWord course, IWord speed, IWord movement, IWord voyage)
 {
     this._course   = course;
     this._speed    = speed;
     this._movement = movement;
     this._voyage   = voyage;
 }
Пример #20
0
 public void RestoreMemento(Memento memento)
 {
     this.word    = memento.Word;
     this.answers = memento.Answers;
     this.score   = memento.Score;
     this.counter = memento.Counter;
 }
Пример #21
0
        public void Setup()
        {
            _relativeCoords = new Mock <IAzureCreateRelativeCoordinate>();
            _createWord     = new Mock <ICreateWordFromAzureWord>();

            _imgWidth  = 100;
            _imgHeight = 200;
            _word1     = new Word();
            _word2     = new Word();
            _word3     = new Word();
            _line      = new Line {
                Words = new[] { _word1, _word2, _word3 }
            };

            var metaWord1Mock = new Mock <IWord>();
            var metaWord2Mock = new Mock <IWord>();
            var metaWord3Mock = new Mock <IWord>();

            _metaWord1 = metaWord1Mock.Object;
            _metaWord2 = metaWord2Mock.Object;
            _metaWord3 = metaWord3Mock.Object;

            metaWord1Mock.Setup(x => x.Value).Returns("This is");
            metaWord2Mock.Setup(x => x.Value).Returns("a");
            metaWord3Mock.Setup(x => x.Value).Returns("very important test");

            _createWord.Setup(x => x.Execute(_word1, _imgWidth, _imgHeight)).Returns(metaWord1Mock.Object);
            _createWord.Setup(x => x.Execute(_word2, _imgWidth, _imgHeight)).Returns(metaWord2Mock.Object);
            _createWord.Setup(x => x.Execute(_word3, _imgWidth, _imgHeight)).Returns(metaWord3Mock.Object);

            _target = new TransformAzureLineIntoSentence(_relativeCoords.Object, _createWord.Object);
        }
Пример #22
0
        public WordViewModel()
        {
            IDAO  dao  = (IDAO)LateBinding.GetDAOConstructor().Invoke(new object[] { });
            IWord word = dao.CreateNewWord();

            _word = word;
        }
Пример #23
0
        void MakePart(IWord word, ISourceLine location, PartOfSpeech part, string description,
                      Func <OldParserWord, Action <Context, ISourceLine, byte> > getSetter, ref byte next, bool onlyNumberedInV3 = false)
        {
            var result = (OldParserWord)word;

            if ((result.PartOfSpeech & part) != 0)
            {
                return;
            }

            byte value;

            if (!onlyNumberedInV3 || ctx.ZEnvironment.ZVersion == 3)
            {
                if (next == 0)
                {
                    throw new InterpreterError(
                              InterpreterMessages.Too_Many_0_Only_1_Allowed_In_This_Vocab_Format,
                              description,
                              255);
                }

                value = next--;
            }
            else
            {
                value = 0;
            }

            getSetter(result)(ctx, location, value);
        }
Пример #24
0
        public IDictionaryWord FindBestWord(IWord source)
        {
            int minUsingCount = 100100100;

            foreach (IDictionaryWord dw in dictionaryWords)
            {
                minUsingCount = Math.Min(minUsingCount, dw.GetUsingCount());
            }
            double          maxEval = -100100100;
            IDictionaryWord res     = null;

            foreach (IDictionaryWord dw in dictionaryWords)
            {
                if (minUsingCount != dw.GetUsingCount())
                {
                    continue;
                }
                double eval = Evaluate(source, dw);
                if (maxEval < eval)
                {
                    maxEval = eval;
                    res     = dw;
                }
            }
            if (res == null)
            {
                ;
            }
            return(res);
        }
Пример #25
0
 public static WordViewModel ConvertFromEntity(IWord word)
 {
     return(new WordViewModel
     {
         Value = word.Value
     });
 }
Пример #26
0
 public void CheckCommand(string playerChoice, IWord word)
 {
     var playerChoiceToLower = playerChoice.ToLower();
     if (playerChoiceToLower == Command.Help.ToString().ToLower())
     {
         if (this.HasHelpUsed == true)
         {
             UIMassages.UsedHelpOptionMessage();
             UIMassages.SecretWordMessage(word.PrintView, false);
         }
         else
         {
             this.CommandManager.Proceed(this.HelpCommand);
             this.HasHelpUsed = true;
             if (word.NumOfRevealedLetters < word.WordLength)
             {
                 UIMassages.SecretWordMessage(word.PrintView, false);
             }
         }
     }
     else if (playerChoiceToLower == Command.Restart.ToString().ToLower())
     {
         this.CommandManager.Proceed(this.RestartCommand);
     }
     else if (playerChoiceToLower == Command.Exit.ToString().ToLower())
     {
         this.CommandManager.Proceed(this.ExitCommand);
     }
     else if (playerChoiceToLower == Command.Used.ToString().ToLower())
     {
         this.CommandManager.Proceed(this.UsedCommand);
     }
 }
Пример #27
0
        /**
         * /// Add a Node with a given ID that represents the theory that a given word was spoken over a given period of time.
         * /// This method is used when loading Lattices from .LAT files.
         *
         * /// @param word
         * /// @param beginTime
         * /// @param endTime
         * /// @return the new Node
         */
        protected Node addNode(String id, IWord word, int beginTime, int endTime)
        {
            Node n = new Node(id, word, beginTime, endTime);

            addNode(n);
            return(n);
        }
Пример #28
0
        public Syntax(ISourceLine src, [NotNull] IWord verb, int numObjects, [CanBeNull] IWord prep1, [CanBeNull] IWord prep2,
                      byte options1, byte options2, [CanBeNull] ZilAtom findFlag1, [CanBeNull] ZilAtom findFlag2,
                      [NotNull] ZilAtom action, [CanBeNull] ZilAtom preaction, [NotNull] ZilAtom actionName,
                      [ItemNotNull][CanBeNull] IEnumerable <ZilAtom> synonyms = null)
        {
            SourceLine = src;

            Verb         = verb;
            NumObjects   = numObjects;
            Preposition1 = prep1;
            Preposition2 = prep2;
            Options1     = options1;
            Options2     = options2;
            FindFlag1    = findFlag1;
            FindFlag2    = findFlag2;
            Action       = action;
            Preaction    = preaction;
            ActionName   = actionName;

            if (synonyms == null)
            {
                Synonyms = EmptySynonyms;
            }
            else
            {
                Synonyms = new List <ZilAtom>(synonyms).AsReadOnly();
            }
        }
Пример #29
0
 /// <inheritdoc />
 public async Task <long> AddOrUpdateWordAsync(IWord word, CancellationToken token)
 {
     using (_counterAddOrUpdate.Start())
     {
         return(await InsertWordAsync(word, token).ConfigureAwait(false));
     }
 }
        /// <inheritdoc />
        public async Task <bool> AddWordToFilesAsync(IWord wordToAdd, IList <long> fileIdsToAddWordTo, CancellationToken token)
        {
            // if we have no files, we don't actually want to add the word.
            if (!fileIdsToAddWordTo.Any())
            {
                return(false);
            }

            try
            {
                // try and insert the word into the words table.
                // if the word already exists, we will get the id for it.
                // if the word does not exist, we will add it and get the id for it...
                var wordId = await _words.AddOrUpdateWordAsync(wordToAdd, token).ConfigureAwait(false);

                if (-1 == wordId)
                {
                    _logger.Error($"There was an issue inserting/finding the word : {wordToAdd.Value}.");
                    return(false);
                }

                // then add the id to the files.
                return(await AddWordToFilesAsync(wordId, fileIdsToAddWordTo, token).ConfigureAwait(false));
            }
            catch (OperationCanceledException)
            {
                _logger.Warning("Received cancellation request - Add pending parser words");
                throw;
            }
            catch (Exception ex)
            {
                _logger.Exception("There was an exception adding parser words", ex);
                throw;
            }
        }
Пример #31
0
        public void AddWord(IWord word, long idUser)
        {
            word.OwnerId = idUser;
            var user = _userApi.GetUserById(idUser);

            word.FolderId = user.CurrentFolderId;
            _wordApi.AddWord(word);
        }
Пример #32
0
        public void UpdateWord(IWord word)
        {
            var path     = "/word";
            var postBody = ApiClient.Serialize(word);
            var response = ApiClient.CallApi(path, Method.PUT, postBody);

            ApiClient.CheckResponse(response);
        }
Пример #33
0
 public IWord GetChallenge()
 {
     IWord word;
     do {
         var wordIndex = random.Next () % words.Count;
         word = words [wordIndex];
     } while(words.Count > 1 && word == previousWord);
     previousWord = word;
     return word;
 }
Пример #34
0
 protected void Dump(IWord word)
 {
     Console.Out.WriteLine(word.Text + ", " + word.Type);
     int n = 1;
     foreach (IMeaning meaning in word.Meanings)
     {
         Console.Out.WriteLine(String.Format("{0}.", n));
         Dump(meaning);
     }
 }
Пример #35
0
 private int CompareWords(IWord alfa, IWord bravo)
 {
     int scoreAlfa, scoreBravo;
     if (record.TryGetValue (alfa, out scoreAlfa) == false) {
         scoreAlfa = 0;
     }
     if (record.TryGetValue (bravo, out scoreBravo) == false) {
         scoreBravo = 0;
     }
     //This is inverted so that the list will sort in descending order
     return scoreBravo - scoreAlfa;
 }
Пример #36
0
 public IWord GetChallenge()
 {
     words.Sort (CompareWords);
     IWord word;
     do {
         var wordIndex = random.Next () % words.Count;
         wordIndex *= wordIndex;
         wordIndex /= words.Count;
         word = words [wordIndex];
     } while(words.Count > 1 && word == previousWord);
     previousWord = word;
     return word;
 }
Пример #37
0
 public void LogOutcome(IWord word, IScore score)
 {
     int rank;
     if (record.TryGetValue (word, out rank) == false) {
         rank = 0;
     }
     if (score.IsCorrect) {
         rank /= 2;
     } else {
         rank++;
     }
     record [word] = rank;
 }
Пример #38
0
        /// <summary>
        /// Checks if opcode represents this command
        /// </summary>
        /// <param name="word">A word from the memory</param>
        /// </param>
        /// <returns>true if the word represents this command</returns>
        public static bool CheckOpCode(IWord word)
        {
            int result = word.UValue | 3072;

            if (result == 3968)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
Пример #39
0
 private void GameOver(IWord word)
 {
     if (this.Player.AttemptsToGuess == MaxPlayerAttempts)
     {
         UIMessages.LostGameMessage();
     }
     else
     {
         UIMessages.GuessAllWordMessage(this.Player.AttemptsToGuess);
         UIMessages.SecretWordMessage(word.Content, true);
         this.ScoreBoard.Update(this.Player);
         this.ScoreBoard.Print();
     }
 }
Пример #40
0
        public void InputData(IWord word)
        {
            while (true)
            {
                UIMassages.InviteForGuessOrCommandMessage();
                string playerChoice = this.ConsoleWrapper.ReadLine().ToLower();
                if (playerChoice == string.Empty)
                {
                    continue;
                }

                char playerLetter = playerChoice.ToLower()[0];
                if (playerChoice.Length > 1)
                {
                    if (this.IsTheCommandCorrect(playerChoice))
                    {
                        this.CheckManager.CheckCommand(playerChoice, word);
                    }
                    else
                    {
                        UIMassages.IncorrectInputMessage();
                    }
                    if (word.NumOfRevealedLetters == word.WordLength)
                    {
                        break;
                    }
                }
                else
                {
                    if (char.IsLetter(playerLetter))
                    {
                        this.CheckManager.CheckLetterAccordance(word, playerLetter);
                    }
                    else
                    {
                        UIMassages.IncorrectInputMessage();
                    }
                    break;
                }
            }
        }
Пример #41
0
        public void AddWord(int id, Side side, WordType type, IWord word)
        {
            if (word != null && word.Word.Length > 0)
            {
                using (NpgsqlConnection con = PostgreSQLConn.CreateConnection(Parent.CurrentUser))
                {
                    using (NpgsqlCommand cmd = con.CreateCommand())
                    {
                        cmd.CommandText = "SELECT \"InsertWordIfNotExists\"(:id,:cardid,:isdefault,:text,:side,:type);";
                        cmd.Parameters.Add("id", word.Id);
                        cmd.Parameters.Add("isdefault", word.Default);
                        cmd.Parameters.Add("cardid", id);
                        cmd.Parameters.Add("text", word.Word);
                        cmd.Parameters.Add("side", side.ToString());
                        cmd.Parameters.Add("type", type.ToString());
                        PostgreSQLConn.ExecuteNonQuery(cmd, Parent.CurrentUser);

                        Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(ObjectLifetimeIdentifier.GetCacheObject(side, type), id));
                    }
                }
            }
        }
        /// <summary>
        /// Adds the word.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <param name="side">The side.</param>
        /// <param name="type">The type.</param>
        /// <param name="word">The word.</param>
        /// <remarks>Documented by Dev03, 2009-01-09</remarks>
        public void AddWord(int id, Side side, WordType type, IWord word)
        {
            if (word != null && word.Word.Length > 0)
            {
                SqlCeCommand cmd = MSSQLCEConn.CreateCommand(Parent.CurrentUser);
                cmd.CommandText = "SELECT count(*) FROM TextContent WHERE id = @wordid AND text = @word AND type = @type AND is_default = @isdefault;";
                cmd.Parameters.Add("@wordid", word.Id);
                cmd.Parameters.Add("@word", word.Word);
                cmd.Parameters.Add("@type", type.ToString());
                cmd.Parameters.Add("@isdefault", word.Default);
                bool wordExists = (Convert.ToInt32(MSSQLCEConn.ExecuteScalar(cmd)) > 0);
                if (!wordExists)
                {
                    cmd.CommandText = "SELECT position FROM TextContent WHERE cards_id=@id AND side=@side AND type=@type ORDER BY position DESC";
                    cmd.Parameters.Add("@id", id);
                    cmd.Parameters.Add("@side", side.ToString());
                    cmd.Parameters.Add("@type", type.ToString());

                    int currentPos = 0;
                    object retval = MSSQLCEConn.ExecuteScalar(cmd);
                    if (retval != DBNull.Value)
                        currentPos = Convert.ToInt32(retval);
                    cmd.Parameters.Clear();

                    cmd.CommandText = @"INSERT INTO TextContent (cards_id, text, side, type, position, is_default) VALUES (@id, @text, @side, @type, @position, @isdefault); SELECT @@IDENTITY;";
                    cmd.Parameters.Add("@id", id);
                    cmd.Parameters.Add("@text", word.Word);
                    cmd.Parameters.Add("@side", side.ToString());
                    cmd.Parameters.Add("@type", type.ToString());
                    cmd.Parameters.Add("@position", currentPos + 10);
                    cmd.Parameters.Add("@isdefault", word.Default);
                    MSSQLCEConn.ExecuteNonQuery(cmd);
                }

                Parent.CurrentUser.Cache.Uncache(ObjectLifetimeIdentifier.GetIdentifier(ObjectLifetimeIdentifier.GetCacheObject(side, type), id));
            }
        }
Пример #43
0
 protected WordValidator(IWord word)
 {
     Debug.Assert(word != null);
     this.word = word;
     Hook(word);
 }
Пример #44
0
 protected internal MeaningWordLookupValidator(IWord parentWord, IMeaning meaning, WordCollection childrenWords, LookupData lookup)
     : base(lookup)
 {
     Debug.Assert(parentWord != null);
     Debug.Assert(meaning != null);
     Debug.Assert(childrenWords != null);
     this.parentWord = parentWord;
     this.meaning = meaning;
     this.childrenWords = childrenWords;
 }
Пример #45
0
 protected MeaningValidator(IWord word, IMeaning meaning)
 {
     Debug.Assert(word != null);
     this.word = word;
     Debug.Assert(meaning != null);
     this.meaning = meaning;
     Hook(meaning.Translations);
     Hook(meaning.Synonyms);
     Hook(meaning.Antonyms);
     Hook(meaning.Categories);
     Hook(meaning);
 }
Пример #46
0
 protected internal InsertWordValidator(IWord word)
     : base(word)
 {
     Validate();
 }
Пример #47
0
 protected internal InsertMeaningWordLookupValidator(IWord parentWord, IMeaning meaning, WordCollection childrenWords, LookupData lookup)
     : base(parentWord, meaning, childrenWords, lookup)
 {
     Validate();
 }
Пример #48
0
 protected override void InsertItem(int index, IWord item)
 {
     VerifySameVocabulary(item);
     VerifyDuplicateItem(item);
     base.InsertItem(index, item);
 }
Пример #49
0
 public HelpCommand(IWord word)
 {
     this.Word = word;
 }
Пример #50
0
 protected internal EditMeaningWordLookupValidator(IWord parentWord, IMeaning meaning, WordCollection childrenWords, LookupData lookup)
     : base(parentWord, meaning, childrenWords, lookup)
 {
     WordItem item = (WordItem)this.lookup.Data;
     this.originalWord = item.Word;
     Validate();
 }
Пример #51
0
 protected internal EditMeaningValidator(IWord word, IMeaning meaning, IMeaning meaningOriginal)
     : base(word, meaning)
 {
     Debug.Assert(meaningOriginal != null);
     this.meaningOriginal = meaningOriginal;
     Validate();
 }
Пример #52
0
 public WordItem(IWord word)
 {
     Debug.Assert(word != null);
     this.word = word;
 }
Пример #53
0
 private void VerifySameVocabulary(IWord item)
 {
     Debug.Assert(item.Vocabulary == this.meaning.Vocabulary);
     if (item.Vocabulary != this.meaning.Vocabulary)
     {
         throw new InternalDataException();
     }
 }
Пример #54
0
 private void VerifyDuplicateItem(IWord item)
 {
     if (this.IndexOf(item) >= 0)
     {
         throw new DuplicateWordException(item);
     }
 }
Пример #55
0
 protected override void SetItem(int index, IWord item)
 {
     if (!this[index].Equals(item))
     {
         VerifySameVocabulary(item);
         VerifyDuplicateItem(item);
         base.SetItem(index, item);
     }
 }
Пример #56
0
 public int CompareTo(IWord other)
 {
     return this.Occurrences - other.Occurrences;
 }
        /// <summary>
        /// Counts the number of letters still not guessed. 
        /// </summary>
        /// <param name="word">IWord word object.</param>
        /// <returns></returns>
        private int LettersLeft(IWord word)
        {
            int countLeftLetters = 0;
            foreach (var letter in word.Content)
            {
                if (!letter.IsFound)
                {
                    countLeftLetters++;
                }
            }

            return countLeftLetters;
        }
Пример #58
0
 protected internal InsertMeaningValidator(IWord word, IMeaning meaning)
     : base(word, meaning)
 {
     Validate();
 }
Пример #59
0
 protected internal EditWordValidator(IWord word, IWord wordOriginal)
     : base(word)
 {
     Debug.Assert(wordOriginal != null);
     this.wordOriginal = wordOriginal;
     Validate();
 }
Пример #60
0
 public override bool Remove(IWord item)
 {
     return (this as ObservableCollection<IWord>).Remove(item);
 }