Example #1
0
        public ActionResult ShowSpecial(UserLanguages userLanguages,
                                        GroupForUser group,
                                        Func <GroupModel, SourceWithTranslation> foundGetterByModel)
        {
            if (WebSettingsConfig.Instance.IsSectionForbidden(SectionId))
            {
                return(RedirectToAction("Index", RouteConfig.MAIN_CONTROLLER_NAME));
            }

            GroupModel model = GetModel(userLanguages, group);

            if (model.IsInvalid())
            {
                return(GetRedirectToGroups());
            }
            SourceWithTranslation foundTranslation = foundGetterByModel(model);

            if (foundTranslation == null)
            {
                //искомые слова не найдены
                return(GetRedirectToGroups());
            }
            //искомый элемент найден - пометить как текущее
            model.SetCurrent(foundTranslation);
            return(View("Index", model));
        }
Example #2
0
        public ActionResult Translation(long userId, long?sourceId, long?translationId)
        {
            if (WebSettingsConfig.Instance.IsSectionForbidden(_sectionId))
            {
                return(RedirectToAction("Index", RouteConfig.MAIN_CONTROLLER_NAME));
            }

            if (!sourceId.HasValue || !translationId.HasValue)
            {
                return(RedirectToAction(_viewName));
            }
            List <SourceWithTranslation> sourceWithTranslations = _query.GetExact(userId,
                                                                                  sourceId.Value,
                                                                                  translationId.Value);

            if (sourceWithTranslations == null || sourceWithTranslations.Count == 0)
            {
                return(RedirectToAction(_viewName));
            }
            var languages = new LanguagesQuery(WebSettingsConfig.Instance.DefaultLanguageFrom,
                                               WebSettingsConfig.Instance.DefaultLanguageTo);
            SourceWithTranslation currentSentence = sourceWithTranslations.Single(e => e.IsCurrent);
            UserLanguages         userLanguages   = languages.GetLanguages(new List <long> {
                currentSentence.Source.LanguageId,
                currentSentence.Translation.LanguageId
            });

            if (UserLanguages.IsInvalid(userLanguages))
            {
                return(RedirectToAction(_viewName));
            }
            return(View(_viewName, new ShuffleModel(userLanguages, sourceWithTranslations)));
        }
Example #3
0
        private SourceWithTranslation CreateSentencencesWithTranslation(SentenceType type,
                                                                        PronunciationForUser source,
                                                                        PronunciationForUser translation,
                                                                        byte[] image = null,
                                                                        int?rating   = null)
        {
            SourceWithTranslation result = null;

            Adapter.ActionByContext(context => {
                Sentence sourceSentence      = GetOrAddSentenceToContext(source.LanguageId, source.Text, context);
                Sentence translationSentence = GetOrAddSentenceToContext(translation.LanguageId, translation.Text,
                                                                         context);
                context.SaveChanges();
                if (IdValidator.IsInvalid(sourceSentence.Id) || IdValidator.IsInvalid(translationSentence.Id))
                {
                    return;
                }
                var sentenceTranslation = new SentenceTranslation
                {
                    SentenceId1 = sourceSentence.Id, SentenceId2 = translationSentence.Id
                };
                SetSentenceTranslation(sentenceTranslation, type, image, rating);
                context.SentenceTranslation.Add(sentenceTranslation);
                context.SaveChanges();
                if (IdValidator.IsInvalid(sentenceTranslation.Id))
                {
                    return;
                }
                result = ConverterEntities.ConvertToSourceWithTranslation(sentenceTranslation.Id, sentenceTranslation.Image, source.LanguageId,
                                                                          sourceSentence,
                                                                          translationSentence);
            });
            return(result);
        }
        public void Create(string file)
        {
            var csvReader = new CsvReader(file);

            var      languages = new LanguagesQuery(LanguageShortName.Unknown, LanguageShortName.Unknown);
            Language from      = languages.GetByShortName(_from);
            Language russian   = languages.GetByShortName(LanguageShortName.Ru);

            //заголовок не учитывать
            string[] firstLine = csvReader.ReadLine();

            var popularWordsQuery = new PopularWordsQuery();

            do
            {
                string[] line = csvReader.ReadLine();
                if (line == null)
                {
                    break;
                }
                if (line.Length < 2)
                {
                    continue;
                }

                SourceWithTranslation popularWord = popularWordsQuery.GetOrCreate(CreateWordForUser(line[0], from),
                                                                                  CreateWordForUser(line[1], russian),
                                                                                  _type);
                Console.WriteLine("{0}: {1}", popularWord != null ? "Сохранено" : "Не сохранено",
                                  line.Aggregate((e1, e2) => e1 + " -> " + e2));
            } while (true);
        }
