Пример #1
0
        private static void InheritSources(SIDocument doc2, Round round, Theme theme)
        {
            var sources = theme.Info.Sources;

            if (sources.Count == 0)
            {
                sources = round.Info.Sources;
                if (sources.Count == 0)
                {
                    sources = doc2.Package.Info.Sources;
                }

                if (sources.Count > 0)
                {
                    var realSources = doc2.GetRealSources(sources);
                    theme.Info.Sources.Clear();

                    foreach (var item in realSources)
                    {
                        theme.Info.Sources.Add(item);
                    }
                }
            }
            else
            {
                for (int i = 0; i < sources.Count; i++)
                {
                    var link = doc2.GetLink(theme.Info.Sources, i, out string tail);
                    if (link != null)
                    {
                        theme.Info.Sources[i] = link + tail;
                    }
                }
            }
        }
Пример #2
0
        private async void ImportXml_Executed(object arg)
        {
            var file = PlatformManager.Instance.ShowImportXmlUI();

            if (file == null)
            {
                return;
            }

            try
            {
                using (var stream = File.OpenRead(file))
                {
                    var doc = await SIDocument.LoadXml(stream);

                    var docViewModel = new QDocument(doc, _storageContextViewModel)
                    {
                        Path = "", Changed = true, FileName = Path.GetFileNameWithoutExtension(file)
                    };

                    LoadMediaFromFolder(docViewModel, Path.GetDirectoryName(file));

                    DocList.Add(docViewModel);
                }
            }
            catch (Exception exc)
            {
                ShowError(exc);
            }
        }
Пример #3
0
        public PackageTreeViewDialog(SIDocument doc, GameConfiguration.GameTypes gameType)
        {
            InitializeComponent();

            treeView1.Nodes.Add(doc.Package.Name);

            foreach (Round round in doc.Package.Rounds)
            {
                TreeNode roundNode = new TreeNode(round.Name);
                treeView1.Nodes[0].Nodes.Add(roundNode);

                if (gameType != GameConfiguration.GameTypes.TeleSI)
                {
                    foreach (Theme theme in round.Themes)
                    {
                        TreeNode themeNode = new TreeNode(theme.Name);
                        roundNode.Nodes.Add(themeNode);

                        foreach (Question quest in theme.Questions)
                        {
                            themeNode.Nodes.Add(quest.ToString());
                        }
                    }
                }
            }
        }
Пример #4
0
        private static void InheritAuthors(SIDocument doc2, Round round, Theme theme)
        {
            var authors = theme.Info.Authors;

            if (authors.Count == 0)
            {
                authors = round.Info.Authors;
                if (authors.Count == 0)
                {
                    authors = doc2.Package.Info.Authors;
                }

                if (authors.Count > 0)
                {
                    var realAuthors = doc2.GetRealAuthors(authors);
                    theme.Info.Authors.Clear();

                    foreach (var item in realAuthors)
                    {
                        theme.Info.Authors.Add(item);
                    }
                }
            }
            else
            {
                for (int i = 0; i < authors.Count; i++)
                {
                    var link = doc2.GetLink(theme.Info.Authors, i, out string tail);
                    if (link != null)
                    {
                        theme.Info.Authors[i] = link + tail;
                    }
                }
            }
        }
Пример #5
0
        public async Task ApplyData(SIDocument document)
        {
            if (Authors != null)
            {
                foreach (var author in Authors)
                {
                    if (!document.Authors.Any(x => x.Id == author.Id))
                    {
                        document.Authors.Add(author);
                    }
                }
            }

            if (Sources != null)
            {
                foreach (var source in Sources)
                {
                    if (!document.Sources.Any(x => x.Id == source.Id))
                    {
                        document.Sources.Add(source);
                    }
                }
            }

            if (Images != null)
            {
                foreach (var item in Images)
                {
                    if (!document.Images.Contains(item.Key))
                    {
                        await document.Images.AddFile(item.Key, item.Value.Stream);
                    }
                }
            }

            if (Audio != null)
            {
                foreach (var item in Audio)
                {
                    if (!document.Audio.Contains(item.Key))
                    {
                        await document.Audio.AddFile(item.Key, item.Value.Stream);
                    }
                }
            }

            if (Video != null)
            {
                foreach (var item in Video)
                {
                    if (!document.Video.Contains(item.Key))
                    {
                        await document.Video.AddFile(item.Key, item.Value.Stream);
                    }
                }
            }
        }
