コード例 #1
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);
        }
コード例 #2
0
        public ActionResult ShowAll(UserLanguages userLanguages,
                                    GroupForUser group,
                                    CrossReferenceType crossReferenceType)
        {
            if (WebSettingsConfig.Instance.IsSectionForbidden(SectionId))
            {
                return(RedirectToAction("Index", RouteConfig.MAIN_CONTROLLER_NAME));
            }

            if (UserLanguages.IsInvalid(userLanguages) || group == null)
            {
                return(GetRedirectToGroups());
            }
            GroupModel model = GetModel(userLanguages, group);

            if (model.IsInvalid())
            {
                return(GetRedirectToGroups());
            }

            long languageId                       = WebSettingsConfig.Instance.GetLanguageFromId();
            var  crossReferencesQuery             = new CrossReferencesQuery(languageId);
            List <CrossReference> crossReferences = crossReferencesQuery.GetReferences(group.Id, crossReferenceType);

            model.CrossReferencesModel = new CrossReferencesModel(group.Name, crossReferenceType, crossReferences);
            return(View("All", model));
        }
コード例 #3
0
        public ActionResult GetFile(UserLanguages userLanguages,
                                    GroupForUser group, DocumentType docType, string fileName)
        {
            if (WebSettingsConfig.Instance.IsSectionForbidden(SectionId))
            {
                return(RedirectToAction("Index", RouteConfig.MAIN_CONTROLLER_NAME));
            }

            if (UserLanguages.IsInvalid(userLanguages) || group == null)
            {
                return(GetRedirectToGroups());
            }
            GroupModel model = GetModel(userLanguages, group);

            if (model.IsInvalid())
            {
                return(GetRedirectToGroups());
            }

            string header = WebSettingsConfig.Instance.GetTemplateText(SectionId, PageId.Detail, TemplateId.Header,
                                                                       group.Name);

            header = HttpUtility.HtmlDecode(header);

            var downloader = new GroupDataDownloader(WebSettingsConfig.Instance.DomainWithProtocol, CommonConstants.GetFontPath(Server))
            {
                Header = header, TableHeader = TableHeader
            };
            var documentGenerator = downloader.Download(docType, fileName, model.ElemsWithTranslations);

            Stream stream = documentGenerator.Generate();

            return(File(stream, documentGenerator.ContentType, documentGenerator.FileName));
        }
コード例 #4
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            GroupForUser groupForUser = GetGroupForUser(filterContext);

            filterContext.ActionParameters[_uniqueParamName] = groupForUser;
            filterContext.RouteData.Values[_uniqueParamName] = groupForUser;
        }
コード例 #5
0
        public ActionResult GetImageByName(GroupForUser group)
        {
            long languageId  = WebSettingsConfig.Instance.GetLanguageFromId();
            var  groupsQuery = new GroupsQuery(languageId);

            return(GetImage(group != null ? group.Name : null, n => groupsQuery.GetImage(n, GroupType.ByWord)));
        }
コード例 #6
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));
        }
コード例 #7
0
        protected override List <SourceWithTranslation> GetSourceWithTranslations(UserLanguages userLanguages,
                                                                                  GroupForUser group)
        {
            var groupSentencesQuery             = new GroupSentencesQuery();
            List <SourceWithTranslation> result = groupSentencesQuery.GetSentencesByGroup(userLanguages, group.Id);

            return(result);
        }
コード例 #8
0
 public ActionResult GapsTrainer(GroupForUser group)
 {
     return(GetGapsTrainerView(group, model => {
         model.LoadNextBtnCaption = "Показать другие слова";
         model.SpeakerDataType = SpeakerDataType.Word;
         model.BreadcrumbsItems = BreadcrumbsHelper.GetWords(Url, group.Name, CommonConstants.FILL_GAPS);
     }));
 }
コード例 #9
0
        protected override List <SourceWithTranslation> GetSourceWithTranslations(UserLanguages userLanguages,
                                                                                  GroupForUser group)
        {
            var groupWordsQuery = new GroupWordsQuery();
            List <SourceWithTranslation> wordsWithTranslations = groupWordsQuery.GetWordsByGroup(userLanguages,
                                                                                                 group.Id);

            return(wordsWithTranslations);
        }