Example #5
0
        private SourceWithTranslation Create(GroupForUser groupForUser,
                                             SourceWithTranslation sentenceWithTranslation,
                                             int?rating)
        {
            SourceWithTranslation result = null;

            Adapter.ActionByContext(context => {
                var groupSentence = new GroupSentence
                {
                    SentenceTranslationId = sentenceWithTranslation.Id, GroupId = groupForUser.Id, Rating = rating
                };
                context.GroupSentence.Add(groupSentence);
                context.SaveChanges();
                if (IdValidator.IsValid(groupSentence.Id))
                {
                    result = new SourceWithTranslation();
                    result.Set(groupSentence.Id, sentenceWithTranslation.Source, sentenceWithTranslation.Translation);
                }
                else
                {
                    LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                        "GroupSentencesQuery.Create can't add sentence with translation for sentence with id {0}, translation with id {1}, rating {2}",
                        sentenceWithTranslation.Source.Id, sentenceWithTranslation.Translation.Id,
                        rating);
                }
            });
            return(result);
        }
Example #6
0
        protected override SourceWithTranslation GetBySourceAndTranslation(long userId,
                                                                           long sourceId,
                                                                           long translationId)
        {
            SourceWithTranslation result = Adapter.ReadByContext(c => {
                var sourceWithTranslation = (from s1 in c.Sentence
                                             join st in c.SentenceTranslation on s1.Id equals st.SentenceId1
                                             join s2 in c.Sentence on st.SentenceId2 equals s2.Id
                                             join ss in c.ShuffleSentence on st.Id equals ss.SentenceTranslationId
                                             where (ss.UserId == userId &&
                                                    ((st.SentenceId1 == sourceId &&
                                                      st.SentenceId2 == translationId)
                                                     ||
                                                     (st.SentenceId2 == sourceId &&
                                                      st.SentenceId1 == translationId)))
                                             select new { st.Id, st.Image, s1, s2 }).FirstOrDefault();

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

                long sourceLanguageId = sourceWithTranslation.s1.Id == sourceId
                                            ? sourceWithTranslation.s1.LanguageId
                                            : sourceWithTranslation.s2.LanguageId;
                return(ConverterEntities.ConvertToSourceWithTranslation(sourceWithTranslation.Id,
                                                                        sourceWithTranslation.Image,
                                                                        sourceLanguageId,
                                                                        sourceWithTranslation.s1,
                                                                        sourceWithTranslation.s2));
            });

            return(result);
        }
Example #7
0
        private void AssertConvertToItems(List <SourceWithTranslation> sourcesWithTranslation,
                                          List <List <Tuple <int, int> > > ranges)
        {
            List <GapsTrainerItem> items = _helper.ConvertToItems(sourcesWithTranslation);

            Assert.That(items.Count, Is.EqualTo(sourcesWithTranslation.Count));

            for (int i = 0; i < sourcesWithTranslation.Count; i++)
            {
                GapsTrainerItem       item = items[i];
                SourceWithTranslation sourceWithTranslation = sourcesWithTranslation[i];

                Assert.That(item, Is.Not.Null);
                Assert.That(item.Id, Is.EqualTo(sourceWithTranslation.Id));
                Assert.That(item.Original, Is.EqualTo(sourceWithTranslation.Source));
                Assert.That(item.Translation, Is.EqualTo(sourceWithTranslation.Translation));
                string textWithGaps = item.TextForUser;
                Assert.That(textWithGaps, Is.Not.Null);

                string sourceText = string.Join(" ",
                                                sourceWithTranslation.Source.Text.Split(new[] { ' ' },
                                                                                        StringSplitOptions.
                                                                                        RemoveEmptyEntries));
                Assert.That(textWithGaps.Length, Is.EqualTo(sourceText.Length));
                string[] words = textWithGaps.Split(' ');
                List <Tuple <int, int> > wordRanges = ranges[i];
                for (int wordIndex = 0; wordIndex < words.Length; wordIndex++)
                {
                    string           word  = words[wordIndex];
                    Tuple <int, int> range = wordRanges[wordIndex];
                    AssertWord(word, range.Item1, range.Item2);
                }
            }
        }
Example #8
0
        public SourceWithTranslation GetOrCreate(SentenceType type,
                                                 PronunciationForUser source,
                                                 PronunciationForUser translation,
                                                 byte[] image,
                                                 int?rating = null)
        {
            //TODO: проверять корректность параметров
            SourceWithTranslation result = null;

            Adapter.ActionByContext(context => {
                SentenceTranslation sentenceTranslation = GetSentenceTranslation(context, source, translation);
                if (sentenceTranslation != null)
                {
                    //обновить возможно изменившиеся поля
                    SetSentenceTranslation(sentenceTranslation, type, image, rating);
                    context.SaveChanges();
                    if (IdValidator.IsValid(sentenceTranslation.Id))
                    {
                        result = new SourceWithTranslation();
                        result.Set(sentenceTranslation.Id, source, translation);
                    }
                }
                else
                {
                    result = CreateSentencencesWithTranslation(type, source, translation, image, rating);
                }
            });
            return(result);
        }