Пример #6
0
        private static async Task <bool> ExtractThemeAsync(
            IPackagesProvider provider,
            SIDocument doc,
            List <string> files,
            int roundIndex,
            Func <Round, bool> predicate,
            StringBuilder packageComments,
            int baseCost)
        {
            var fIndex = Rand.Next(files.Count);
            var doc2   = await provider.GetPackageAsync(files[fIndex]);

            if (doc2 == null)
            {
                throw new PackageNotFoundException(files[fIndex]);
            }

            using (doc2)
            {
                var normal = doc2.Package.Rounds.Where(predicate).ToList();
                var count  = normal.Count;
                if (count == 0)
                {
                    files.RemoveAt(fIndex);
                    return(false);
                }

                var rIndex = Rand.Next(count);
                var r      = normal[rIndex];
                var tIndex = Rand.Next(r.Themes.Count);

                var theme = r.Themes[tIndex];

                // Исключим повторения имён тем
                if (doc.Package.Rounds.Any(round => round.Themes.Any(th => th.Name == theme.Name)))
                {
                    return(false);
                }

                // Нужно перенести в пакет необходимых авторов, источники, медиаконтент
                InheritAuthors(doc2, r, theme);
                InheritSources(doc2, r, theme);

                for (int i = 0; i < theme.Questions.Count; i++)
                {
                    theme.Questions[i].Price = (roundIndex + 1) * (i + 1) * baseCost;

                    InheritAuthors(doc2, theme.Questions[i]);
                    InheritSources(doc2, theme.Questions[i]);
                    await InheritContentAsync(doc, doc2, theme.Questions[i]);
                }

                doc.Package.Rounds[roundIndex].Themes.Add(theme);
                packageComments.AppendFormat("{0}:{1}:{2};", files[fIndex], doc2.Package.Rounds.IndexOf(r), tIndex);
                return(true);
            }
        }
Пример #7
0
 public override string GetPackageId()
 {
     using (var stream = File.OpenRead(FileName))
     {
         using (var doc = SIDocument.Load(stream))
         {
             return(doc.Package.ID);
         }
     }
 }
Пример #8
0
        private static SIDocument CreateDocument()
        {
            var document = SIDocument.Create("test", "author", new PackageMock());

            var round = new Round();

            document.Package.Rounds.Add(round);

            var theme = new Theme();

            round.Themes.Add(theme);

            var question = new Question();

            theme.Questions.Add(question);

            question.Scenario.Add(new Atom {
                Type = AtomTypes.Text, Text = "question"
            });
            question.Scenario.Add(new Atom {
                Type = AtomTypes.Marker
            });
            question.Scenario.Add(new Atom {
                Type = AtomTypes.Audio, Text = "audio.mp3", AtomTime = 10
            });

            var question2 = new Question();

            theme.Questions.Add(question2);

            question2.Scenario.Add(new Atom {
                Type = AtomTypes.Text, Text = "question"
            });
            question2.Right.Add("right");

            var question3 = new Question();

            theme.Questions.Add(question3);

            question3.Scenario.Add(new Atom {
                Type = AtomTypes.Text, Text = "question"
            });
            question3.Scenario.Add(new Atom {
                Type = AtomTypes.Marker
            });
            question3.Scenario.Add(new Atom {
                Type = AtomTypes.Audio, Text = "audio.mp3", AtomTime = 10
            });
            question3.Scenario.Add(new Atom {
                Type = AtomTypes.Text, Text = "answer"
            });

            return(document);
        }
Пример #9
0
        public static Task <SIDocument> GenerateRandomPackageAsync(
            IPackagesProvider provider,
            string folder,
            string name,
            string author,
            string roundNameFormat,
            string finalName,
            int roundsCount = 3,
            int themesCount = 6,
            int baseCost    = 100)
        {
            var doc = SIDocument.Create(name, author, folder);

            return(GenerateCoreAsync(provider, roundsCount, themesCount, baseCost, doc, roundNameFormat, finalName));
        }
