Ejemplo n.º 1
0
        private RepresentationForUser GetOrCreateRepresentation(RepresentationForUser representationForUser,
                                                                StudyLanguageContext c)
        {
            Size           size           = representationForUser.Size;
            Representation representation =
                c.Representation.FirstOrDefault(
                    e => e.Title == representationForUser.Title && e.LanguageId == _languageId);

            if (representation == null)
            {
                representation = new Representation {
                    Title      = representationForUser.Title,
                    IsVisible  = true,
                    LanguageId = _languageId
                };
                c.Representation.Add(representation);
            }

            representation.Image        = representationForUser.Image;
            representation.Width        = size.Width;
            representation.Height       = size.Height;
            representation.WidthPercent = representationForUser.WidthPercent;
            representation.LastModified = DateTime.Now;
            c.SaveChanges();

            return(IdValidator.IsValid(representation.Id) ? new RepresentationForUser(representation) : null);
        }
        public ActionResult Index(UserLanguages userLanguages, string group)
        {
            if (WebSettingsConfig.Instance.IsSectionForbidden(SectionId.VisualDictionary))
            {
                return(RedirectToAction("Index", RouteConfig.MAIN_CONTROLLER_NAME));
            }

            if (UserLanguages.IsInvalid(userLanguages))
            {
                return(RedirectToAction("Index", RouteConfig.VISUAL_DICTIONARIES_CONTROLLER_NAME));
            }
            RepresentationForUser representationForUser = GetRepresentationForUser(userLanguages, group);

            if (representationForUser == null)
            {
                return(RedirectToActionPermanent("Index", RouteConfig.VISUAL_DICTIONARIES_CONTROLLER_NAME));
            }

            long languageId                       = WebSettingsConfig.Instance.GetLanguageFromId();
            var  crossReferencesQuery             = new CrossReferencesQuery(languageId);
            List <CrossReference> crossReferences = crossReferencesQuery.GetReferences(representationForUser.Id,
                                                                                       CrossReferenceType.
                                                                                       VisualDictionary);
            var model = new VisualDictionaryModel(userLanguages, representationForUser);

            model.CrossReferencesModel = new CrossReferencesModel(representationForUser.Title,
                                                                  CrossReferenceType.VisualDictionary, crossReferences);
            return(View(model));
        }
Ejemplo n.º 3
0
        public static int GetRecommendedImageWidth(RepresentationForUser representation)
        {
            const decimal MAX_WIDTH = 50;

            if (representation.WidthPercent.HasValue)
            {
                return(representation.WidthPercent.Value);
            }

            Size size = representation.Size;

            if (size.Width >= size.Height)
            {
                return(44);
            }
            decimal ratio = size.Width / (decimal)size.Height;

            /*if (ratio > 1) {
             *  ratio = ratio - 1;
             * } else if (ratio > 0) {*/
            ratio = 1 - ratio;
            //}
            decimal recommendedPercent = Math.Abs(MAX_WIDTH - ratio * 100);

            return(Convert.ToInt32(Math.Floor(recommendedPercent)));
        }