Example #9
0
        private List <SourceWithTranslation> GetUserEntities(long userId, long sourceId, long translationId)
        {
            SourceWithTranslation userSentence = GetBySourceAndTranslation(userId, sourceId, translationId);

            if (userSentence == null)
            {
                return(new List <SourceWithTranslation>(0));
            }
            userSentence.IsCurrent = true;
            long sourceLanguageId      = userSentence.Source.LanguageId;
            long translationLanguageId = userSentence.Translation.LanguageId;

            var result = new List <SourceWithTranslation>();
            List <SourceWithTranslation> prev = GetPrevById(userId, userSentence.Id,
                                                            sourceLanguageId,
                                                            translationLanguageId, PORTION_SIZE);

            result.AddRange(prev);
            result.Add(userSentence);

            List <SourceWithTranslation> next = GetNextById(userId, userSentence.Id,
                                                            sourceLanguageId,
                                                            translationLanguageId, PORTION_SIZE);

            result.AddRange(next);
            return(result);
        }
Example #10
0
        private static SourceWithTranslation GetSource(string source, string translation = "translation bla-bla")
        {
            var result = new SourceWithTranslation();

            result.Set(84746, new PronunciationForUser(837, source, true, 31),
                       new PronunciationForUser(33, translation, false, 47));
            return(result);
        }
Example #11
0
        protected SourceWithTranslation FoundTranslation(string item1,
                                                         string item2,
                                                         GroupModel model)
        {
            SourceWithTranslation foundTranslation =
                model.ElemsWithTranslations.FirstOrDefault(
                    e => IsWordsEquals(item1, item2, e) || IsWordsEquals(item2, item1, e));

            return(foundTranslation);
        }
Example #12
0
        public static SourceWithTranslation ConvertToSourceWithTranslation(long id,
                                                                           byte[] image,
                                                                           PronunciationForUser pronunciation1,
                                                                           PronunciationForUser pronunciation2)
        {
            var result = new SourceWithTranslation();

            result.Set(id, pronunciation1, pronunciation2);
            result.HasImage = image != null && image.Length > 0;
            return(result);
        }
Example #13
0
        public void Write(SourceWithTranslation sourceWithTranslation, List <string> best, List <string> other)
        {
            var element = new XElement("item",
                                       new XElement("source", sourceWithTranslation.Source.Text),
                                       new XElement("translation", sourceWithTranslation.Translation.Text)
                                       );

            TranslationsToElement(element, "best", best);
            TranslationsToElement(element, "other", other);
            _xmlWriter.Write(element);
        }
Example #14
0
        public void ConvertVisualDictionaries()
        {
            LoadLanguages();

            var representationsQuery = new RepresentationsQuery(_userLanguages.To.Id);
            Dictionary <long, string> visibleDictionaries =
                representationsQuery.GetVisibleWithoutAreas().ToDictionary(e => e.Id, e => e.Title);

            foreach (var visualDictionary in visibleDictionaries)
            {
                long id = visualDictionary.Key;
                if (!visibleDictionaries.ContainsKey(id))
                {
                    continue;
                }

                string title    = visibleDictionaries[id];
                string fileName =
                    string.Format(@"C:\Projects\StudyLanguages\Источники визуального словаря\{0}\Xml\{1}.xml",
                                  _languageTo, title);

                if (File.Exists(fileName))
                {
                    Console.WriteLine("Визуальный словарь \"{0}\" уже существует - пропустить", title);
                    continue;
                }

                Console.WriteLine("Начали обрабатывать визуальный словарь \"{0}\"", title);

                RepresentationForUser representation = representationsQuery.GetWithAreas(_userLanguages,
                                                                                         visualDictionary.Value);
                if (representation == null)
                {
                    Console.WriteLine(
                        "Не удалось получить данные из словаря \"{0}\" - пропустить. Нажмите enter для продолжения...",
                        title);
                    Console.ReadLine();
                    continue;
                }
                List <SourceWithTranslation> words =
                    representation.Areas.Select(e => {
                    var sourceWithTranslation = new SourceWithTranslation();
                    sourceWithTranslation.Set(e.WordTranslationId, e.Source, e.Translation);
                    return(sourceWithTranslation);
                }).ToList();

                SaveConvertedWords(fileName, words);
            }

            Console.WriteLine(
                "Переконвертировали визуальные словари. Воспользовались дополнительными словарями {0} раз",
                _translator.CountExtraCalls);
        }
Example #15
0
        /// <summary>
        /// Возвращает урл для элемента
        /// <param group="linkId">идентификатор ссылки</param>
        /// <param group="item">элемент, для которого нужно получить ссылку</param>
        /// </summary>
        public LinkInfo GetLink(string patternUrl, LinkId linkId, SourceWithTranslation item)
        {
            string text;

            if (!_links.TryGetValue(linkId, out text))
            {
                return(null);
            }
            string url = item != null?_linkUrlGetter(patternUrl, item) : null;

            return(new LinkInfo(text, url ?? CommonConstants.EMPTY_LINK));
        }