Пример #10
0
        private static void InheritAuthors(SIDocument doc2, Question question)
        {
            var authors = question.Info.Authors;

            if (authors.Count > 0)
            {
                for (int i = 0; i < authors.Count; i++)
                {
                    var link = doc2.GetLink(question.Info.Authors, i, out string tail);
                    if (link != null)
                    {
                        question.Info.Authors[i] = link + tail;
                    }
                }
            }
        }
Пример #11
0
        private static void InheritSources(SIDocument doc2, Question question)
        {
            var sources = question.Info.Sources;

            if (sources.Count > 0)
            {
                for (int i = 0; i < sources.Count; i++)
                {
                    var link = doc2.GetLink(question.Info.Sources, i, out string tail);
                    if (link != null)
                    {
                        question.Info.Sources[i] = link + tail;
                    }
                }
            }
        }
Пример #12
0
 public GameRunner(Server server,
                   IGameSettingsCore <AppSettingsCore> settings,
                   SIDocument document,
                   IGameManager backLink,
                   IShare share,
                   ComputerAccount[] defaultPlayers,
                   ComputerAccount[] defaultShowmans,
                   bool createHost = true)
 {
     _server          = server;
     _settings        = settings;
     _document        = document;
     _backLink        = backLink;
     _share           = share;
     _defaultPlayers  = defaultPlayers;
     _defaultShowmans = defaultShowmans;
     _createHost      = createHost;
 }
Пример #13
0
        public async Task <SIDocument> GetPackageAsync(string name)
        {
            if (string.IsNullOrEmpty(_storageOriginsPath))
            {
                var fileName = Path.GetTempFileName();

                try
                {
                    var request = WebRequest.Create($"{_storageUrl}/{Uri.EscapeDataString(name)}"); // TODO: -> HttpClient
                    using (var response = await request.GetResponseAsync())
                        using (var stream = response.GetResponseStream())
                        {
                            using (var fs = File.Create(fileName))
                            {
                                await stream.CopyToAsync(fs);
                            }
                        }

                    _downloadedFiles.Add(fileName);

                    using (var fs = File.OpenRead(fileName))
                    {
                        return(SIDocument.Load(fs));
                    }
                }
                finally
                {
                    File.Delete(fileName);
                }
            }
            else
            {
                var paths             = name.Split('\\');
                var packagePath       = Path.Combine(paths);
                var packageOriginPath = Path.Combine(_storageOriginsPath, packagePath);

                if (!File.Exists(packageOriginPath))
                {
                    throw new Exception($"Пакет {name} не существует!");
                }

                return(SIDocument.Load(File.OpenRead(packageOriginPath)));
            }
        }
Пример #14
0
        private void SelectAtomObject_Do(string mediaType, MediaItemViewModel file, bool asAnswer)
        {
            var index = CurrentPosition;

            if (index == -1)
            {
                index = Count - 1;
            }

            OwnerDocument.BeginChange();

            try
            {
                if (asAnswer)
                {
                    if (!_isComplex)
                    {
                        AddMarker_Executed(null);
                        index = Count - 1;
                    }
                }
                else if (string.IsNullOrWhiteSpace(this[index].Model.Text))
                {
                    RemoveAt(index--);
                }

                var atom = new AtomViewModel(new Atom {
                    Type = mediaType, Text = ""
                });
                Insert(index + 1, atom);

                SIDocument.SetLink(atom.Model, file.Model.Name);
                OwnerDocument.ActiveItem = null;
            }
            catch (Exception exc)
            {
                OwnerDocument.OnError(exc);
            }
            finally
            {
                OwnerDocument.CommitChange();
            }
        }
Пример #15
0
        private void BeginNewGameCompleted(SIDocument document, string documentPath)
        {
            var localizer = new NetworkLocalizer(Thread.CurrentThread.CurrentUICulture.Name);

            Server server;

            if (NetworkGame)
            {
                server = new TcpMasterServer(NetworkPort, ServerConfiguration.Default, localizer);
                ((TcpMasterServer)server).StartListen();
            }
            else
            {
                server = new BasicServer(ServerConfiguration.Default, localizer);
            }

            server.Error += Server_Error;

            _model.NetworkGamePassword = "";
            _model.AppSettings.Culture = Thread.CurrentThread.CurrentUICulture.Name;
            _model.HumanPlayerName     = Human.Name;

            var(host, _) = new GameRunner(
                server,
                _model,
                document,
                BackLink.Default,
                new WebManager(_model.AppSettings.MultimediaPort),
                _computerPlayers.ToArray(),
                _computerShowmans.ToArray())
                           .Run();

            if (!NetworkGame)
            {
                host.MyData.IsChatOpened = false;
                host.MyData.AutoReady    = true;
            }

            MoveToGame(server, host, documentPath);
        }