コード例 #10
0
 public ActionResult ShowSpecialItem(UserLanguages userLanguages, GroupForUser group, string elem1, string elem2)
 {
     if (UserLanguages.IsInvalid(userLanguages) || group == null || string.IsNullOrWhiteSpace(elem1) ||
         string.IsNullOrWhiteSpace(elem2))
     {
         return(GetRedirectToGroups());
     }
     return(ShowSpecial(userLanguages, group, model => FoundTranslation(elem1, elem2, model)));
 }
コード例 #11
0
        public void Create(string file)
        {
            var csvReader = new CsvReader(file);
            //var sentences = IoCModule.Create<SentencesQuery>();
            var      languages = new LanguagesQuery(LanguageShortName.Unknown, LanguageShortName.Unknown);
            Language from      = languages.GetByShortName(_from);
            Language russian   = languages.GetByShortName(LanguageShortName.Ru);

            string[] firstLine = csvReader.ReadLine();
            if (firstLine == null || EnumerableValidator.IsEmpty(firstLine))
            {
                return;
            }

            string groupName = TextFormatter.FirstUpperCharAndTrim(firstLine[0]);

            if (string.IsNullOrEmpty(groupName) || groupName.Length < 2)
            {
                return;
            }
            var groupsQuery = new GroupsQuery(from.Id);

            string fileName = firstLine.Length > 1 && !string.IsNullOrWhiteSpace(firstLine[1])
                                  ? firstLine[1].Trim()
                                  : groupName;
            string imageFileName = Path.Combine(@"C:\Projects\StudyLanguages\Источники для групп\Источники картинок\",
                                                fileName + ".jpg");

            //создает или получает раннее созданную группу
            byte[]       image        = !string.IsNullOrEmpty(imageFileName) ? File.ReadAllBytes(imageFileName) : null;
            GroupForUser groupForUser = groupsQuery.GetOrCreate(GroupType, groupName, image);

            do
            {
                string[] line = csvReader.ReadLine();
                if (line == null)
                {
                    break;
                }
                if (line.Length < 2)
                {
                    continue;
                }
                image = line.Length > 2 && !string.IsNullOrEmpty(line[2]) ? File.ReadAllBytes(line[2]) : null;
                int?rating = null;
                int rat;
                if (line.Length > 3 && int.TryParse(line[3], out rat))
                {
                    rating = rat;
                }

                bool isSuccess = Create(groupForUser, line, from, russian, image, rating);
                Console.WriteLine("{0}: {1}", isSuccess ? "Сохранено" : "Не сохранено",
                                  line.Aggregate((e1, e2) => e1 + " -> " + e2));
            } while (true);
        }
コード例 #12
0
        public JsonResult SetMark(long userId,
                                  GroupForUser group,
                                  UserLanguages userLanguages,
                                  KnowledgeMark mark,
                                  TrainerItem item)
        {
            long groupId = GetGroupId(group);

            return(SetMarkAndGetModel(userId, userLanguages, groupId, mark, item));
        }
コード例 #13
0
 public ActionResult ShowSpecialItem(UserLanguages userLanguages,
                                     GroupForUser group,
                                     long elem1,
                                     long elem2)
 {
     if (UserLanguages.IsInvalid(userLanguages) || group == null || IdValidator.IsInvalid(elem1) ||
         IdValidator.IsInvalid(elem2))
     {
         return(GetRedirectToGroups());
     }
     return(ShowSpecial(userLanguages, group, model => FoundTranslation(elem1, elem2, model)));
 }
コード例 #14
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);
        }
コード例 #15
0
ファイル: GroupModel.cs プロジェクト: AndreyShp/StudyFun
 public GroupModel(GroupForUser group,
                   SpeakerDataType speakerDataType,
                   KnowledgeDataType knowledgeDataType,
                   GroupModelOptions options,
                   UserLanguages userLanguages,
                   List <SourceWithTranslation> groupElemsWithTranslations)
     : base(userLanguages, groupElemsWithTranslations)
 {
     SpeakerDataType   = speakerDataType;
     KnowledgeDataType = knowledgeDataType;
     Id        = group.Id;
     GroupName = group.Name;
     _options  = options;
 }
コード例 #16
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);
        }
コード例 #17
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);
        }
コード例 #18
0
        public ActionResult GetGapsTrainerView(GroupForUser group, Action <GapsTrainerModel> filler)
        {
            if (WebSettingsConfig.Instance.IsSectionForbidden(SectionId))
            {
                return(RedirectToAction("Index", RouteConfig.MAIN_CONTROLLER_NAME));
            }

            UserLanguages userLanguages = WebSettingsConfig.Instance.DefaultUserLanguages;
            List <SourceWithTranslation> sourceWithTranslation = GetSourceWithTranslations(userLanguages, group);

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

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

            filler(model);
            return(View("GapsTrainer", model));
        }
