Exemplo n.º 1
0
        private static RepresentationArea GetOrCreateArea(StudyLanguageContext c,
                                                          long representationId,
                                                          long wordTranslationId,
                                                          RepresentationAreaForUser areaForUser)
        {
            RepresentationArea representationArea = c.RepresentationArea
                                                    .FirstOrDefault(e => e.RepresentationId == representationId && e.WordTranslationId == wordTranslationId);

            if (representationArea == null)
            {
                representationArea = new RepresentationArea {
                    RepresentationId  = representationId,
                    WordTranslationId = wordTranslationId
                };
                c.RepresentationArea.Add(representationArea);
            }

            representationArea.LeftUpperX   = areaForUser.LeftUpperCorner.X;
            representationArea.LeftUpperY   = areaForUser.LeftUpperCorner.Y;
            representationArea.RightBottomX = areaForUser.RightBottomCorner.X;
            representationArea.RightBottomY = areaForUser.RightBottomCorner.Y;
            c.SaveChanges();

            return(representationArea);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Получает представление по названию
        /// </summary>
        /// <param name="userLanguages">языковые настройки пользователя</param>
        /// <param name="title">название представления</param>
        /// <returns>представление или null если не найдено</returns>
        public RepresentationForUser GetWithAreas(UserLanguages userLanguages, string title)
        {
            long sourceLanguageId      = userLanguages.From.Id;
            long translationLanguageId = userLanguages.To.Id;

            RepresentationForUser result = Adapter.ReadByContext(c => {
                var representationsQuery = (from r in c.Representation
                                            join ra in c.RepresentationArea on r.Id equals
                                            ra.RepresentationId
                                            join wt in c.WordTranslation on ra.WordTranslationId equals wt.Id
                                            join w1 in c.Word on wt.WordId1 equals w1.Id
                                            join w2 in c.Word on wt.WordId2 equals w2.Id
                                            where r.Title == title && r.LanguageId == _languageId &&
                                            ((w1.LanguageId == sourceLanguageId &&
                                              w2.LanguageId == translationLanguageId)
                                             ||
                                             (w1.LanguageId == translationLanguageId &&
                                              w2.LanguageId == sourceLanguageId))
                                            orderby ra.Rating descending
                                            select new { r, ra, w1, w2 });
                var representationsInfos = representationsQuery.AsEnumerable();
                var firstRepresentation  = representationsInfos.FirstOrDefault();
                if (firstRepresentation == null)
                {
                    return(null);
                }
                var innerResult = new RepresentationForUser(firstRepresentation.r);
                foreach (var representationsInfo in representationsInfos)
                {
                    RepresentationArea repArea = representationsInfo.ra;

                    Tuple <PronunciationForUser, PronunciationForUser> tuple =
                        GroupingHelper.GroupByLanguages(sourceLanguageId,
                                                        representationsInfo.w1,
                                                        representationsInfo.w2);

                    var area = new RepresentationAreaForUser(repArea)
                    {
                        Source = tuple.Item1, Translation = tuple.Item2
                    };
                    innerResult.AddArea(area);
                }
                return(innerResult);
            });

            return(result);
        }
Exemplo n.º 3
0
        public RepresentationForUser GetOrCreate(RepresentationForUser representationForUser)
        {
            if (IsInvalid(representationForUser))
            {
                return(null);
            }

            bool isSuccess = true;
            RepresentationForUser result = null;

            Adapter.ActionByContext(c => {
                result = GetOrCreateRepresentation(representationForUser, c);
                if (result == null)
                {
                    LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                        "RepresentationsQuery.GetOrCreate не удалось создать представление! Название: {0}, изображение: {1}",
                        representationForUser.Title,
                        representationForUser.Image != null
                            ? representationForUser.Image.Length.ToString(CultureInfo.InvariantCulture)
                            : "<NULL>");
                    isSuccess = false;
                    return;
                }

                var wordsQuery = new WordsQuery();
                foreach (RepresentationAreaForUser areaForUser in representationForUser.Areas)
                {
                    long wordTranslationId = wordsQuery.GetIdByWordsForUser(areaForUser.Source, areaForUser.Translation);
                    if (IdValidator.IsInvalid(wordTranslationId))
                    {
                        LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                            "RepresentationsQuery.GetOrCreate не найти связку для слов!" +
                            "Id представления: {0}, слово источник {1}, слово перевод {2}",
                            result.Id, areaForUser.Source.Text, areaForUser.Translation.Text);
                        isSuccess = false;
                        continue;
                    }

                    RepresentationArea representationArea = GetOrCreateArea(c, result.Id, wordTranslationId, areaForUser);
                    if (IdValidator.IsInvalid(representationArea.Id))
                    {
                        LoggerWrapper.LogTo(LoggerName.Errors).ErrorFormat(
                            "RepresentationsQuery.GetOrCreate не удалось создать область представления! " +
                            "Id представления: {0}, левый верхний угол: {1}, правый нижний угол: {2}, исходное слово {3}, слово перевод {4}",
                            result.Id, areaForUser.LeftUpperCorner, areaForUser.RightBottomCorner,
                            areaForUser.Source.Text,
                            areaForUser.Translation.Text);
                        isSuccess = false;
                        continue;
                    }
                    var newRepresentationArea = new RepresentationAreaForUser(representationArea)
                    {
                        Source = areaForUser.Source, Translation = areaForUser.Translation
                    };
                    result.AddArea(newRepresentationArea);
                }

                if (isSuccess)
                {
                    //удалить слова из группы, которые не были переданы в этот раз в группу
                    DeleteOldVisualWords(c, result);
                }
            });
            return(isSuccess ? result : null);
        }