Пример #16
0
        private async Task <(SIDocument, string)> BeginNewGameAsync()
        {
            try
            {
                var(packageFile, isTemp) = await Package.GetPackageFileAsync();

                var tempDir = Path.Combine(Path.GetTempPath(), CommonSettings.AppNameEn, Guid.NewGuid().ToString());
                ZipHelper.ExtractToDirectory(packageFile, tempDir);

                if (isTemp)
                {
                    File.Delete(packageFile);
                }

                return(SIDocument.Load(tempDir), tempDir);
            }
            finally
            {
                IsProgress = false;
                BeginGame.CanBeExecuted = true;
            }
        }
Пример #17
0
        public async Task <SIDocument> GetPackageAsync(string name)
        {
            if (string.IsNullOrEmpty(_storageOriginsPath))
            {
                var fileName = Path.GetTempFileName();

                var packageNameParts = name.Split('\\');
                var escapedName      = string.Join("/", packageNameParts.Select(pnp => Uri.EscapeDataString(pnp)));

                var uri = $"{_storageUrl}/{escapedName}";
                using (var response = await HttpClient.GetAsync(uri))
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        throw new Exception($"Error while accessing \"{uri}\": {await response.Content.ReadAsStringAsync()}!");
                    }

                    using var fs = File.Create(fileName);
                    await response.Content.CopyToAsync(fs);
                }

                _downloadedFiles.Add(fileName);

                return(SIDocument.Load(File.OpenRead(fileName)));
            }
            else
            {
                var paths             = name.Split('\\');
                var packagePath       = Path.Combine(paths);
                var packageOriginPath = Path.Combine(_storageOriginsPath, packagePath);

                if (!File.Exists(packageOriginPath))
                {
                    throw new Exception($"Пакет {name} не существует!");
                }

                return(SIDocument.Load(File.OpenRead(packageOriginPath)));
            }
        }
        private async void Select2_Executed(object arg)
        {
            var authors     = _document.Document.Package.Info.Authors;
            var newDocument = SIDocument.Create(_document.Document.Package.Name, authors.Count > 0 ? authors[0] : Resources.Empty);
            var mainRound   = newDocument.Package.CreateRound(RoundTypes.Standart, Resources.ThemesCollection);

            var allthemes = Themes.Where(st => st.IsSelected).Select(st => st.Theme);

            foreach (var theme in allthemes)
            {
                var newTheme = theme.Clone();
                mainRound.Themes.Add(newTheme);

                // Выгрузим с собой необходимые коллекции
                await _document.Document.CopyCollections(newDocument, theme);
            }

            OnNewItem(new QDocument(newDocument, _document.StorageContext)
            {
                FileName = newDocument.Package.Name
            });
        }
Пример #19
0
        /// <summary>
        /// Получить полные данные для объекта, включая присоединённые элементы коллекций
        /// </summary>
        /// <returns></returns>
        public void GetFullData(SIDocument document, InfoOwner owner)
        {
            var length = owner.Info.Authors.Count;

            for (int i = 0; i < length; i++)
            {
                var docAuthor = document.GetLink(owner.Info.Authors, i);
                if (docAuthor != null)
                {
                    if (Authors == null)
                    {
                        Authors = new List <AuthorInfo>();
                    }

                    if (!Authors.Contains(docAuthor))
                    {
                        Authors.Add(docAuthor);
                    }
                }
            }

            length = owner.Info.Sources.Count;
            for (int i = 0; i < length; i++)
            {
                var docSource = document.GetLink(owner.Info.Sources, i);
                if (docSource != null)
                {
                    if (Sources == null)
                    {
                        Sources = new List <SourceInfo>();
                    }

                    if (!Sources.Contains(docSource))
                    {
                        Sources.Add(docSource);
                    }
                }
            }
        }