Example #16
0
        /// <summary>
        /// Создает слова для группы
        /// </summary>
        /// <param name="groupForUser">группа, к которой нужно добавить слово</param>
        /// <param name="source">слово</param>
        /// <param name="translation">перевод</param>
        /// <param name="image">изображение для слова</param>
        /// <param name="rating">рейтинг</param>
        /// <returns>созданные слова для группы, или ничего</returns>
        public SourceWithTranslation GetOrCreate(GroupForUser groupForUser,
                                                 PronunciationForUser source,
                                                 PronunciationForUser translation,
                                                 byte[] image,
                                                 int?rating)
        {
            var sentencesQuery = new SentencesQuery();
            SourceWithTranslation sentenceWithTranslation = sentencesQuery.GetOrCreate(SentenceType.FromGroup, source,
                                                                                       translation, image,
                                                                                       null);

            if (sentenceWithTranslation == null || IdValidator.IsInvalid(sentenceWithTranslation.Id))
            {
                LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                    "GroupSentencesQuery.GetOrCreate can't add sentence {0} with translation {1}, image {2}, rating {3}",
                    source.Text, translation.Text,
                    image != null ? image.Length.ToString(CultureInfo.InvariantCulture) : "<NULL>", rating);
                return(null);
            }
            SourceWithTranslation result = Adapter.ReadByContext(c => {
                var wordsWithTranslationsQuery = (from s1 in c.Sentence
                                                  join st in c.SentenceTranslation on s1.Id equals st.SentenceId1
                                                  join gs in c.GroupSentence on st.Id equals gs.SentenceTranslationId
                                                  join s2 in c.Sentence on st.SentenceId2 equals s2.Id
                                                  where
                                                  gs.GroupId == groupForUser.Id &&
                                                  st.Id == sentenceWithTranslation.Id
                                                  select new { gs, st, s1, s2 });
                var firstRecord = wordsWithTranslationsQuery.AsEnumerable().FirstOrDefault();
                if (firstRecord == null)
                {
                    return(null);
                }
                //сохранить возможно изменившийся рейтинг
                GroupSentence groupSentence = firstRecord.gs;
                groupSentence.Rating        = rating;
                c.SaveChanges();

                SourceWithTranslation innerResult = ConvertToGroupSentenceWithTranslation(firstRecord.st.Id,
                                                                                          firstRecord.st.Image,
                                                                                          sentenceWithTranslation
                                                                                          .Source.LanguageId,
                                                                                          firstRecord.s1,
                                                                                          firstRecord.s2);
                return(innerResult);
            });

            if (result == null)
            {
                result = Create(groupForUser, sentenceWithTranslation, rating);
            }
            return(result);
        }
Example #17
0
        /// <summary>
        /// Получает count случайных энтитей с переводом
        /// </summary>
        /// <param name="userId">идентификатор пользователя</param>
        /// <param name="userLanguages">информация о языкых текущего пользователя</param>
        /// <param name="count">кол-во энтитей, которое необходимо получить</param>
        /// <returns>список энтитей перемешанных случайным образом</returns>
        public List <SourceWithTranslation> GetRandom(long userId,
                                                      UserLanguages userLanguages,
                                                      int count = PORTION_SIZE)
        {
            long sourceLanguageId               = userLanguages.From.Id;
            long translationLanguageId          = userLanguages.To.Id;
            List <SourceWithTranslation> result = GetSourceWithTranslations(userId, sourceLanguageId,
                                                                            translationLanguageId, count);

            if (NeedCreate(result))
            {
                //попробовать добавить новые энтити и вернуть большее кол-во энтитей
                result = GetMore(userId, count, result, sourceLanguageId, translationLanguageId);
            }

            SourceWithTranslation        currentEntity = result.FirstOrDefault();
            List <SourceWithTranslation> previous;

            if (currentEntity != null)
            {
                currentEntity.IsCurrent = true;
                previous = GetPrevById(userId, currentEntity.Id,
                                       sourceLanguageId,
                                       translationLanguageId,
                                       count);
            }
            else
            {
                LoggerWrapper.LogTo(LoggerName.Default).DebugFormat(
                    "BaseRandomQuery.GetRandom у пользователя {0} нет новых предложений для показа, может все просмотрел?",
                    userId);
                long maxId = GetMaxId(userId, sourceLanguageId, translationLanguageId);

                previous = IdValidator.IsValid(maxId)
                               ? GetPrevById(userId, maxId, sourceLanguageId, translationLanguageId, count)
                               : new List <SourceWithTranslation>(0);
                SourceWithTranslation last = previous.LastOrDefault();
                if (last != null)
                {
                    last.IsCurrent = true;
                }
                else
                {
                    LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                        "BaseRandomQuery.GetRandom для пользователя {0} нет предложений для показа", userId);
                }
            }
            result.InsertRange(0, previous);
            return(result);
        }