Ejemplo n.º 4
0
        private static bool IsInvalid(RepresentationForUser representationForUser)
        {
            Size size = representationForUser != null ? representationForUser.Size : null;

            bool result = representationForUser == null || string.IsNullOrEmpty(representationForUser.Title) ||
                          IsInvalidSize(size) || IsInvalidImage(representationForUser.Image) ||
                          !EnumerableValidator.IsNotNullAndNotEmpty(representationForUser.Areas);

            if (!result)
            {
                IWordsQuery wordsQuery = new WordsQuery();
                //проверить области
                List <RepresentationAreaForUser> areas = representationForUser.Areas;
                foreach (RepresentationAreaForUser area in areas)
                {
                    if (wordsQuery.IsInvalid(area.Source) || wordsQuery.IsInvalid(area.Translation) ||
                        IsInvalid(size, area.LeftUpperCorner) || IsInvalid(size, area.RightBottomCorner))
                    {
                        result = true;
                        break;
                    }
                }
            }
            return(result);
        }
        public JsonResult Preview(string group)
        {
            UserLanguages         userLanguages         = WebSettingsConfig.Instance.DefaultUserLanguages;
            RepresentationForUser representationForUser = GetRepresentationForUser(userLanguages, group);

            if (representationForUser == null)
            {
                return(null);
            }
            return(JsonResultHelper.GetUnlimitedJsonResult(representationForUser.Areas));
        }
        private static RepresentationForUser GetRepresentationForUser(UserLanguages userLanguages, string group)
        {
            if (string.IsNullOrEmpty(group))
            {
                return(null);
            }
            RepresentationsQuery  representationsQuery  = GetRepresentationsQuery();
            RepresentationForUser representationForUser = representationsQuery.GetWithAreas(userLanguages, group);

            return(representationForUser);
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
        public List <RepresentationForUser> GetBought(UserLanguages userLanguages, HashSet <long> ids)
        {
            //TODO: оптимизация запросов, вытянуть одним большим
            List <RepresentationForUser> withoutImages =
                GetVisibleWithoutAreas().Where(e => ids.Contains(e.Id)).OrderBy(e => e.Title).ToList();
            var result = new List <RepresentationForUser>();

            foreach (RepresentationForUser withoutImage in withoutImages)
            {
                RepresentationForUser representationImage = GetWithAreas(userLanguages, withoutImage.Title);
                result.Add(representationImage);
            }
            return(result);
        }
Ejemplo n.º 9
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);
        }
        public DocumentationGenerator Download(DocumentType docType,
                                               string fileName,
                                               RepresentationForUser representationForUser)
        {
            DocumentationGenerator documentGenerator = DocumentationGenerator.Create(_domain, _fontPath, docType, fileName);

            var tableData = new TableData(2, true);

            tableData.AddHeader("Слово", "Перевод");
            foreach (RepresentationAreaForUser area in representationForUser.Areas)
            {
                tableData.AddRow(area.Source.Text, area.Translation.Text);
            }

            documentGenerator.AddHeader(string.Format("Визуальный словарь на тему «{0}»", representationForUser.Title));
            documentGenerator.AddTable(tableData);

            return(documentGenerator);
        }
        public ActionResult GapsTrainer(string group)
        {
            if (WebSettingsConfig.Instance.IsSectionForbidden(SectionId.VisualDictionary))
            {
                return(RedirectToAction("Index", RouteConfig.MAIN_CONTROLLER_NAME));
            }

            UserLanguages         userLanguages         = WebSettingsConfig.Instance.DefaultUserLanguages;
            RepresentationForUser representationForUser = GetRepresentationForUser(userLanguages, group);

            var gapsTrainerHelper        = new GapsTrainerHelper();
            List <GapsTrainerItem> items = gapsTrainerHelper.ConvertToItems(representationForUser.Areas);

            var pageRequiredData = new PageRequiredData(SectionId.VisualDictionary, PageId.GapsTrainer, group);
            var model            = new GapsTrainerModel(pageRequiredData, items);

            model.LoadNextBtnCaption = "Показать другие слова";
            model.SpeakerDataType    = SpeakerDataType.Word;
            model.BreadcrumbsItems   = BreadcrumbsHelper.GetVisualDictionary(Url, group, CommonConstants.FILL_GAPS);
            return(View("GapsTrainer", model));
        }
        public ActionResult Download(UserLanguages userLanguages, string group, DocumentType type)
        {
            if (UserLanguages.IsInvalid(userLanguages))
            {
                return(RedirectToAction("Index", RouteConfig.VISUAL_DICTIONARIES_CONTROLLER_NAME));
            }
            RepresentationForUser representationForUser = GetRepresentationForUser(userLanguages, group);

            if (representationForUser == null)
            {
                return(RedirectToActionPermanent("Index", RouteConfig.VISUAL_DICTIONARIES_CONTROLLER_NAME));
            }

            var downloader = new VisualDictionaryDownloader(WebSettingsConfig.Instance.DomainWithProtocol,
                                                            CommonConstants.GetFontPath(Server));
            string fileName = string.Format("Визуальный словарь на тему {0}",
                                            representationForUser.Title.ToLowerInvariant());
            DocumentationGenerator documentGenerator = downloader.Download(type, fileName, representationForUser);

            return(File(documentGenerator.Generate(), documentGenerator.ContentType, documentGenerator.FileName));
        }