Пример #20
0
        private static async Task InheritContent(SIDocument doc, SIDocument doc2, Question question)
        {
            foreach (var atom in question.Scenario)
            {
                if (atom.Type == AtomTypes.Text || atom.Type == AtomTypes.Oral)
                {
                    continue;
                }

                var link = doc2.GetLink(atom);
                if (link.GetStream != null)
                {
                    DataCollection collection = null;
                    switch (atom.Type)
                    {
                    case AtomTypes.Video:
                        collection = doc.Video;
                        break;

                    case AtomTypes.Audio:
                        collection = doc.Audio;
                        break;

                    case AtomTypes.Image:
                        collection = doc.Images;
                        break;
                    }

                    if (collection != null)
                    {
                        using (var stream = link.GetStream().Stream)
                        {
                            await collection.AddFile(link.Uri, stream);
                        }
                    }
                }
            }
        }
Пример #21
0
        private void AppendInfo(SIDocument doc, Paragraph paragraph, InfoOwner owner)
        {
            var count = owner.Info.Authors.Count;

            if (count > 0)
            {
                paragraph.AppendLine().Append(string.Format("{0}{1}: ", Resources.BaseAuthors, count > 1 ? "ы" : ""));
                paragraph.Append(string.Join(", ", doc.GetRealAuthors(owner.Info.Authors)).EndWithPoint());
            }

            count = owner.Info.Sources.Count;
            if (count > 0)
            {
                paragraph.AppendLine().Append(string.Format("{0}{1}: ", Resources.BaseSources, count > 1 ? "и" : ""));
                paragraph.Append(string.Join(", ", doc.GetRealSources(owner.Info.Sources)).EndWithPoint());
            }

            if (owner.Info.Comments.Text.Length > 0)
            {
                paragraph.AppendLine().Append(string.Format("{0}: ", Resources.Comments));
                paragraph.Append(owner.Info.Comments.Text);
            }
        }
Пример #22
0
        /// <summary>
        /// Получить строковое представление результатов игры
        /// </summary>
        /// <param name="doc">Игровой пакет, используемый для извлечения текстов вопросов и ответов</param>
        /// <returns>Строковое представление результатов игры</returns>
        public static string ToString(this GameResult gameResult, SIDocument doc)
        {
            var result = new StringBuilder();

            result.AppendFormat("Имя пакета: {0}", gameResult.PackageName).AppendLine().AppendLine();
            result.AppendLine("Результаты игры:");

            foreach (var item in gameResult.Results)
            {
                result.AppendFormat("{0}: {1}", item.Name, item.Sum).AppendLine();
            }

            result.AppendLine().AppendLine("Апеллированные ответы:");
            PrintCollection(doc, gameResult.ApellatedQuestions, result, "Апелляция");

            result.AppendLine().AppendLine("Неверные ответы:");
            PrintCollection(doc, gameResult.WrongVersions, result, "Неверный ответ");

            result.AppendLine().AppendLine("Сообщения об ошибках:");
            result.AppendLine(gameResult.ErrorLog);

            return(result.ToString().Replace(Environment.NewLine, "\r"));
        }
Пример #23
0
        /// <summary>
        /// Получить строковое представление результатов игры
        /// </summary>
        /// <param name="gameResult">Результаты игры</param>
        /// <param name="doc">Игровой пакет, используемый для извлечения текстов вопросов и ответов</param>
        /// <param name="localizer">Локализатор</param>
        /// <returns>Строковое представление результатов игры</returns>
        public static string ToString(this GameResult gameResult, SIDocument doc, ILocalizer localizer)
        {
            var result = new StringBuilder();

            result.AppendFormat(DescriptionFormat, localizer[R.PackageName], gameResult.PackageName).AppendLine().AppendLine();
            result.Append(localizer[R.GameResults]).AppendLine(":");

            foreach (var item in gameResult.Results)
            {
                result.AppendFormat(DescriptionFormat, item.Name, item.Sum).AppendLine();
            }

            result.AppendLine().Append(localizer[R.ApellatedAnswers]).AppendLine(":");
            PrintCollection(doc, gameResult.ApellatedQuestions, result, localizer[R.Apellation], localizer);

            result.AppendLine().Append(localizer[R.WrongAnswers]).AppendLine(":");
            PrintCollection(doc, gameResult.WrongVersions, result, localizer[R.WrongAns], localizer);

            result.AppendLine().Append(localizer[R.ErrorMessages]).AppendLine(":");
            result.AppendLine(gameResult.ErrorLog);

            return(result.ToString().Replace(Environment.NewLine, "\r"));
        }