Example #18
0
        protected override bool Create(GroupForUser groupForUser,
                                       string[] line,
                                       Language english,
                                       Language russian,
                                       byte[] image,
                                       int?rating)
        {
            IGroupWordsQuery      groupWordsQuery     = new GroupWordsQuery();
            SourceWithTranslation wordWithTranslation =
                groupWordsQuery.GetOrCreate(groupForUser, CreateWordForUser(line[0], english),
                                            CreateWordForUser(line[1], russian), image, rating);
            bool isSuccess = wordWithTranslation != null;

            return(isSuccess);
        }
Example #19
0
        /// <summary>
        /// Создает слова для группы
        /// </summary>
        /// <param name="groupForUser">группа, к которой нужно добавить слово</param>
        /// <param name="source">слово</param>
        /// <param name="translation">перевод</param>
        /// <param name="image">изображение для слова</param>
        /// <param name="rating">рейтинг</param>
        /// <returns>созданные слова для группы, или ничего</returns>
        public SourceWithTranslation GetOrCreate(GroupForUser groupForUser,
                                                 PronunciationForUser source,
                                                 PronunciationForUser translation,
                                                 byte[] image,
                                                 int?rating)
        {
            var wordsQuery = new WordsQuery();
            WordWithTranslation wordWithTranslation = wordsQuery.GetOrCreate(source, translation, image,
                                                                             WordType.Default, null);

            if (wordWithTranslation == null)
            {
                return(null);
            }
            SourceWithTranslation result = Adapter.ReadByContext(c => {
                var wordsWithTranslationsQuery = (from w1 in c.Word
                                                  join wt in c.WordTranslation on w1.Id equals wt.WordId1
                                                  join gw in c.GroupWord on wt.Id equals gw.WordTranslationId
                                                  join w2 in c.Word on wt.WordId2 equals w2.Id
                                                  where gw.GroupId == groupForUser.Id && wt.Id == wordWithTranslation.Id
                                                  select new { gw, wt, w1, w2 });
                var firstRecord = wordsWithTranslationsQuery.AsEnumerable().FirstOrDefault();
                if (firstRecord == null)
                {
                    return(null);
                }
                //сохранить возможно изменившийся рейтинг
                GroupWord groupWord = firstRecord.gw;
                groupWord.Rating    = rating;
                c.SaveChanges();

                SourceWithTranslation innerResult = ConverterEntities.ConvertToSourceWithTranslation(firstRecord.wt.Id,
                                                                                                     firstRecord.wt.
                                                                                                     Image,
                                                                                                     wordWithTranslation
                                                                                                     .Source.
                                                                                                     LanguageId,
                                                                                                     firstRecord.w1,
                                                                                                     firstRecord.w2);
                return(innerResult);
            });

            if (result == null)
            {
                result = Create(groupForUser, wordWithTranslation, rating);
            }
            return(result);
        }
Example #20
0
        private bool CreateExamples(IEnumerable <ComparisonRuleExampleForUser> ruleExamples,
                                    ComparisonRuleForUser newComparisonRuleForUser,
                                    StudyLanguageContext c)
        {
            bool result           = true;
            int  orderRuleExample = 1;

            foreach (ComparisonRuleExampleForUser ruleExample in ruleExamples)
            {
                SourceWithTranslation example = ruleExample.Example;
                SourceWithTranslation sentenceWithTranslation =
                    _sentencesQuery.GetOrCreate(SentenceType.ComparisonExample,
                                                example.Source,
                                                example.Translation,
                                                null);
                long sentenceTranslationId = sentenceWithTranslation.Id;
                if (IdValidator.IsInvalid(sentenceTranslationId))
                {
                    LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                        "ComparisonsQuery.GetOrCreate не удалось создать предложения примера! " +
                        "Предложение: {0}, перевод предложения {1}",
                        sentenceWithTranslation.Source.Text, sentenceWithTranslation.Translation.Text);
                    result = false;
                    continue;
                }

                long ruleId = newComparisonRuleForUser.Id;
                ComparisonRuleExample comparisonRuleExample = GetOrCreateComparisonRuleExample(ruleId,
                                                                                               sentenceTranslationId,
                                                                                               ruleExample.Description,
                                                                                               orderRuleExample++, c);

                if (IdValidator.IsInvalid(comparisonRuleExample.Id))
                {
                    LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                        "ComparisonsQuery.GetOrCreate не удалось создать пример для правила сравнения! " +
                        "Id примера: {0}, sentenceWithTranslationId {1}",
                        ruleId, sentenceTranslationId);
                    result = false;
                    continue;
                }

                var exampleForUser = new ComparisonRuleExampleForUser(comparisonRuleExample, sentenceWithTranslation);
                newComparisonRuleForUser.AddExample(exampleForUser);
            }
            return(result);
        }