Exemplo n.º 4
0
        public void Create(string fileName, string pathToImagePattern)
        {
            var csvReader = new CsvReader(fileName);

            var      languages            = new LanguagesQuery(LanguageShortName.Unknown, LanguageShortName.Unknown);
            Language from                 = languages.GetByShortName(_from);
            Language to                   = languages.GetByShortName(LanguageShortName.Ru);
            var      representationsQuery = new RepresentationsQuery(from.Id);

            string[] line = csvReader.ReadLine();
            if (line.Length < 1 || string.IsNullOrEmpty(line[0]))
            {
                Console.WriteLine("Некорректная первая строка в файле {0}!", fileName);
                return;
            }

            int imageIndex = 0;

            if (line.Length >= 2 && !string.IsNullOrEmpty(line[1]))
            {
                imageIndex = 1;
            }

            string imageFileName = string.Format(pathToImagePattern, line[imageIndex].Trim());
            Image  image         = Image.FromFile(imageFileName);
            var    memoryStream  = new MemoryStream();

            image.Save(memoryStream, ImageFormat.Jpeg);
            byte[] imageBytes = memoryStream.ToArray();

            string visualDictionaryName = line[0];

            byte?widthPercent = null;

            if (line.Length > 2)
            {
                byte w;
                if (byte.TryParse(line[2], out w) && w > 0 && w <= 100)
                {
                    widthPercent = w;
                }
            }
            visualDictionaryName = char.ToUpper(visualDictionaryName[0]) + visualDictionaryName.Substring(1);

            var representationForUser = new RepresentationForUser(IdValidator.INVALID_ID, visualDictionaryName,
                                                                  imageBytes,
                                                                  new Size(image.Size.Width, image.Size.Height),
                                                                  widthPercent);
            bool hasErrors = false;

            do
            {
                line = csvReader.ReadLine();
                if (line != null)
                {
                    if (line.Length < 6)
                    {
                        hasErrors = true;
                        break;
                    }

                    PronunciationForUser englishWord = CreateWordForUser(line[0], from);
                    PronunciationForUser russianWord = CreateWordForUser(line[1], to);

                    Point leftTopPoint     = CreatePoint(line[2], line[3]);
                    Point rightBottomPoint = CreatePoint(line[4], line[5]);

                    if (englishWord == null || russianWord == null || leftTopPoint == null || rightBottomPoint == null)
                    {
                        hasErrors = true;
                        break;
                    }

                    var representationArea = new RepresentationAreaForUser(IdValidator.INVALID_ID, leftTopPoint,
                                                                           rightBottomPoint)
                    {
                        Source = russianWord, Translation = englishWord
                    };
                    representationForUser.AddArea(representationArea);
                }
            } while (line != null);

            if (hasErrors)
            {
                Console.WriteLine("В файле {0} возникли ошибки! Файл не будет сохранен", fileName);
                return;
            }

            RepresentationForUser savedRepresentation = representationsQuery.GetOrCreate(representationForUser);

            Console.WriteLine("Визуальный словарь {0} {1}", representationForUser.Title,
                              savedRepresentation != null ? "сохранен" : "НЕ сохранен!");
        }