Пример #24
0
        private void CheckPackage()
        {
            var filePath = cbPackagePath.Text;

            if (!File.Exists(filePath))
            {
                doc = null;
                cbPackagePath.Text = "";
                return;
            }

            try
            {
                using (var stream = File.OpenRead(filePath))
                {
                    doc = SIDocument.Load(stream);
                }
            }
            catch (Exception e)
            {
                cbPackagePath.Text = "";
                MessageBox.Show(this, e.Message);
            }
        }
        internal async Task <SIDocument> SelectAsync(DBNode item)
        {
            var doc = await Utils.GetXml(item.Key);

            var manager = new XmlNamespaceManager(doc.NameTable);

            var siDoc = SIDocument.Create(doc.SelectNodes(@"/tournament/Title", manager)[0].InnerText.GrowFirstLetter().ClearPoints(), Resources.EmptyValue);

            siDoc.Package.Info.Comments.Text += string.Format(Resources.DBStorageComment, doc["tournament"]["FileName"].InnerText);
            string s = doc["tournament"]["Info"].InnerText;

            if (s.Length > 0)
            {
                siDoc.Package.Info.Comments.Text += string.Format("\r\nИнфо: {0}", s);
            }
            s = doc["tournament"]["URL"].InnerText;
            if (s.Length > 0)
            {
                siDoc.Package.Info.Comments.Text += string.Format("\r\nURL: {0}", s);
            }
            s = doc["tournament"]["PlayedAt"].InnerText;
            if (s.Length > 0)
            {
                siDoc.Package.Info.Comments.Text += string.Format("\r\nИграно: {0}", s);
            }
            s = doc["tournament"]["Editors"].InnerText;
            if (s.Length > 0)
            {
                siDoc.Package.Info.Authors[0] = $"{Resources.Editors}: {s}";
            }

            var round = siDoc.Package.CreateRound(RoundTypes.Standart, Resources.EmptyValue);

            var nodeList2 = doc.SelectNodes(@"/tournament/question", manager);

            foreach (XmlNode node2 in nodeList2)
            {
                var text = node2["Question"].InnerText.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
                var ans = node2["Answer"].InnerText.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
                var sour = node2["Sources"].InnerText.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
                int i = 0, j = 0;
                var themeName = new StringBuilder();
                while (i < text.Length && !(text[i].Length > 3 && text[i].Substring(0, 3) == "   "))
                {
                    if (themeName.Length > 0)
                    {
                        themeName.Append(' ');
                    }
                    themeName.Append(text[i++]);
                }

                var theme       = round.CreateTheme(themeName.ToString().GrowFirstLetter().ClearPoints());
                var authorsText = node2["Authors"].InnerText;
                if (!string.IsNullOrWhiteSpace(authorsText))
                {
                    theme.Info.Authors.Add(authorsText);
                }

                var themeComments = new StringBuilder(node2["Comments"].InnerText);

                while (i < text.Length && text[i].Length > 4 && text[i].Substring(0, 3) == "   " && !char.IsDigit(text[i][3]))
                {
                    if (themeComments.Length > 0)
                    {
                        themeComments.Append(' ');
                    }
                    themeComments.Append(text[i++]);
                }

                theme.Info.Comments.Text = themeComments.ToString();

                bool     final = true;
                Question quest = null;
                var      qText = new StringBuilder();
                i--;

                #region questionsReading

                while (++i < text.Length)
                {
                    text[i] = text[i].Trim();
                    string js = (j + 1).ToString();
                    if (text[i].Substring(0, js.Length) == js && (text[i].Length > 3 && text[i].Substring(js.Length, 2) == ". " || text[i].Length > 4 && text[i].Substring(js.Length, 3) == "0. "))
                    {
                        j++;
                        final = false;
                        if (qText.Length > 0)
                        {
                            quest           = theme.CreateQuestion(10 * (j - 1));
                            quest.Type.Name = QuestionTypes.Simple;
                            quest.Scenario.Clear();
                            quest.Scenario.Add(qText.ToString().GrowFirstLetter().ClearPoints());
                        }
                        int add = 3;
                        if (text[i].Substring(js.Length, 2) == ". ")
                        {
                            add = 2;
                        }

                        qText = new StringBuilder(text[i].Substring(js.Length + add));
                    }
                    else
                    {
                        if (qText.Length > 0)
                        {
                            qText.Append(' ');
                        }
                        qText.Append(text[i]);
                    }
                }

                if (final)
                {
                    quest          = theme.CreateQuestion(0);
                    quest.Right[0] = node2["Answer"].InnerText.Trim().GrowFirstLetter().ClearPoints();
                }
                else
                {
                    quest = theme.CreateQuestion(10 * j);
                }

                quest.Scenario.Clear();
                quest.Scenario.Add(qText.ToString().GrowFirstLetter().ClearPoints());
                quest.Type.Name = QuestionTypes.Simple;

                #endregion

                #region answersReading

                int number = 0, number2 = -1, multiplier = 1;

                if (!final)
                {
                    i     = -1;
                    qText = new StringBuilder();

                    while (++i < ans.Length)
                    {
                        ans[i] = ans[i].Trim();
                        number = 0;
                        int k = 0;
                        while (char.IsDigit(ans[i][k]))
                        {
                            number = number * 10 + int.Parse(ans[i][k++].ToString());
                        }

                        if (!((ans[i].Length > k + 2 && ans[i].Substring(k, 2) == ". " || ans[i].Length > 3 + k && ans[i].Substring(k, 3) == "0. ")))
                        {
                            number = -1;
                        }
                        if (number >= 0)
                        {
                            if (qText.Length > 0 && theme.Questions.Count > number2)
                            {
                                theme.Questions[number2].Right[0] = qText.ToString().GrowFirstLetter().ClearPoints();
                            }

                            if (number2 == -1)
                            {
                                multiplier = number;
                            }
                            number2 = number / multiplier - 1;
                            int add = 3;
                            if (ans[i].Substring(k, 2) == ". ")
                            {
                                add = 2;
                            }
                            qText = new StringBuilder(ans[i].Substring(k + add));
                        }
                        else
                        {
                            if (qText.Length > 0)
                            {
                                qText.Append(' ');
                            }
                            qText.Append(ans[i]);
                        }
                    }

                    if (theme.Questions.Count > number2)
                    {
                        theme.Questions[number2].Right[0] = qText.ToString().GrowFirstLetter().ClearPoints();
                    }
                }

                #endregion

                #region sourcesReading

                i       = -1;
                qText   = new StringBuilder();
                number  = 0;
                number2 = 0;

                while (++i < sour.Length)
                {
                    sour[i] = sour[i].Trim();
                    number  = 0;
                    int k = 0;
                    while (char.IsDigit(sour[i][k]))
                    {
                        number = number * 10 + int.Parse(sour[i][k++].ToString());
                    }
                    number--;
                    if (!((sour[i].Length > k + 2 && sour[i].Substring(k, 2) == ". " || sour[i].Length > 3 + k && sour[i].Substring(k, 3) == "0. ")))
                    {
                        number = -1;
                    }
                    if (number >= 0)
                    {
                        if (qText.Length > 0 && theme.Questions.Count > number2)
                        {
                            theme.Questions[number2].Info.Sources.Add(qText.ToString().GrowFirstLetter().ClearPoints());
                        }

                        number2 = number;
                        int add = 3;
                        if (sour[i].Substring(k, 2) == ". ")
                        {
                            add = 2;
                        }
                        qText = new StringBuilder(sour[i].Substring(k + add));
                    }
                    else
                    {
                        if (qText.Length > 0)
                        {
                            qText.Append(' ');
                        }
                        qText.Append(sour[i]);
                    }
                }

                if (theme.Questions.Count > number2 && qText.Length > 0)
                {
                    theme.Questions[number2].Info.Sources.Add(qText.ToString().GrowFirstLetter().ClearPoints());
                }

                if (number2 == -1)
                {
                    theme.Info.Sources.Add(node2["Sources"].InnerText);
                }

                #endregion
            }

            return(siDoc);
        }