Example #21
0
        public List <SourceWithTranslation> GetNextPortion(long userId,
                                                           long id,
                                                           UserLanguages userLanguages,
                                                           int count = PORTION_SIZE)
        {
            if (UserLanguages.IsInvalid(userLanguages))
            {
                return(new List <SourceWithTranslation>(0));
            }
            long sourceLanguageId               = userLanguages.From.Id;
            long translationLanguageId          = userLanguages.To.Id;
            List <SourceWithTranslation> result = GetNextById(userId, id, sourceLanguageId,
                                                              translationLanguageId, count);
            bool needCreate = NeedCreate(result);

            if (!needCreate)
            {
                return(result);
            }
            //попробовать добавить новые предложения и вернуть большее кол-во предложений
            bool isInserted = InsertShuffle(userId, sourceLanguageId, translationLanguageId, count);

            if (!isInserted)
            {
                return(result);
            }
            //result = GetNextById(userUnique, id, sourceLanguageId, translationLanguageId, count);
            SourceWithTranslation lastSentence = result.LastOrDefault();

            if (lastSentence == null)
            {
                //нет ни одного предложения - даже после вставки:(
                LoggerWrapper.LogTo(LoggerName.Default).InfoFormat(
                    "BaseRandomQuery.GetNextPortion для пользователя {0} нет ни одного предложения даже после вставки. Может все просмотрел?",
                    userId);
                return(result);
            }

            //получаем энтити - которые вставили
            List <SourceWithTranslation> nextPortion = GetNextById(userId, lastSentence.Id,
                                                                   sourceLanguageId,
                                                                   translationLanguageId, count);

            result.AddRange(nextPortion);
            return(result);
        }
Example #22
0
        private ComparisonRuleExampleForUser GetComparisonExampleForUser(XElement xExample)
        {
            string source             = GetChildElementValue(xExample, "source");
            string translation        = GetChildElementValue(xExample, "translation");
            string descriptionExample = GetChildElementValue(xExample, "description");

            var sourceWithTranslation = new SourceWithTranslation();

            sourceWithTranslation.Set(IdValidator.INVALID_ID,
                                      new PronunciationForUser(IdValidator.INVALID_ID,
                                                               TextFormatter.FirstUpperCharAndTrim(source), false,
                                                               _englishId),
                                      new PronunciationForUser(IdValidator.INVALID_ID,
                                                               TextFormatter.FirstUpperCharAndTrim(translation), false,
                                                               _russianId));
            return(new ComparisonRuleExampleForUser(sourceWithTranslation,
                                                    TextFormatter.FirstUpperCharAndTrim(descriptionExample)));
        }
Example #23
0
        private SourceWithTranslation Create(WordWithTranslation wordWithTranslation, int type)
        {
            SourceWithTranslation result = null;

            Adapter.ActionByContext(context => {
                var popularWord = new PopularWord
                {
                    WordTranslationId = wordWithTranslation.Id, Type = type
                };
                context.PopularWord.Add(popularWord);
                context.SaveChanges();
                if (IdValidator.IsValid(popularWord.Id))
                {
                    result = new SourceWithTranslation();
                    result.Set(popularWord.Id, wordWithTranslation.Source, wordWithTranslation.Translations[0]);
                }
            });
            return(result);
        }
Example #24
0
        /// <summary>
        /// Создает слова по типу популярности
        /// </summary>
        /// <param name="source">слово</param>
        /// <param name="translation">перевод</param>
        /// <param name="type">тип популярности</param>
        /// <returns>созданные слова для группы, или ничего</returns>
        public SourceWithTranslation GetOrCreate(PronunciationForUser source,
                                                 PronunciationForUser translation,
                                                 PopularWordType type)
        {
            var wordsQuery = new WordsQuery();
            WordWithTranslation wordWithTranslation = wordsQuery.GetOrCreate(source, translation, null, WordType.Default,
                                                                             null);

            if (wordWithTranslation == null)
            {
                return(null);
            }
            var parsedType = (int)type;
            SourceWithTranslation result = Adapter.ReadByContext(c => {
                var wordsWithTranslationsQuery = (from w1 in c.Word
                                                  join wt in c.WordTranslation on w1.Id equals wt.WordId1
                                                  join pw in c.PopularWord on wt.Id equals pw.WordTranslationId
                                                  join w2 in c.Word on wt.WordId2 equals w2.Id
                                                  where pw.Type == parsedType && wt.Id == wordWithTranslation.Id
                                                  select new { wt, w1, w2 });
                var firstRecord = wordsWithTranslationsQuery.AsEnumerable().FirstOrDefault();
                if (firstRecord == null)
                {
                    return(null);
                }

                SourceWithTranslation innerResult = ConverterEntities.ConvertToSourceWithTranslation(firstRecord.wt.Id,
                                                                                                     firstRecord.wt.
                                                                                                     Image,
                                                                                                     wordWithTranslation
                                                                                                     .Source.
                                                                                                     LanguageId,
                                                                                                     firstRecord.w1,
                                                                                                     firstRecord.w2);
                return(innerResult);
            });

            if (result == null)
            {
                result = Create(wordWithTranslation, parsedType);
            }
            return(result);
        }