コード例 #19
0
        public ActionResult GetTrainer(UserLanguages userLanguages, GroupForUser group)
        {
            if (WebSettingsConfig.Instance.IsSectionForbidden(SectionId))
            {
                return(RedirectToAction("Index", RouteConfig.MAIN_CONTROLLER_NAME));
            }

            if (UserLanguages.IsInvalid(userLanguages) || group == null)
            {
                return(GetRedirectToGroups());
            }
            GroupModel model = GetModel(userLanguages, group);

            if (model.IsInvalid())
            {
                return(GetRedirectToGroups());
            }
            model.SetCurrent(model.ElemsWithTranslations[0]);
            return(View("Index", model));
        }
コード例 #20
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);
        }
コード例 #21
0
        protected override GroupModel GetModel(UserLanguages userLanguages,
                                               GroupForUser group)
        {
            List <SourceWithTranslation> sentencesWithTranslations = GetSourceWithTranslations(userLanguages, group);

            var options = new GroupModelOptions(new Dictionary <LinkId, string> {
                { LinkId.First, "Первая фраза" },
                { LinkId.Prev, "Предыдущая фраза" },
                { LinkId.Next, "Следующая фраза" },
                { LinkId.Last, "Последняя фраза" }
            }, (patternUrl, elem) => string.Format(patternUrl, elem.Source.Id, elem.Translation.Id))
            {
                SourceTextGetter      = elem => elem.Source.Text,
                TranslationTextGetter = elem => elem.Translation.Text,
            };

            var model = new GroupModel(group, SpeakerDataType.Sentence, KnowledgeDataType.PhraseTranslation, options,
                                       userLanguages,
                                       sentencesWithTranslations);

            return(model);
        }
コード例 #22
0
        protected override GroupModel GetModel(UserLanguages userLanguages,
                                               GroupForUser group)
        {
            List <SourceWithTranslation> wordsWithTranslations = GetSourceWithTranslations(userLanguages, group);

            var options = new GroupModelOptions(new Dictionary <LinkId, string> {
                { LinkId.First, "Первое слово" },
                { LinkId.Prev, "Предыдущее слово" },
                { LinkId.Next, "Следующее слово" },
                { LinkId.Last, "Последнее слово" }
            },
                                                (patternUrl, elem) =>
                                                string.Format(patternUrl,
                                                              UrlBuilder.EncodePartUrl(
                                                                  elem.Source.Text),
                                                              UrlBuilder.EncodePartUrl(
                                                                  elem.Translation.Text)));
            var model = new GroupModel(group, SpeakerDataType.Word, KnowledgeDataType.WordTranslation, options,
                                       userLanguages, wordsWithTranslations);

            return(model);
        }
コード例 #23
0
        public ActionResult Index(long userId, GroupForUser group, UserLanguages userLanguages)
        {
            long groupId = GetGroupId(group);

            return(GetIndex(userId, userLanguages, groupId, model => SetModel(group.Name, model)));
        }
コード例 #24
0
 public ActionResult Trainer(UserLanguages userLanguages, GroupForUser group)
 {
     return(GetTrainer(userLanguages, group));
 }
コード例 #25
0
        public ActionResult Download(UserLanguages userLanguages, GroupForUser group, DocumentType type)
        {
            string fileName = string.Format("Слова на тему {0}", group.LowerName.ToLowerInvariant());

            return(GetFile(userLanguages, group, type, fileName));
        }
コード例 #26
0
 protected abstract bool Create(GroupForUser groupForUser,
                                string[] line,
                                Language english,
                                Language russian,
                                byte[] image,
                                int?rating);
コード例 #27
0
 protected abstract GroupModel GetModel(UserLanguages userLanguages,
                                        GroupForUser group);
コード例 #28
0
 protected abstract List <SourceWithTranslation> GetSourceWithTranslations(UserLanguages userLanguages,
                                                                           GroupForUser group);
コード例 #29
0
 private static long GetGroupId(GroupForUser group)
 {
     return(group != null ? group.Id : IdValidator.INVALID_ID);
 }
コード例 #30
0
 public ActionResult Index(UserLanguages userLanguages, GroupForUser group)
 {
     return(ShowAll(userLanguages, group, CrossReferenceType.GroupWord));
 }