Пример #26
0
 public abstract void ExportTable(SIDocument doc, string filename);
Пример #27
0
 public abstract IFlowDocumentWrapper BuildDocument(SIDocument doc, ExportFormats format);
Пример #28
0
        public static async Task <SIDocument> GenerateRandomPackage(IPackagesProvider provider, string name, string author, string roundNameFormat, int roundsCount = 3, int themesCount = 6, int baseCost = 100, Stream stream = null)
        {
            var doc = SIDocument.Create(name, author, stream);

            return(await GenerateCore(provider, roundsCount, themesCount, baseCost, doc, roundNameFormat));
        }
Пример #29
0
        private static async Task <SIDocument> GenerateCore(IPackagesProvider provider, int roundsCount, int themesCount, int baseCost, SIDocument doc, string roundNameFormat)
        {
            var files = (await provider.GetPackages()).ToList();

            var packageComments = new StringBuilder(RandomIndicator);             // Информация для отчёта об игре

            for (var i = 0; i < roundsCount; i++)
            {
                doc.Package.Rounds.Add(new Round {
                    Type = RoundTypes.Standart, Name = string.Format(roundNameFormat, i + 1)
                });
                for (int j = 0; j < themesCount; j++)
                {
                    if (files.Count == 0)
                    {
                        break;
                    }

                    if (!await ExtractTheme(provider, doc, files, i, round => round.Type == RoundTypes.Standart && round.Themes.Count > 0 /*, usedThemes*/, packageComments, baseCost))
                    {
                        j--;
                        continue;
                    }
                }

                if (files.Count == 0)
                {
                    break;
                }
            }

            doc.Package.Rounds.Add(new Round {
                Type = RoundTypes.Final, Name = "ФИНАЛ"
            });
            for (var j = 0; j < 7; j++)
            {
                if (files.Count == 0)
                {
                    break;
                }

                if (!await ExtractTheme(provider, doc, files, roundsCount, round => round.Type == RoundTypes.Final && round.Themes.Count > 0 /*, usedThemes*/, packageComments, 0))
                {
                    j--;
                    continue;
                }
            }

            // В пакете могут быть и свои комментарии; допишем туда
            doc.Package.Info.Comments.Text += packageComments.ToString();

            return(doc);
        }