Ejemplo n.º 13
0
        private static void DeleteOldVisualWords(StudyLanguageContext c, RepresentationForUser representationForUser)
        {
            var areasIds = new HashSet <long>(representationForUser.Areas.Select(e => e.Id));

            bool needRemove = false;
            List <RepresentationArea> areas =
                c.RepresentationArea.Where(e => e.RepresentationId == representationForUser.Id).ToList();

            foreach (RepresentationArea area in areas)
            {
                if (areasIds.Contains(area.Id))
                {
                    continue;
                }
                c.RepresentationArea.Remove(area);
                needRemove = true;
            }
            if (needRemove)
            {
                c.SaveChanges();
            }
        }
Ejemplo n.º 14
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 ? "сохранен" : "НЕ сохранен!");
        }
Ejemplo n.º 15
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);
        }
Ejemplo n.º 16
0
 public VisualDictionaryModel(UserLanguages userLanguages, RepresentationForUser representation)
     : base(userLanguages)
 {
     Representation = representation;
 }
Ejemplo n.º 17
0
        private DocumentationGenerator GetGenerator(AllMaterialsQuery allMaterialsQuery,
                                                    SectionId sectionId,
                                                    long id,
                                                    string title)
        {
            DocumentationGenerator result;

            switch (sectionId)
            {
            case SectionId.GroupByWords:
                var groupWordsDownloader = new GroupDataDownloader(_domain, _fontPath)
                {
                    Header      = string.Format("Слова на тему «{0}»", title),
                    TableHeader = "Слово"
                };

                List <SourceWithTranslation> words = allMaterialsQuery.GetWordsByGroup(id);
                result = groupWordsDownloader.Download(DOCUMENT_TYPE, title, words);
                break;

            case SectionId.GroupByPhrases:
                var groupDataDownloader = new GroupDataDownloader(_domain, _fontPath)
                {
                    Header      = string.Format("Фразы на тему «{0}»", title),
                    TableHeader = "Фраза"
                };

                List <SourceWithTranslation> sentences = allMaterialsQuery.GetSentencesByGroup(id);
                result = groupDataDownloader.Download(DOCUMENT_TYPE, title, sentences);
                break;

            case SectionId.VisualDictionary:
                var visualDictionaryDownloader = new VisualDictionaryDownloader(_domain, _fontPath);

                RepresentationForUser representationForUser = allMaterialsQuery.GetVisualDictionary(title);
                result = visualDictionaryDownloader.Download(DOCUMENT_TYPE, title, representationForUser);
                break;

            case SectionId.FillDifference:
                var comparisonDownloader = new ComparisonDownloader(_domain, _fontPath);

                ComparisonForUser comparisonForUser = allMaterialsQuery.GetComparison(title);
                result = comparisonDownloader.Download(DOCUMENT_TYPE, title, comparisonForUser);
                break;

            case SectionId.Video:
                var videoTextDownloader = new VideoTextDownloader(_domain, _fontPath);

                VideoForUser videoForUser = allMaterialsQuery.GetVideo(title);
                result = videoTextDownloader.Download(DOCUMENT_TYPE, title, videoForUser);
                break;

            case SectionId.PopularWord:
                var popularWordsDownloader = new PopularWordsDownloader(_domain, _fontPath)
                {
                    Header = "Минилекс слов Гуннемарка"
                };

                List <SourceWithTranslation> popularWords = allMaterialsQuery.GetPopularWords();
                result = popularWordsDownloader.Download(DOCUMENT_TYPE, title, popularWords);
                break;

            default:
                result = null;
                break;
            }
            return(result);
        }