Example #25
0
        public void Fill()
        {
            var csvReader = new CsvReader(@"C:\Projects\StudyLanguages\1.csv");

            string[] line;
            var      sentences = new SentencesQuery();
            var      languages = new LanguagesQuery(LanguageShortName.Unknown, LanguageShortName.Unknown);
            Language english   = languages.GetByShortName(LanguageShortName.En);
            Language russian   = languages.GetByShortName(LanguageShortName.Ru);

            do
            {
                line = csvReader.ReadLine();
                if (line != null)
                {
                    SourceWithTranslation sentenceWithTranslation =
                        sentences.GetOrCreate(SentenceType.Separate,
                                              new PronunciationForUser(IdValidator.INVALID_ID, line[0],
                                                                       false, english.Id),
                                              new PronunciationForUser(IdValidator.INVALID_ID, line[1],
                                                                       false, russian.Id),
                                              null, null);
                    Console.WriteLine("{0}: {1}", sentenceWithTranslation != null ? "Сохранено" : "Не сохранено",
                                      line.Aggregate((e1, e2) => e1 + " -> " + e2));
                }
            } while (line != null);

            /* for (int i = 1; i <= 100000; i++) {
             *  SentenceWithTranslation sentenceWithTranslation =
             *      sentences.CreateSentencencesWithTranslation(english, "Test sentence number " + i, russian,
             *                                                  "Тестовое предложение № " + i);
             *  if (sentenceWithTranslation == null) {
             *      Console.WriteLine("Не удалось сохранить предложение {0}. Нажмите Enter...", i);
             *      Console.ReadLine();
             *  }
             *
             *  if (i % 10000 == 0) {
             *      Console.WriteLine("Сохранено {0} предложений", i);
             *  }
             * }*/
        }
Example #26
0
        private SourceWithTranslation Create(GroupForUser groupForUser,
                                             WordWithTranslation wordWithTranslation,
                                             int?rating)
        {
            SourceWithTranslation result = null;

            Adapter.ActionByContext(context => {
                var groupWord = new GroupWord
                {
                    WordTranslationId = wordWithTranslation.Id, GroupId = groupForUser.Id, Rating = rating
                };
                context.GroupWord.Add(groupWord);
                context.SaveChanges();
                if (IdValidator.IsValid(groupWord.Id))
                {
                    result = new SourceWithTranslation();
                    result.Set(groupWord.Id, wordWithTranslation.Source, wordWithTranslation.Translations[0]);
                }
            });
            return(result);
        }
Example #27
0
        public Dictionary <long, List <SourceWithTranslation> > GetForAllGroups(UserLanguages userLanguages)
        {
            long sourceLanguageId      = userLanguages.From.Id;
            long translationLanguageId = userLanguages.To.Id;
            Dictionary <long, List <SourceWithTranslation> > result = Adapter.ReadByContext(c => {
                var sentencesWithTranslationsQuery = (from s1 in c.Sentence
                                                      join st in c.SentenceTranslation on s1.Id equals st.SentenceId1
                                                      join gw in c.GroupSentence on st.Id equals
                                                      gw.SentenceTranslationId
                                                      join s2 in c.Sentence on st.SentenceId2 equals s2.Id
                                                      where ((s1.LanguageId == sourceLanguageId &&
                                                              s2.LanguageId == translationLanguageId)
                                                             ||
                                                             (s1.LanguageId == translationLanguageId &&
                                                              s2.LanguageId == sourceLanguageId))
                                                      orderby gw.GroupId, gw.Rating descending, gw.Id
                                                      select new { gw.GroupId, st, s1, s2 });

                var innerResult = new Dictionary <long, List <SourceWithTranslation> >();
                foreach (var item in sentencesWithTranslationsQuery.AsEnumerable())
                {
                    long groupId = item.GroupId;
                    List <SourceWithTranslation> sentencesInGroup;
                    if (!innerResult.TryGetValue(groupId, out sentencesInGroup))
                    {
                        sentencesInGroup = new List <SourceWithTranslation>();
                        innerResult.Add(groupId, sentencesInGroup);
                    }

                    SourceWithTranslation sentence = ConvertToGroupSentenceWithTranslation(item.st.Id,
                                                                                           item.st.Image,
                                                                                           sourceLanguageId,
                                                                                           item.s1, item.s2);
                    sentencesInGroup.Add(sentence);
                }
                return(innerResult);
            });

            return(result);
        }