Пример #30
0
        /// <summary>
        /// Открытие существующего файла
        /// </summary>
        /// <param name="path">Имя файла</param>
        /// <param name="fileStream">Открытый для чтения файл</param>
        internal void OpenFile(string path, string search = null, string overridePath = null, Action onSuccess = null)
        {
            var savingPath = overridePath ?? path;

            Task <QDocument> loader() => Task.Run(() =>
            {
                FileStream stream = null;
                try
                {
                    stream = File.Open(path, FileMode.Open, FileAccess.ReadWrite);

                    // Раньше было read = false
                    // Но из-за этого при каждом открытии, даже если файл не изменялся, менялась дата его изменения
                    var doc = SIDocument.Load(stream);

                    var docViewModel = new QDocument(doc, _storageContextViewModel)
                    {
                        Path     = savingPath,
                        FileName = Path.GetFileNameWithoutExtension(savingPath)
                    };

                    if (search != null)
                    {
                        docViewModel.SearchText = search;
                    }

                    if (overridePath != null)
                    {
                        docViewModel.OverridePath = overridePath;
                        docViewModel.OriginalPath = path;
                        docViewModel.Changed      = true;
                    }

                    return(docViewModel);
                }
                catch (Exception exc)
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }

                    if (exc is FileNotFoundException)
                    {
                        AppSettings.Default.History.Remove(path);
                    }

                    if (exc is UnauthorizedAccessException && (new FileInfo(path).Attributes & FileAttributes.ReadOnly) > 0)
                    {
                        throw new Exception(Resources.FileIsReadOnly);
                    }

                    throw exc;
                }
            });

            DocList.Add(new DocumentLoaderViewModel(path, loader, () =>
            {
                AppSettings.Default.History.Add(savingPath);

                onSuccess?.Invoke();
            }));
        }