Example #28
0
        public Dictionary <long, List <SourceWithTranslation> > GetForAllGroups(UserLanguages userLanguages)
        {
            long sourceLanguageId      = userLanguages.From.Id;
            long translationLanguageId = userLanguages.To.Id;
            Dictionary <long, List <SourceWithTranslation> > result = Adapter.ReadByContext(c => {
                var wordsWithTranslationsQuery = (from w1 in c.Word
                                                  join wt in c.WordTranslation on w1.Id equals wt.WordId1
                                                  join gw in c.GroupWord on wt.Id equals gw.WordTranslationId
                                                  join w2 in c.Word on wt.WordId2 equals w2.Id
                                                  where ((w1.LanguageId == sourceLanguageId &&
                                                          w2.LanguageId == translationLanguageId)
                                                         ||
                                                         (w1.LanguageId == translationLanguageId &&
                                                          w2.LanguageId == sourceLanguageId))
                                                  orderby gw.GroupId, gw.Rating descending, gw.Id
                                                  select new { gw.GroupId, wt, w1, w2 });

                var innerResult = new Dictionary <long, List <SourceWithTranslation> >();
                foreach (var e in wordsWithTranslationsQuery.AsEnumerable())
                {
                    long groupId = e.GroupId;
                    List <SourceWithTranslation> wordsInGroup;
                    if (!innerResult.TryGetValue(groupId, out wordsInGroup))
                    {
                        wordsInGroup = new List <SourceWithTranslation>();
                        innerResult.Add(groupId, wordsInGroup);
                    }
                    SourceWithTranslation groupWord = ConverterEntities.ConvertToSourceWithTranslation(e.wt.Id,
                                                                                                       e.wt.Image,
                                                                                                       sourceLanguageId,
                                                                                                       e.w1, e.w2);
                    wordsInGroup.Add(groupWord);
                }
                return(innerResult);
            });

            return(result);
        }
Example #29
0
        public List <SourceWithTranslation> GetExact(long userId, long sourceId, long translationId)
        {
            if (IdValidator.IsValid(userId))
            {
                //пользователя знаем - может быть это его энтити - попробуем найти
                List <SourceWithTranslation> result = GetUserEntities(userId, sourceId, translationId);
                if (result.Count > 0)
                {
                    return(result);
                }
            }
            Tuple <long, byte[], PronunciationEntity, PronunciationEntity> sourceAndTranslationWithId =
                GetBySourceAndTranslation(sourceId, translationId);
            long id = sourceAndTranslationWithId.Item1;
            PronunciationEntity source      = sourceAndTranslationWithId.Item3;
            PronunciationEntity translation = sourceAndTranslationWithId.Item4;

            if (IdValidator.IsInvalid(id) || source == null || translation == null)
            {
                LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                    "BaseRandomQuery.GetExact для пользователя {0} не удалось получить данные с идентификаторами {1} и {2}",
                    userId, sourceId, translationId);
                return(null);
            }
            long sourceLanguageId          = source.Id == sourceId ? source.LanguageId : translation.LanguageId;
            SourceWithTranslation sentence = ConverterEntities.ConvertToSourceWithTranslation(id,
                                                                                              sourceAndTranslationWithId
                                                                                              .Item2,
                                                                                              sourceLanguageId, source,
                                                                                              translation);

            sentence.IsCurrent = true;
            return(new List <SourceWithTranslation> {
                sentence
            });
        }
Example #30
0
        protected override SourceWithTranslation GetBySourceAndTranslation(long userId,
                                                                           long sourceId,
                                                                           long translationId)
        {
            SourceWithTranslation result = Adapter.ReadByContext(c => {
                var sourceWithTranslation = (from w1 in c.Word
                                             join wt in c.WordTranslation on w1.Id equals wt.WordId1
                                             join w2 in c.Word on wt.WordId2 equals w2.Id
                                             join sw in c.ShuffleWord on wt.Id equals sw.WordTranslationId
                                             where (sw.UserId == userId &&
                                                    sw.Type == _shuffleType &&
                                                    (w1.Type & _wordType) == _wordType &&
                                                    (w2.Type & _wordType) == _wordType &&
                                                    ((wt.WordId1 == sourceId &&
                                                      wt.WordId2 == translationId)
                                                     ||
                                                     (wt.WordId2 == sourceId &&
                                                      wt.WordId1 == translationId)))
                                             orderby sw.Id descending
                                             select new { sw.WordTranslationId, wt.Image, w1, w2 }).FirstOrDefault();

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

                long sourceLanguageId = sourceWithTranslation.w1.Id == sourceId
                                            ? sourceWithTranslation.w1.LanguageId
                                            : sourceWithTranslation.w2.LanguageId;
                return(ConverterEntities.ConvertToSourceWithTranslation(sourceWithTranslation.WordTranslationId,
                                                                        sourceWithTranslation.Image, sourceLanguageId,
                                                                        sourceWithTranslation.w1, sourceWithTranslation.w2));
            });

            return(result);
        }