├── Platonus Tester
├── HashSource
│ ├── hash_0.txt
│ ├── hash_50.txt
│ ├── hash_60.txt
│ ├── hash_75.txt
│ ├── hash_90.txt
│ ├── test.txt
│ └── hash_100.txt
├── Media
│ ├── icon.ico
│ ├── icon.png
│ └── logo.png
├── bin
│ └── Release
│ │ ├── DocX.dll
│ │ ├── Platest.dll
│ │ ├── ResultComments.dll
│ │ ├── Platonus Tester.exe
│ │ ├── Platonus Tester.vshost.exe
│ │ ├── Platonus Tester.exe.config
│ │ ├── Platonus Tester.vshost.exe.config
│ │ ├── settings.xml
│ │ ├── Platonus Tester.vshost.exe.manifest
│ │ └── Platonus Tester.XML
├── Properties
│ ├── Settings.settings
│ ├── Settings.Designer.cs
│ ├── AssemblyInfo.cs
│ ├── Resources.Designer.cs
│ └── Resources.resx
├── App.config
├── App.xaml.cs
├── Platonus Tester.csproj.DotSettings
├── App.xaml
├── Helper
│ ├── Settings.cs
│ ├── Const.cs
│ └── UInterfaceHelper.cs
├── ErrorWindow.xaml
├── ErrorWindow.xaml.cs
├── ResultWindow.xaml
├── Controller
│ └── SettingsController.cs
├── SettingsForm.xaml
├── ResultWindow.xaml.cs
├── SettingsForm.xaml.cs
├── Platonus Tester.csproj
├── MainWindow.xaml
└── MainWindow.xaml.cs
├── Platest
├── packages.config
├── Interfaces
│ ├── ISourceLoadListener.cs
│ ├── IQuestionProvider.cs
│ └── IQuestionManager.cs
├── Models
│ ├── CurrentDispatcherFile.cs
│ ├── TestQuestion.cs
│ ├── AnsweredQuestion.cs
│ ├── Question.cs
│ └── SourceFile.cs
├── Properties
│ └── AssemblyInfo.cs
├── Controllers
│ ├── QuestionManager.cs
│ └── SourceController.cs
├── Helpers
│ ├── Extensions.cs
│ └── QuestionProcessor.cs
└── Platest.csproj
├── PlatestTest
├── test.txt
├── PlatestTest.csproj
└── QuestionProcessorTest.cs
├── source.md
├── ResultComments
├── Helpers
│ └── CommentProvider.cs
├── Properties
│ └── AssemblyInfo.cs
├── ResultComments.csproj
└── Models
│ ├── Comment.cs
│ └── Swear.cs
├── notice.md
├── Platonus Tester.sln
├── .gitattributes
├── readme.md
├── .gitignore
└── license.md
/Platonus Tester/HashSource/hash_0.txt:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Platonus Tester/HashSource/hash_50.txt:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Platonus Tester/HashSource/hash_60.txt:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Platonus Tester/HashSource/hash_75.txt:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Platonus Tester/HashSource/hash_90.txt:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/Platonus Tester/HashSource/test.txt:
--------------------------------------------------------------------------------
1 | success
--------------------------------------------------------------------------------
/Platonus Tester/Media/icon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maximgorbatyuk/Platonus-Tester/HEAD/Platonus Tester/Media/icon.ico
--------------------------------------------------------------------------------
/Platonus Tester/Media/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maximgorbatyuk/Platonus-Tester/HEAD/Platonus Tester/Media/icon.png
--------------------------------------------------------------------------------
/Platonus Tester/Media/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maximgorbatyuk/Platonus-Tester/HEAD/Platonus Tester/Media/logo.png
--------------------------------------------------------------------------------
/Platonus Tester/bin/Release/DocX.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maximgorbatyuk/Platonus-Tester/HEAD/Platonus Tester/bin/Release/DocX.dll
--------------------------------------------------------------------------------
/Platonus Tester/bin/Release/Platest.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maximgorbatyuk/Platonus-Tester/HEAD/Platonus Tester/bin/Release/Platest.dll
--------------------------------------------------------------------------------
/Platonus Tester/bin/Release/ResultComments.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maximgorbatyuk/Platonus-Tester/HEAD/Platonus Tester/bin/Release/ResultComments.dll
--------------------------------------------------------------------------------
/Platonus Tester/bin/Release/Platonus Tester.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maximgorbatyuk/Platonus-Tester/HEAD/Platonus Tester/bin/Release/Platonus Tester.exe
--------------------------------------------------------------------------------
/Platest/packages.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/Platonus Tester/HashSource/hash_100.txt:
--------------------------------------------------------------------------------
1 | Мистер YesIKnowItAll, а не свалить бы тебе за бугор?#
2 | Ну окей, в этот раз ты взял высший балл. Лимит удачи исчерпан#
3 |
--------------------------------------------------------------------------------
/PlatestTest/test.txt:
--------------------------------------------------------------------------------
1 | Question 1Variant 1
2 | Variant 2
3 | Variant 3
4 | Variant 4
5 | Variant 5
6 | Question 2
--------------------------------------------------------------------------------
/Platonus Tester/bin/Release/Platonus Tester.vshost.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/maximgorbatyuk/Platonus-Tester/HEAD/Platonus Tester/bin/Release/Platonus Tester.vshost.exe
--------------------------------------------------------------------------------
/Platest/Interfaces/ISourceLoadListener.cs:
--------------------------------------------------------------------------------
1 | using Platest.Models;
2 |
3 | namespace Platest.Interfaces
4 | {
5 | public interface ISourceLoadListener
6 | {
7 | void OnSourceLoaded(object currentDispatcher);
8 | }
9 | }
--------------------------------------------------------------------------------
/Platonus Tester/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/Platonus Tester/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Platest/Models/CurrentDispatcherFile.cs:
--------------------------------------------------------------------------------
1 | using System.Windows.Threading;
2 |
3 | namespace Platest.Models
4 | {
5 | public class CurrentDispatcherFile
6 | {
7 | public Dispatcher Dispatcher { get; set; }
8 | public SourceFile SourceFile { get; set; }
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/Platonus Tester/bin/Release/Platonus Tester.exe.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Platonus Tester/bin/Release/Platonus Tester.vshost.exe.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Platest/Models/TestQuestion.cs:
--------------------------------------------------------------------------------
1 | namespace Platest.Models
2 | {
3 | ///
4 | /// тестовый (незаданный) вопрос. Добавляется только поле Верный ответ
5 | ///
6 | public class TestQuestion : Question
7 | {
8 | public string CorrectAnswer { get; set; }
9 | }
10 | }
--------------------------------------------------------------------------------
/Platest/Interfaces/IQuestionProvider.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using Platest.Models;
3 |
4 | namespace Platest.Interfaces
5 | {
6 | public interface IQuestionProvider
7 | {
8 | List GetQuestionList(SourceFile file);
9 |
10 | IEnumerable GetErrors();
11 | }
12 | }
--------------------------------------------------------------------------------
/source.md:
--------------------------------------------------------------------------------
1 | http://stackoverflow.com/questions/16063520/how-do-you-create-an-asynchronous-method-in-c
2 | http://stackoverflow.com/questions/1126915/how-do-i-split-a-string-by-a-multi-character-delimiter-in-c
3 | http://stackoverflow.com/questions/6090913/make-an-installation-program-for-c-sharp-applications-and-include-net-framework
4 | http://stackoverflow.com/questions/20309158/c-sharp-checking-internet-connection
--------------------------------------------------------------------------------
/Platonus Tester/bin/Release/settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | false
4 | true
5 | true
6 | false
7 | 25
8 |
--------------------------------------------------------------------------------
/Platonus Tester/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Configuration;
4 | using System.Data;
5 | using System.Linq;
6 | using System.Threading.Tasks;
7 | using System.Windows;
8 |
9 | namespace Platonus_Tester
10 | {
11 | ///
12 | /// Логика взаимодействия для App.xaml
13 | ///
14 | public partial class App : Application
15 | {
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/Platonus Tester/Platonus Tester.csproj.DotSettings:
--------------------------------------------------------------------------------
1 |
2 | Yes
--------------------------------------------------------------------------------
/Platest/Interfaces/IQuestionManager.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using Platest.Models;
3 |
4 | namespace Platest.Interfaces
5 | {
6 | public interface IQuestionManager
7 | {
8 | void SetSourceList(SourceFile file);
9 |
10 | void Shuffle();
11 |
12 | TestQuestion GetNext();
13 |
14 | int GetCount();
15 |
16 | int GetFirstListCount();
17 |
18 | void SetQuestionLimit(int limit);
19 |
20 | int GetCurrentPosition();
21 |
22 | IEnumerable GetErrors();
23 | }
24 | }
--------------------------------------------------------------------------------
/Platest/Models/AnsweredQuestion.cs:
--------------------------------------------------------------------------------
1 | namespace Platest.Models
2 | {
3 | ///
4 | /// Отвеченный вопрос, где добавляемые поля - отмеченный, верный и флаг корректности (лол)
5 | ///
6 | public class AnsweredQuestion : Question
7 | {
8 | public string ChosenAnswer;
9 | public string CorrectAnswer;
10 | public bool IsItCorrect;
11 |
12 | public override string ToString()
13 | {
14 | var result = $"{AskQuestion}";
15 | return result;
16 | }
17 | }
18 |
19 |
20 | }
--------------------------------------------------------------------------------
/Platonus Tester/bin/Release/Platonus Tester.vshost.exe.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Platest/Models/Question.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Drawing;
3 |
4 | namespace Platest.Models
5 | {
6 | ///
7 | /// Класс-предок для отвеченного вопроса и незаданного
8 | ///
9 | public class Question
10 | {
11 | ///
12 | /// Вопрос
13 | ///
14 | public string AskQuestion { get; set; }
15 | ///
16 | /// Изображение. Может быть NULL
17 | ///
18 | public Image Picture { get; set; }
19 | ///
20 | /// Массив вариантов ответа
21 | ///
22 | public List AnswerList { get; set; }
23 |
24 | }
25 | }
--------------------------------------------------------------------------------
/ResultComments/Helpers/CommentProvider.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Threading.Tasks;
4 | using ResultComments.Models;
5 |
6 | namespace ResultComments.Helpers
7 | {
8 | ///
9 | /// Обработчик скачанного текста с репозитория в массив строк
10 | ///
11 | public abstract class CommentProvider
12 | {
13 |
14 | public static List GetHashList(string text)
15 | {
16 | var result = new List(0);
17 | var splitSeparators = new[] { "#\n" };
18 | var list = text.Split(splitSeparators, StringSplitOptions.RemoveEmptyEntries);
19 | result.AddRange(list);
20 | return result;
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/Platest/Models/SourceFile.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace Platest.Models
4 | {
5 | ///
6 | /// Класс-обертка для исходного файла
7 | ///
8 | public class SourceFile
9 | {
10 | ///
11 | /// текст документа. Включая таблицы и теги картинок
12 | ///
13 | public string SourceText { get; }
14 | ///
15 | /// Массив картинок в формате библиотеки Novacode
16 | ///
17 | public List Images { get; }
18 | ///
19 | /// Имя документа в файл-системе для отобрадения в UI компонентах
20 | ///
21 | public string FileName { get; }
22 |
23 | public SourceFile(string text, List images, string filename)
24 | {
25 | SourceText = text;
26 | Images = images;
27 | FileName = filename;
28 | }
29 | }
30 | }
--------------------------------------------------------------------------------
/Platonus Tester/App.xaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
13 |
14 |
18 |
19 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/Platonus Tester/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // Этот код создан программой.
4 | // Исполняемая версия:4.0.30319.42000
5 | //
6 | // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае
7 | // повторной генерации кода.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace Platonus_Tester.Properties {
12 |
13 |
14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
17 |
18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
19 |
20 | public static Settings Default {
21 | get {
22 | return defaultInstance;
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/PlatestTest/PlatestTest.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.1
5 |
6 | false
7 |
8 |
9 |
10 |
11 | d37e2a3e-8545-3a39-9f4f-31827c9124ab
12 | 2
13 | 4
14 | tlbimp
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 | ..\Platonus Tester\bin\Release\DocX.dll
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/notice.md:
--------------------------------------------------------------------------------
1 | =========================================================================
2 | == Example NOTICE file for use with the Apache License, Version 2.0, ==
3 | == in this case for the Apache httpd-2.0 distribution. ==
4 | =========================================================================
5 |
6 | Apache HTTP Server
7 | Copyright 1999-2006 The Apache Software Foundation
8 |
9 | This product includes software developed at
10 | The Apache Software Foundation (http://www.apache.org/).
11 |
12 | Portions of this software were developed at the National Center
13 | for Supercomputing Applications (NCSA) at the University of
14 | Illinois at Urbana-Champaign.
15 |
16 | This software contains code derived from the RSA Data Security
17 | Inc. MD5 Message-Digest Algorithm, including various
18 | modifications by Spyglass Inc., Carnegie Mellon University, and
19 | Bell Communications Research, Inc (Bellcore).
20 |
21 | Regular expression support is provided by the PCRE library package,
22 | which is open source software, written by Philip Hazel, and copyright
23 | by the University of Cambridge, England. The original software is
24 | available from
25 | ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/
26 |
--------------------------------------------------------------------------------
/Platonus Tester/Helper/Settings.cs:
--------------------------------------------------------------------------------
1 | namespace Platonus_Tester.Helper
2 | {
3 | ///
4 | /// настройки программы, записывающиеся в XML формате
5 | ///
6 | public class Settings
7 | {
8 | ///
9 | /// Установить лимит вопросов (25 обычно), как на тестировании
10 | ///
11 | public bool EnableLimit { get; set; }
12 | ///
13 | /// Показать ругательные комментарии
14 | ///
15 | public bool ShowSwearing { get; set; }
16 | ///
17 | /// Загружать ли комментарии с репозитория
18 | ///
19 | public bool DownloadSwears { get; set; }
20 | ///
21 | /// Будет добавлена в будущем поддержка двух цветовых схем.
22 | ///
23 | public bool LightColorScheme { get; set; }
24 | ///
25 | /// Количество лимита
26 | ///
27 | public int QuestionLimitCount { get; set; }
28 |
29 | public Settings()
30 | {
31 | EnableLimit = false;
32 | ShowSwearing = false;
33 | DownloadSwears = false;
34 | LightColorScheme = true;
35 | QuestionLimitCount = 25;
36 | }
37 | }
38 | }
--------------------------------------------------------------------------------
/Platonus Tester/ErrorWindow.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/Platest/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Общие сведения об этой сборке предоставляются следующим набором
6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
7 | // связанные со сборкой.
8 | [assembly: AssemblyTitle("Platest")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("Platest")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
18 | // для компонентов COM. Если необходимо обратиться к типу в этой сборке через
19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
20 | [assembly: ComVisible(false)]
21 |
22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
23 | [assembly: Guid("a41424e6-309b-4f20-9988-de56038a02b6")]
24 |
25 | // Сведения о версии сборки состоят из следующих четырех значений:
26 | //
27 | // Основной номер версии
28 | // Дополнительный номер версии
29 | // Номер сборки
30 | // Редакция
31 | //
32 | // Можно задать все значения или принять номер сборки и номер редакции по умолчанию.
33 | // используя "*", как показано ниже:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/ResultComments/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // Общие сведения об этой сборке предоставляются следующим набором
6 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
7 | // связанные со сборкой.
8 | [assembly: AssemblyTitle("ResultComments")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("ResultComments")]
13 | [assembly: AssemblyCopyright("Copyright © 2017")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
18 | // для компонентов COM. Если необходимо обратиться к типу в этой сборке через
19 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
20 | [assembly: ComVisible(false)]
21 |
22 | // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
23 | [assembly: Guid("83d12892-8383-44b3-bc52-585c6909ecbf")]
24 |
25 | // Сведения о версии сборки состоят из следующих четырех значений:
26 | //
27 | // Основной номер версии
28 | // Дополнительный номер версии
29 | // Номер сборки
30 | // Редакция
31 | //
32 | // Можно задать все значения или принять номер сборки и номер редакции по умолчанию.
33 | // используя "*", как показано ниже:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/Platonus Tester/ErrorWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows;
7 | using System.Windows.Controls;
8 | using System.Windows.Data;
9 | using System.Windows.Documents;
10 | using System.Windows.Input;
11 | using System.Windows.Media;
12 | using System.Windows.Media.Imaging;
13 | using System.Windows.Shapes;
14 |
15 | namespace Platonus_Tester
16 | {
17 | ///
18 | /// Логика взаимодействия для ErrorWindow.xaml
19 | ///
20 | public partial class ErrorWindow : Window
21 | {
22 |
23 | private readonly List _errorList;
24 |
25 | public ErrorWindow(List source)
26 | {
27 | InitializeComponent();
28 | _errorList = source;
29 | }
30 |
31 | private void Window_Loaded(object sender, RoutedEventArgs e)
32 | {
33 | listBox.Items.Clear();
34 |
35 | foreach (var error in _errorList)
36 | {
37 | listBox.Items.Add(error);
38 | }
39 | }
40 |
41 | private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
42 | {
43 | var item = (string) listBox.SelectedItem;
44 | textBlock.Text = item;
45 | }
46 |
47 | private void cancelButton_Click(object sender, RoutedEventArgs e)
48 | {
49 | Close();
50 | }
51 |
52 | private void okButton_Click(object sender, RoutedEventArgs e)
53 | {
54 | Close();
55 | }
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/PlatestTest/QuestionProcessorTest.cs:
--------------------------------------------------------------------------------
1 | using Platest.Helpers;
2 | using Platest.Models;
3 | using Xunit;
4 | using System.Collections.Generic;
5 | using System.IO;
6 | using System;
7 |
8 | namespace PlatestTest
9 | {
10 | public class QuestionProcessorTest
11 | {
12 |
13 | [Fact]
14 | public void GetQuestionListResultTest()
15 | {
16 | var controller = new QuestionProcessor();
17 |
18 | // Act
19 | var result = controller.GetQuestionList(SourceFile());
20 |
21 | // Arrange
22 | Assert.IsType>(result);
23 |
24 | Assert.NotNull(result);
25 | }
26 |
27 | [Fact]
28 | public void GetQuestionResultTest()
29 | {
30 | var controller = new QuestionProcessor();
31 |
32 | // Act
33 | var result = controller.GetQuestion(SourceFile().SourceText);
34 |
35 | // Arrange
36 | Assert.IsType(result);
38 | Assert.NotNull(result);
39 | }
40 |
41 | [Fact]
42 | public void GetQuestionResultMissingVariantTest()
43 | {
44 | var controller = new QuestionProcessor();
45 | int variantCount = 0;
46 | // Act
47 | var result = controller.GetQuestionList(SourceFile());
48 | foreach (var res in result)
49 | {
50 | variantCount = res.AnswerList.Count;
51 | // Arrange
52 | Assert.Equal(5, variantCount);
53 | }
54 | }
55 |
56 |
57 | public SourceFile SourceFile()
58 | {
59 |
60 |
61 | var text = File.ReadAllText(@"C:\Users\Gaukhar\source\repos\Platonus-Tester\PlatestTest\test.txt");
62 |
63 | var sf = new SourceFile(text, null, null);
64 | return sf;
65 | }
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/Platonus Tester.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.26228.4
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Platonus Tester", "Platonus Tester\Platonus Tester.csproj", "{CAF474A8-0A6C-4CB0-B38E-E23644D58E77}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Platest", "Platest\Platest.csproj", "{A41424E6-309B-4F20-9988-DE56038A02B6}"
9 | EndProject
10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResultComments", "ResultComments\ResultComments.csproj", "{83D12892-8383-44B3-BC52-585C6909ECBF}"
11 | EndProject
12 | Global
13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
14 | Debug|Any CPU = Debug|Any CPU
15 | Release|Any CPU = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
18 | {CAF474A8-0A6C-4CB0-B38E-E23644D58E77}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
19 | {CAF474A8-0A6C-4CB0-B38E-E23644D58E77}.Debug|Any CPU.Build.0 = Debug|Any CPU
20 | {CAF474A8-0A6C-4CB0-B38E-E23644D58E77}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {CAF474A8-0A6C-4CB0-B38E-E23644D58E77}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {A41424E6-309B-4F20-9988-DE56038A02B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
23 | {A41424E6-309B-4F20-9988-DE56038A02B6}.Debug|Any CPU.Build.0 = Debug|Any CPU
24 | {A41424E6-309B-4F20-9988-DE56038A02B6}.Release|Any CPU.ActiveCfg = Release|Any CPU
25 | {A41424E6-309B-4F20-9988-DE56038A02B6}.Release|Any CPU.Build.0 = Release|Any CPU
26 | {83D12892-8383-44B3-BC52-585C6909ECBF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
27 | {83D12892-8383-44B3-BC52-585C6909ECBF}.Debug|Any CPU.Build.0 = Debug|Any CPU
28 | {83D12892-8383-44B3-BC52-585C6909ECBF}.Release|Any CPU.ActiveCfg = Release|Any CPU
29 | {83D12892-8383-44B3-BC52-585C6909ECBF}.Release|Any CPU.Build.0 = Release|Any CPU
30 | EndGlobalSection
31 | GlobalSection(SolutionProperties) = preSolution
32 | HideSolutionNode = FALSE
33 | EndGlobalSection
34 | EndGlobal
35 |
--------------------------------------------------------------------------------
/Platonus Tester/ResultWindow.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
30 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/ResultComments/ResultComments.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {83D12892-8383-44B3-BC52-585C6909ECBF}
8 | Library
9 | Properties
10 | ResultComments
11 | ResultComments
12 | v4.5.2
13 | 512
14 |
15 |
16 | true
17 | full
18 | false
19 | bin\Debug\
20 | DEBUG;TRACE
21 | prompt
22 | 4
23 |
24 |
25 | pdbonly
26 | true
27 | bin\Release\
28 | TRACE
29 | prompt
30 | 4
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/Platonus Tester/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Resources;
3 | using System.Runtime.CompilerServices;
4 | using System.Runtime.InteropServices;
5 | using System.Windows;
6 |
7 | // Управление общими сведениями о сборке осуществляется с помощью
8 | // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
9 | // связанные со сборкой.
10 | [assembly: AssemblyTitle("Platonus Tester")]
11 | [assembly: AssemblyDescription("")]
12 | [assembly: AssemblyConfiguration("")]
13 | [assembly: AssemblyCompany("github.com/maximgorbatyuk")]
14 | [assembly: AssemblyProduct("Platonus Tester")]
15 | [assembly: AssemblyCopyright("Copyright © Maxim Gorbatyuk")]
16 | [assembly: AssemblyTrademark("")]
17 | [assembly: AssemblyCulture("")]
18 |
19 | // Параметр ComVisible со значением FALSE делает типы в сборке невидимыми
20 | // для COM-компонентов. Если требуется обратиться к типу в этой сборке через
21 | // COM, задайте атрибуту ComVisible значение TRUE для этого типа.
22 | [assembly: ComVisible(false)]
23 |
24 | //Чтобы начать сборку локализованных приложений, задайте
25 | //CultureYouAreCodingWith в файле .csproj
26 | //внутри . Например, если используется английский США
27 | //в своих исходных файлах установите в en-US. Затем отмените преобразование в комментарий
28 | //атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
29 | //строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
30 |
31 | //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
32 |
33 |
34 | [assembly: ThemeInfo(
35 | ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
36 | //(используется, если ресурс не найден на странице
37 | // или в словарях ресурсов приложения)
38 | ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
39 | //(используется, если ресурс не найден на странице,
40 | // в приложении или в каких-либо словарях ресурсов для конкретной темы)
41 | )]
42 |
43 |
44 | // Сведения о версии сборки состоят из следующих четырех значений:
45 | //
46 | // Основной номер версии
47 | // Дополнительный номер версии
48 | // Номер сборки
49 | // Редакция
50 | //
51 | // Можно задать все значения или принять номера сборки и редакции по умолчанию
52 | // используя "*", как показано ниже:
53 | // [assembly: AssemblyVersion("1.0.*")]
54 | [assembly: AssemblyVersion("2.0.0.0")]
55 | [assembly: AssemblyFileVersion("1.0.*.*")]
56 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | ###############################################################################
2 | # Set default behavior to automatically normalize line endings.
3 | ###############################################################################
4 | * text=auto
5 |
6 | ###############################################################################
7 | # Set default behavior for command prompt diff.
8 | #
9 | # This is need for earlier builds of msysgit that does not have it on by
10 | # default for csharp files.
11 | # Note: This is only used by command line
12 | ###############################################################################
13 | #*.cs diff=csharp
14 |
15 | ###############################################################################
16 | # Set the merge driver for project and solution files
17 | #
18 | # Merging from the command prompt will add diff markers to the files if there
19 | # are conflicts (Merging from VS is not affected by the settings below, in VS
20 | # the diff markers are never inserted). Diff markers may cause the following
21 | # file extensions to fail to load in VS. An alternative would be to treat
22 | # these files as binary and thus will always conflict and require user
23 | # intervention with every merge. To do so, just uncomment the entries below
24 | ###############################################################################
25 | #*.sln merge=binary
26 | #*.csproj merge=binary
27 | #*.vbproj merge=binary
28 | #*.vcxproj merge=binary
29 | #*.vcproj merge=binary
30 | #*.dbproj merge=binary
31 | #*.fsproj merge=binary
32 | #*.lsproj merge=binary
33 | #*.wixproj merge=binary
34 | #*.modelproj merge=binary
35 | #*.sqlproj merge=binary
36 | #*.wwaproj merge=binary
37 |
38 | ###############################################################################
39 | # behavior for image files
40 | #
41 | # image files are treated as binary by default.
42 | ###############################################################################
43 | #*.jpg binary
44 | #*.png binary
45 | #*.gif binary
46 |
47 | ###############################################################################
48 | # diff behavior for common document formats
49 | #
50 | # Convert binary document formats to text before diffing them. This feature
51 | # is only available from the command line. Turn it on by uncommenting the
52 | # entries below.
53 | ###############################################################################
54 | #*.doc diff=astextplain
55 | #*.DOC diff=astextplain
56 | #*.docx diff=astextplain
57 | #*.DOCX diff=astextplain
58 | #*.dot diff=astextplain
59 | #*.DOT diff=astextplain
60 | #*.pdf diff=astextplain
61 | #*.PDF diff=astextplain
62 | #*.rtf diff=astextplain
63 | #*.RTF diff=astextplain
64 |
--------------------------------------------------------------------------------
/Platest/Controllers/QuestionManager.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using Platest.Helpers;
5 | using Platest.Interfaces;
6 | using Platest.Models;
7 |
8 | namespace Platest.Controllers
9 | {
10 | ///
11 | /// Класс для обработки массива готовых тестовых вопросов
12 | ///
13 | ///
14 | public class QuestionManager : IQuestionManager
15 | {
16 | private List _list;
17 |
18 |
19 |
20 | private int _firstListCount;
21 |
22 | private readonly IQuestionProvider _questionProvider;
23 |
24 | private int _currentIndex;
25 |
26 | private int _limit;
27 |
28 | public QuestionManager()
29 | {
30 | _list = new List();
31 | _questionProvider = new QuestionProcessor();
32 | }
33 |
34 | public void SetSourceList(SourceFile file)
35 | {
36 | _list = _questionProvider.GetQuestionList(file);
37 | _limit = _list.Count;
38 | _currentIndex = 0;
39 | _firstListCount = _list.Count;
40 | Shuffle();
41 | }
42 |
43 | ///
44 | /// Перемешение вопросов в массиве.
45 | ///
46 | public void Shuffle()
47 | {
48 | var count = _list.Count;
49 | var result = new List(0);
50 | for (var i = 0; i < count; i++)
51 | {
52 | var q = _list[new Random(DateTime.Now.Millisecond + i).Next(_list.Count)];
53 | result.Add(q);
54 | _list.Remove(q);
55 | }
56 | _list = result;
57 | }
58 |
59 | ///
60 | /// Возвращает следующий вопрос. Раньше (до перевода на WPF 04.06.2016) метод удалял
61 | /// возвращаемый вопрос. Сейчас принцип выдачи изменен, так как в планах
62 | /// сделать переход по предыдущим вопросам
63 | ///
64 | ///
65 | public TestQuestion GetNext()
66 | {
67 | if (_currentIndex >= _list.Count || _currentIndex >= _limit)
68 | {
69 | return null;
70 | }
71 | var question = _list[_currentIndex];
72 | _currentIndex++;
73 | return question;
74 | }
75 |
76 | public int GetCount() => _list.Count;
77 |
78 | public int GetFirstListCount() => _firstListCount;
79 |
80 | public void SetQuestionLimit(int limit)
81 | {
82 | _limit = limit > _list.Count? _list.Count : limit;
83 | }
84 |
85 | public int GetCurrentPosition() => _currentIndex;
86 |
87 | public IEnumerable GetErrors() => _questionProvider?.GetErrors();
88 | }
89 | }
--------------------------------------------------------------------------------
/Platest/Helpers/Extensions.cs:
--------------------------------------------------------------------------------
1 | namespace Platest.Helpers
2 | {
3 | public static class Extensions
4 | {
5 | ///
6 | /// Функция для поиска и замены изображений в документе
7 | /// Пробегаюсь по параграфам и нахожу картинки
8 | /// Картинки имею свое имя. Обычно один параграф и есть одна картинка, что упрощает поиск
9 | /// Чтобы в дальнейшем запомнить положение той или иной картинки, я
10 | /// Заменяю место в тексте специальным тегом #picture \\name\\
11 | /// В дальнейшем при обработке я ищу эти теги и заменяю картинками по имени
12 | ///
13 | ///
14 | ///
15 | /// Полный текст документа + теги картинок
16 | public static string ReplaceImages(this string text, Novacode.Container doc)
17 | {
18 | var newText = string.Empty;
19 | foreach (var p in doc.Paragraphs)
20 | {
21 | newText += p.Text;
22 | if (p.Pictures.Count != 0)
23 | {
24 | newText += $"<#picture= {p.Pictures[0].FileName} #>";
25 | }
26 | }
27 | return newText;
28 | }
29 |
30 | ///
31 | /// Функция для замены таблиц в документе текстовым аналогом
32 | /// | столбец | столбец |
33 | /// | строка | строка |
34 | /// Выравнивание пока не реализовано, но пока и так вариант ответа понятен
35 | /// Каждая ячейка в исходном документе была отдельным параграфом, поэтому я передаю и исходный текст,
36 | /// чтобы заменить эти ошибки на презентабельный вид
37 | ///
38 | /// текст с картинками
39 | /// Контейнер документа
40 | /// Полный текст (с картинками) + Таблицы
41 | public static string ReplaceTables(this string text, Novacode.Container doc)
42 | {
43 |
44 | foreach (var p in doc.Tables)
45 | {
46 | var processedText = string.Empty;
47 | var replaceText = string.Empty;
48 | var look = p.Paragraphs;
49 |
50 | for (var i = 0; i < look.Count; i++)
51 | {
52 | if (i != 0 && i % p.ColumnCount == 0)
53 | {
54 | processedText += "\n";
55 | }
56 | replaceText += look[i].Text;
57 | processedText += $"| {look[i].Text} ";
58 |
59 | }
60 |
61 | text = text.Replace(replaceText, processedText);
62 | //processedText += "\n";
63 | }
64 | return text;
65 | }
66 | }
67 | }
--------------------------------------------------------------------------------
/Platonus Tester/Controller/SettingsController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Windows;
4 | using System.Xml.Serialization;
5 | using Platonus_Tester.Helper;
6 |
7 | namespace Platonus_Tester.Controller
8 | {
9 | ///
10 | /// Класс для управления настройками. Настройки записываются в XML формате в файл в той же директории
11 | ///
12 | public abstract class SettingsController
13 | {
14 |
15 | ///
16 | ///
17 | ///
18 | ///
19 | public static void SaveSettings(Settings settings)
20 | {
21 | //var path = Environment.SpecialFolder.ApplicationData;
22 | //var fileName = $"C:\\ProgramData\\Platonus tester\\settings.xml";
23 | var fileName = $"{Environment.CurrentDirectory}\\settings.xml";
24 | StreamWriter stream = null;
25 | try
26 | {
27 | stream = new StreamWriter(File.Open(fileName, FileMode.Create));
28 | var serializer = new XmlSerializer(typeof(Settings));
29 | serializer.Serialize(stream, settings);
30 | }
31 | catch (Exception ex)
32 | {
33 | //ignored
34 | }
35 | finally
36 | {
37 | stream?.Close();
38 | }
39 | }
40 |
41 | ///
42 | /// Загрузка настроек из файла. Если происходит ошибка, возвращаются станлартные настройки
43 | ///
44 | ///
45 | public static Settings Load()
46 | {
47 | //var path = Environment.SpecialFolder.ApplicationData;
48 | var fileName = $"{Environment.CurrentDirectory}\\settings.xml";
49 | Settings settings = null;
50 | StreamReader stream = null;
51 | try
52 | {
53 | if (File.Exists(fileName))
54 | {
55 | stream = new StreamReader(File.Open(fileName, FileMode.Open));
56 | var serializer = new XmlSerializer(typeof(Settings));
57 | settings = serializer.Deserialize(stream) as Settings;
58 | }
59 | else
60 | {
61 | settings = new Settings();
62 | SaveSettings(settings);
63 | }
64 | }
65 | catch (Exception ex)
66 | {
67 |
68 | define_error("Ошибка 4.2\nЗагружены настройки по умолчанию " + ex.Message);
69 |
70 | }
71 | finally
72 | {
73 | stream?.Close();
74 | }
75 | return settings;
76 | }
77 |
78 | private static void define_error(string text)
79 | {
80 | MessageBox.Show(text);
81 | }
82 | }
83 | }
--------------------------------------------------------------------------------
/Platonus Tester/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // Этот код создан программным средством.
4 | // Версия среды выполнения: 4.0.30319.42000
5 | //
6 | // Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
7 | // код создан повторно.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace Platonus_Tester.Properties
12 | {
13 |
14 |
15 | ///
16 | /// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
17 | ///
18 | // Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
19 | // класс с помощью таких средств, как ResGen или Visual Studio.
20 | // Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
21 | // с параметром /str или заново постройте свой VS-проект.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources
26 | {
27 |
28 | private static global::System.Resources.ResourceManager resourceMan;
29 |
30 | private static global::System.Globalization.CultureInfo resourceCulture;
31 |
32 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
33 | internal Resources()
34 | {
35 | }
36 |
37 | ///
38 | /// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
39 | ///
40 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
41 | internal static global::System.Resources.ResourceManager ResourceManager
42 | {
43 | get
44 | {
45 | if ((resourceMan == null))
46 | {
47 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Platonus_Tester.Properties.Resources", typeof(Resources).Assembly);
48 | resourceMan = temp;
49 | }
50 | return resourceMan;
51 | }
52 | }
53 |
54 | ///
55 | /// Переопределяет свойство CurrentUICulture текущего потока для всех
56 | /// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
57 | ///
58 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
59 | internal static global::System.Globalization.CultureInfo Culture
60 | {
61 | get
62 | {
63 | return resourceCulture;
64 | }
65 | set
66 | {
67 | resourceCulture = value;
68 | }
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/ResultComments/Models/Comment.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using ResultComments.Helpers;
4 |
5 | namespace ResultComments.Models
6 | {
7 | ///
8 | /// Этот класс является предком для класса ругательств
9 | /// Здесь определены все методы, а так же хэши комментариев
10 | /// В дочернем классе переопределены именно хэши
11 | ///
12 | public class Comment
13 | {
14 |
15 | protected List _hash_100;
16 | protected List _hash_99_90;
17 | protected List _hash_89_75;
18 | protected List _hash_74_60;
19 | protected List _hash_59_50;
20 | protected List _hash_49;
21 |
22 | public Comment()
23 | {
24 | InitiateHashes();
25 | }
26 |
27 | ///
28 | /// Функция возвращает рандомный элемент из массива комментариев
29 | ///
30 | ///
31 | ///
32 | public string Get(double res)
33 | {
34 |
35 | if (res >= 100) return GetRandomSwear(_hash_100);
36 |
37 | if (res >= 90 && res < 100) return GetRandomSwear(_hash_99_90);
38 |
39 | if (res >= 75 && res < 90) return GetRandomSwear(_hash_89_75);
40 |
41 | if ((res >= 60) && (res < 75)) return GetRandomSwear(_hash_74_60);
42 |
43 | if ((res >= 50) && (res < 60)) return GetRandomSwear(_hash_59_50);
44 |
45 | return GetRandomSwear(_hash_49);
46 | }
47 |
48 | protected virtual string GetRandomSwear(List hash)
49 | {
50 | return hash[GetRandomNumber(hash.Count)];
51 | }
52 |
53 | protected virtual int GetRandomNumber(int count)
54 | {
55 | return new Random().Next(count);
56 | }
57 |
58 | ///
59 | /// Инициализация массивов, которая перезаписывается в дочерних элменетах
60 | ///
61 | protected virtual void InitiateHashes()
62 | {
63 | _hash_100 = new List
64 | {
65 | "Молодец! Так держать! Эта сессия - ничто для тебя!"
66 | };
67 | //---------------------------------
68 | _hash_99_90 = new List
69 | {
70 | "Круто! Еще немного подготовки - и стольник тебе обеспечен!"
71 | };
72 | //---------------------------------
73 | _hash_89_75 = new List
74 | {
75 | "Я знаю, ты можешь лучше"
76 | };
77 | //---------------------------------
78 | _hash_74_60 = new List
79 | {
80 | "Ну ничего, в другой раз повезет"
81 | };
82 | _hash_59_50 = new List
83 | {
84 | "Слабовато, но стоит тебе подготовиться, и оценка будет выше!"
85 | };
86 | //--------------------------------
87 | _hash_49 = new List
88 | {
89 | "Ну как же так? Это ведь легкий тест"
90 | };
91 | }
92 | }
93 | }
--------------------------------------------------------------------------------
/Platest/Platest.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {A41424E6-309B-4F20-9988-DE56038A02B6}
8 | Library
9 | Properties
10 | Platest
11 | Platest
12 | v4.5.2
13 | 512
14 |
15 |
16 | true
17 | full
18 | false
19 | bin\Debug\
20 | DEBUG;TRACE
21 | prompt
22 | 4
23 |
24 |
25 | pdbonly
26 | true
27 | bin\Release\
28 | TRACE
29 | prompt
30 | 4
31 |
32 |
33 |
34 | ..\packages\DocX.1.0.0.22\lib\net40\DocX.dll
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/Platonus Tester/SettingsForm.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
33 |
35 |
37 |
39 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/ResultComments/Models/Swear.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace ResultComments.Models
4 | {
5 | ///
6 | /// Класс потомок комментария. Перезаписывается только хэш набор комментариев
7 | ///
8 | public class Swear : Comment
9 | {
10 | protected override void InitiateHashes()
11 | {
12 | _hash_100 = new List
13 | {
14 | "Возьми с полки пирожок, долбанный очкарик",
15 | "Тебе мозги не жмут черепушку?",
16 | "Батя - повелитель белого трона, маманя смотрит Рен-ТВ. И в кого ты такой умный...",
17 | "В церковь сходи, бес в тебе сидит, от лукавого это все",
18 | "Ублюдок, мать твою! А ну иди сюда, говно собачье! А? Сдуру решил на стольник написать?"
19 | };
20 | //---------------------------------
21 | _hash_99_90 = new List
22 | {
23 | "Если такой головастый, то что на стольник не пишешь?",
24 | "У тебя личная жизнь то есть, законченный ботаник?",
25 | "Тут должна была быть запись о том, что ты молодец, но ты будешь послан этой программой!",
26 | "Ну ничего страшного! Ты ж не даун на стольники писать.",
27 | "Опять не 100? Ты в который раз уже пишешь тест, а все так и не научился ничему"
28 | };
29 | //---------------------------------
30 | _hash_89_75 = new List
31 | {
32 | "Даже твоя толстая мамаша может лучше",
33 | "Серьезно? Почему ты не делаешь на 5? Система тестирования легкая ведь!",
34 | "Ты разве не в курсе, что этот тест расчитан на второй класс?",
35 | "Ты пишешь тесты, как маленькая девочка",
36 | "Люк - сын Вейдара, а ты - соседа по лестничной площадке"
37 | };
38 | //---------------------------------
39 | _hash_74_60 = new List
40 | {
41 | "Ну и что ты скажешь своей мамаше?",
42 | "Когда твоих родителей спросят о твоих успехах, они ответят: \"Мой ребенок красивый\"",
43 | "Ты не смог выучить этот простейший тест для детей с синдромом Дауна?",
44 | "Тебя в детстве роняли?",
45 | "Помню я одного аутиста, который пытался засунуть кубик в круглую дырку. В свои 15 лет..."
46 | };
47 | //--------------------------------
48 | _hash_59_50 = new List
49 | {
50 | "Ну и что тут такого? Да любой бомжара может написать тест лучше тебя",
51 | "Твои родители умные люди, раз заставляют тебя учиться в универе. А ты... Ты, наверное, приемный.",
52 | "Утешай себя, что и Эйнштейн учился на двойки",
53 | "Помни, что это - последняя грань. Дальше только аутизм",
54 | "Ты понимаешь, что это начало конца?"
55 | };
56 | //--------------------------------
57 | _hash_49 = new List
58 | {
59 | "У меня нет слов.. Это просто невозможно",
60 | "Знаешь, я как раз искал недоразвитых для социальной рекламы...",
61 | "Эту надпись видят только аутисты, которые не могут даже в проходной",
62 | "Если бы твой мозг был планетой, то ее бы не было",
63 | "Зачем тебе учеба? Лучше мемасики в интернетике погляди да картиночки полайкай"
64 | };
65 | }
66 | }
67 | }
--------------------------------------------------------------------------------
/Platonus Tester/ResultWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows;
7 | using System.Windows.Controls;
8 | using System.Windows.Data;
9 | using System.Windows.Documents;
10 | using System.Windows.Input;
11 | using System.Windows.Media;
12 | using System.Windows.Media.Imaging;
13 | using System.Windows.Shapes;
14 | using Platest.Models;
15 | using Platonus_Tester.Controller;
16 | using Platonus_Tester.Helper;
17 | using ResultComments.Models;
18 |
19 | namespace Platonus_Tester
20 | {
21 | ///
22 | /// Логика взаимодействия для ResultWindow.xaml
23 | ///
24 | public partial class ResultWindow : Window
25 | {
26 |
27 | private int _rigth;
28 | private readonly List _hash;
29 | private readonly Swear _swearHelper;
30 | private readonly Comment _goodHelper;
31 | private readonly Settings _settings;
32 |
33 | public ResultWindow(List hash, Comment good, Comment bad)
34 | {
35 | InitializeComponent();
36 | _hash = hash;
37 | _goodHelper = good;
38 | _swearHelper = bad as Swear;
39 | _settings = SettingsController.Load();
40 | _rigth = 0;
41 | }
42 |
43 | private void Window_Loaded(object sender, RoutedEventArgs e)
44 | {
45 | Title = Const.ResultTitle;
46 | answerTextBlock.Text = Const.PickAnAnswer;
47 | foreach (var a in _hash)
48 | {
49 | if (a.IsItCorrect)
50 | {
51 | _rigth++;
52 | }
53 | }
54 | TextBlock_AnswerCount.Text = $"Всего вопросов: {_hash.Count}. Отмечено верно: {_rigth}";
55 | var result = (double)_rigth / _hash.Count;
56 | result = result * 100;
57 | commentTextBlock.Text = $"Ваш результат: {result:#.##}%\n{GetComment(result)}";
58 | LoadListBox(_hash);
59 | }
60 |
61 | private string GetComment(double res)
62 | {
63 | return _settings.ShowSwearing ? _swearHelper.Get(res) : _goodHelper.Get(res);
64 | }
65 |
66 | private void LoadListBox(IEnumerable hash)
67 | {
68 | listBox.Items.Clear();
69 | foreach (var q in hash)
70 | {
71 | var text = q.IsItCorrect ? $"Верно: {q}" : $"Неверно: {q}";
72 | listBox.Items.Add(text);
73 | //var item = (ListBoxItem)listBox.Items.
74 | //item.Style = (Style)FindResource(q.IsItCorrect ? "CorrectAnswerStyle" : "IncorrectAnswerStyle");
75 | }
76 | }
77 |
78 | private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
79 | {
80 | var index = listBox.SelectedIndex;
81 | var item = _hash[index];
82 | answerTextBlock.Text = $"{item.AskQuestion}\nПравильный ответ: {item.CorrectAnswer}";
83 | answerTextBlock.Text += !item.IsItCorrect ? $"\nОтвет юзера: {item.ChosenAnswer}" : "";
84 | answerTextBlock.Background = new SolidColorBrush(
85 | item.IsItCorrect ? Const.CorrectColor : Const.IncorrectColor);
86 | }
87 |
88 | private void okButton_Click(object sender, RoutedEventArgs e)
89 | {
90 | Close();
91 | }
92 |
93 | private void cancelButton_Click(object sender, RoutedEventArgs e)
94 | {
95 | Close();
96 | }
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/Platonus Tester/SettingsForm.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 | using System.Windows;
7 | using System.Windows.Controls;
8 | using System.Windows.Data;
9 | using System.Windows.Documents;
10 | using System.Windows.Input;
11 | using System.Windows.Media;
12 | using System.Windows.Media.Imaging;
13 | using System.Windows.Shapes;
14 | using Platonus_Tester.Controller;
15 | using Platonus_Tester.Helper;
16 |
17 | namespace Platonus_Tester
18 | {
19 | ///
20 | /// Логика взаимодействия для SettingsForm.xaml
21 | ///
22 | public partial class SettingsForm : Window
23 | {
24 | public SettingsForm()
25 | {
26 | InitializeComponent();
27 | }
28 |
29 | private void Window_Loaded(object sender, RoutedEventArgs e)
30 | {
31 | SetLimitCountTextBlock.Text = Const.LimitCountSet;
32 | LimitEnableTextBlock.Text = Const.LimitEnableText;
33 | ShowSwearsEnabledTextBlock.Text = Const.ShowSwearEnableText;
34 | DownloadSwearsTextBlock.Text = Const.DownloadSwearEnableText;
35 | ColorSchemeTextBlock.Text = Const.ColorChemeEnabledText;
36 | //----------------------
37 | var settings = SettingsController.Load();
38 | LimitEnableCheckBox.IsChecked = settings.EnableLimit;
39 | LimitEnableCheckBox.Content = settings.EnableLimit ? Const.Enabled : Const.Disabled;
40 |
41 | LimitCountTextBox.Text = $"{settings.QuestionLimitCount}";
42 |
43 | ShowSwearsCheckBox.IsChecked = settings.ShowSwearing;
44 | ShowSwearsCheckBox.Content = settings.ShowSwearing ? Const.Enabled : Const.Disabled;
45 |
46 | DownloadSwearsCheckBox.IsChecked = settings.DownloadSwears;
47 | DownloadSwearsCheckBox.Content = settings.DownloadSwears ? Const.Enabled : Const.Disabled;
48 |
49 | ColorSchemeCheckBox.IsChecked = settings.LightColorScheme;
50 | ColorSchemeCheckBox.Content = settings.LightColorScheme ? Const.Enabled : Const.Disabled;
51 | }
52 |
53 | private void SaveSettings()
54 | {
55 | var limitCount = 25;
56 | try
57 | {
58 | limitCount = int.Parse(LimitCountTextBox.Text);
59 | }
60 | catch (Exception ex)
61 | {
62 |
63 | }
64 | var settings = new Settings
65 | {
66 | EnableLimit = LimitEnableCheckBox.IsChecked != null && LimitEnableCheckBox.IsChecked.Value,
67 | ShowSwearing = ShowSwearsCheckBox.IsChecked != null && ShowSwearsCheckBox.IsChecked.Value,
68 | DownloadSwears = DownloadSwearsCheckBox.IsChecked != null && DownloadSwearsCheckBox.IsChecked.Value,
69 | LightColorScheme = ColorSchemeCheckBox.IsChecked != null && ColorSchemeCheckBox.IsChecked.Value,
70 | QuestionLimitCount = limitCount
71 | };
72 | SettingsController.SaveSettings(settings);
73 | }
74 |
75 | private void OkButton_Click(object sender, RoutedEventArgs e)
76 | {
77 | SaveSettings();
78 | Close();
79 | }
80 |
81 | private void CancelButton_Click(object sender, RoutedEventArgs e)
82 | {
83 | Close();
84 | }
85 |
86 | private void CheckBox_Click(object sender, RoutedEventArgs e)
87 | {
88 | var cb = (CheckBox) sender;
89 | try
90 | {
91 | if (cb.IsChecked == null) return;
92 | cb.Content = cb.IsChecked.Value ? Const.Enabled : Const.Disabled;
93 | }
94 | catch
95 | {
96 | // ignored
97 | }
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/Platonus Tester/Helper/Const.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Reflection;
3 | using System.Windows.Media;
4 |
5 | namespace Platonus_Tester.Helper
6 | {
7 | ///
8 | /// Here I tryed to make an imitation of String resource file
9 | /// This variables a assigned to Control-components contents and titles
10 | /// Also here Color const placed.
11 | ///
12 | public class Const
13 | {
14 | public static readonly string ApplicationName = "Platonus Tester";
15 | public static readonly string DescriptionText =
16 | "Краткое описание: \n " +
17 | "Программа работает с файлами формата*.txt, *.doc и *.docx. " +
18 | "Достаточно просто перетянуть файл в форму или выбрать в диалоговом окне\n\n" +
19 | "Более подробно можете узнать в описании программы, доступном на ГитХабе разработчика. " +
20 | "Кнопка 'О программе' как раз перенаправит пользователя на сайт с описанием.\n\n" +
21 | "В программе присутствут ругательства! Если вы не желаете их видеть, то настройте вывод ругательств в настройках. " +
22 | "По умолчанию они выключены";
23 |
24 | public static readonly string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
25 |
26 | public static readonly string WelcomeText = "Добро пожаловать в программу тестирования";
27 | public static readonly string LoadSourceFile = "Загрузить тест";
28 | public static readonly string StartTesting = "Начать тест";
29 | public static readonly string CheckQuestion = "Проверить вопрос";
30 | public static readonly string ProgrammSetings = "Настройки программы";
31 | public static readonly string DraggingFiles = "Захватываю файл";
32 | public static readonly string FileProcessing = "Загружается файл. Это может занять некоторое время";
33 | public static readonly string ShowResult = "Показать результат";
34 | public static readonly string SwearsEnabled = "Ругательства включены. Так желает юзер";
35 | public static readonly string SwearsDisabled = "Ругательства выключены";
36 | public static readonly string NextQuestion = "Следующий вопрос";
37 | public static readonly string WrongFilename = "Неверный формат файла";
38 | // public static readonly string MissingVariant = "Ошибка: отсутствует вариант ответа";
39 | public static readonly string CheckThis = "Проверить";
40 | public static readonly string ProcessingProblem = $"Возникли проблемы с обработкой вопросов";
41 | public static readonly string ResultTitle = "Результаты тестирования";
42 |
43 | public static readonly string LimitEnabled = "Лимит включен";
44 | public static readonly string LimitDisabled = "Все вопросы";
45 |
46 | public static readonly Color LigthBlack = Color.FromArgb(118, 0, 0, 0);
47 | public static readonly Color LigthBackgroundColor = Color.FromArgb(255, 245, 245, 245);
48 | public static readonly Color DarkBackgroundColor = Color.FromArgb(255, 43, 43, 43);
49 |
50 | public static readonly Color LigthFontColor = Color.FromArgb(255, 33, 33, 33);
51 | public static readonly Color DarkhFontColor = Color.FromArgb(255, 228, 228, 228);
52 |
53 | public static readonly Color CorrectColor = Color.FromArgb(255, 144, 232, 121);
54 | public static readonly Color IncorrectColor = Color.FromArgb(255, 233, 107, 107);
55 |
56 | public static readonly string InviteToLoadFile = "Поместите файл в окно";
57 | public static readonly string PickAnAnswer = "Выберите вопрос для просмотра";
58 |
59 | public static readonly string Enabled = "Вкл";
60 | public static readonly string Disabled = "Выкл";
61 | public static readonly string LimitEnableText = "Установить лимит вопросов (не все вопросы будут выведены)";
62 | public static readonly string LimitCountSet = "Установить число лимита вопросов";
63 | public static readonly string ShowSwearEnableText = "Показывать ругательства ;) в комментариях";
64 | public static readonly string DownloadSwearEnableText = "Загружать ругательства ;) из GitHub";
65 | public static readonly string ColorChemeEnabledText = "Светлая цветовая схема";
66 | public static readonly string SettingsText = "Настройки";
67 | }
68 | }
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # Platonus Tester
2 | Замечательно, что Вы зашли в репозиторий этого проекта!
3 | Ну или Вас "забросило" сюда, потому что Вы нажали "О программе". Anyway ....
4 |
5 | | Вопрос | Ответ |
6 | |--------|-------|
7 | | Что это? | Программа для тестирования в домашних условиях |
8 | | Для кого? | Для студентов Казахстана, у которых сессия проводится в системе Platonus |
9 | | Какие требования к ОС? | Минимальная ОС: Windows 7, установленный пакет .Net Framework версии 4.5.2 минимум. Установить можно со [страницы](https://www.microsoft.com/ru-ru/download/details.aspx?id=48130). Или просто забить в гугл ".Net Framework" |
10 | | Кто автор? | Мой профиль в православном [Вконтакте](https://vk.com/maximgorbatyuk) |
11 | | А зачем мне ссылки? | Чтобы прислать мне багрепорт со скриншотом или сообщить свои предложения и пожелания |
12 | | Сколько стоит? | Распространяется свободно. Юзай, зубри, высший балл получай |
13 | | Как использовать? | В программе есть инструкция, но в целом - ничего сложного |
14 | | Как скачать?| [Прямая ссылка](https://github.com/maximgorbatyuk/Platonus-Tester/releases/tag/1.0.0) на zip-архив, в котором запакованы все файлы. Скачать, распаковать и не забыть быть классным |
15 |
16 | ## Возможности программы
17 | * Возможность прохождения тестирования по системе Platonus
18 | * Автоматическая обработка данных
19 | * Работа с файлами Word (*.docx и *.doc)
20 | * Обработка и отображение изображений в вопросах
21 | * Обработка и отображение таблиц в вопросах
22 | * Загрузка новых комментариев к результату тестирования
23 | * Комментарии Вы можете предлагать сами через Pull request в этом репозитории (Если не знаете как, но горите желанием, ссылки на профили разработчика оставлены не просто так)
24 |
25 |
26 | ## Планы проекта
27 | * [ ] Создать инсталлятор проекта
28 | * [ ] Создать утилиту обновления в атоматическом режиме
29 | * [x] Рефакторинг для оптимизации работы. Например, переработка архитектуры проекта в соответствии (хотя бы приблизительно) с объектно-ориентированными паттернами.
30 | * [x] Рефакторинг интерфейса программы. Перевод на WPF, возможно. Приведение к минималистическому дизайну(_СДЕЛАНО. Информация ниже_)
31 | * [x] Организовать две версии программы: x64 и х32, чтобы была возможность открыть на всех операционных системах(_нет необходимости. Сделал только x32_)
32 | * [x] _Основное!_ Разработать поддержку доковских файлов и картинок соответственно, чтобы было *идеально* (ну как сказать)
33 | * [ ] Найти единомышленников, которые помогли бы с интерфейсом и некоторыми доработками. Ну и тренировка пул-реквестов что-ле.
34 | * [x] Сделать вывод версий файла. Чтобы была возможность скачать различные версии программы из репозитория (_Нет необходимости_)
35 | * [ ] Сделать проверку на ТАМОСовские артефакты ([q]3:1: Question [a][+] variant)
36 |
37 | ## Описание программы
38 | Этот репозиторий - эволюция предыдущего [проекта](https://github.com/maximgorbatyuk/Test-Unit-Project/), построенного на базе WinForms. WinForms ограничивал в создании responsive UI, а замена на WPF в рамках одного проекта не представлялась возможным. Было решено (03.06.2016) создать новый проект и перенести функционал (читай классы) сюда. За один вечер и одно утро было сделано, что сподвигло на рефакторинг, изменение структуры некоторых классов, способствовало открытию нового функционала C# (BackgroundWorker). Есть и минусы, но о них потом. Ниже описание из старого проекта.
39 |
40 | Программа выводит короткий комментарий, исходя из результата тестирования. Комментарий может быть "спокойным" и "ругательным". Вывод ругательств настраивается и по умолчанию выключен. В случае, если в вопросе только 4 варианта ответа, то пятый вариант ответа будет выглядеть следующим образом: "Ошибка: вопрос содержит только 4 варианта ответа". При возникновении проблемы при обработке вопроса будет выдано сообщение об ошибке и текст вопроса.
41 |
42 | ## Лицензия
43 | Программа разработана исключительно в целях подготовки разработчика и его одногруппников к сессии, посему распространяется свободно и не несет в себе цели на коммерческую прибыль. Но в случае, если юзер использует программу в коммерческих целях, желательно сообщить об этом разработчику и разделить деньги поровну.
44 |
45 | Обычно подобное ПО лицензируется по [Apache License](https://ru.wikipedia.org/wiki/%D0%9B%D0%B8%D1%86%D0%B5%D0%BD%D0%B7%D0%B8%D1%8F_Apache).
46 | Чем я хуже? Посему объявляю данное ПО лицензируемым [Apache](https://github.com/maximgorbatyuk/Platonus-Tester/blob/master/license.md).
47 | Можно менять, распространять, но нельзя изменять имя. А если Вы используете программу в коммерческих целях, но перестаньте это делать, пожалуйста. Это нехорошо и неправильно.
48 |
49 |
50 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | # [Rr]elease/
17 | # [Rr]eleases/
18 | [Xx]64/
19 | [Xx]86/
20 | [Bb]uild/
21 | bld/
22 | # [Bb]in/
23 | [Oo]bj/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 | # Uncomment if you have tasks that create the project's static files in wwwroot
28 | #wwwroot/
29 |
30 | # MSTest test Results
31 | [Tt]est[Rr]esult*/
32 | [Bb]uild[Ll]og.*
33 |
34 | # NUNIT
35 | *.VisualState.xml
36 | TestResult.xml
37 |
38 | # Build Results of an ATL Project
39 | [Dd]ebugPS/
40 | [Rr]eleasePS/
41 | dlldata.c
42 |
43 | # DNX
44 | project.lock.json
45 | artifacts/
46 |
47 | *_i.c
48 | *_p.c
49 | *_i.h
50 | *.ilk
51 | *.meta
52 | *.obj
53 | *.pch
54 | *.pdb
55 | *.pgc
56 | *.pgd
57 | *.rsp
58 | *.sbr
59 | *.tlb
60 | *.tli
61 | *.tlh
62 | *.tmp
63 | *.tmp_proj
64 | *.log
65 | *.vspscc
66 | *.vssscc
67 | .builds
68 | *.pidb
69 | *.svclog
70 | *.scc
71 |
72 | # Chutzpah Test files
73 | _Chutzpah*
74 |
75 | # Visual C++ cache files
76 | ipch/
77 | *.aps
78 | *.ncb
79 | *.opendb
80 | *.opensdf
81 | *.sdf
82 | *.cachefile
83 | *.VC.db
84 |
85 | # Visual Studio profiler
86 | *.psess
87 | *.vsp
88 | *.vspx
89 | *.sap
90 |
91 | # TFS 2012 Local Workspace
92 | $tf/
93 |
94 | # Guidance Automation Toolkit
95 | *.gpState
96 |
97 | # ReSharper is a .NET coding add-in
98 | _ReSharper*/
99 | *.[Rr]e[Ss]harper
100 | *.DotSettings.user
101 |
102 | # JustCode is a .NET coding add-in
103 | .JustCode
104 |
105 | # TeamCity is a build add-in
106 | _TeamCity*
107 |
108 | # DotCover is a Code Coverage Tool
109 | *.dotCover
110 |
111 | # NCrunch
112 | _NCrunch_*
113 | .*crunch*.local.xml
114 | nCrunchTemp_*
115 |
116 | # MightyMoose
117 | *.mm.*
118 | AutoTest.Net/
119 |
120 | # Web workbench (sass)
121 | .sass-cache/
122 |
123 | # Installshield output folder
124 | [Ee]xpress/
125 |
126 | # DocProject is a documentation generator add-in
127 | DocProject/buildhelp/
128 | DocProject/Help/*.HxT
129 | DocProject/Help/*.HxC
130 | DocProject/Help/*.hhc
131 | DocProject/Help/*.hhk
132 | DocProject/Help/*.hhp
133 | DocProject/Help/Html2
134 | DocProject/Help/html
135 |
136 | # Click-Once directory
137 | publish/
138 |
139 | # Publish Web Output
140 | *.[Pp]ublish.xml
141 | *.azurePubxml
142 |
143 | # TODO: Un-comment the next line if you do not want to checkin
144 | # your web deploy settings because they may include unencrypted
145 | # passwords
146 | #*.pubxml
147 | *.publishproj
148 |
149 | # NuGet Packages
150 | *.nupkg
151 | # The packages folder can be ignored because of Package Restore
152 | **/packages/*
153 | # except build/, which is used as an MSBuild target.
154 | !**/packages/build/
155 | # Uncomment if necessary however generally it will be regenerated when needed
156 | #!**/packages/repositories.config
157 | # NuGet v3's project.json files produces more ignoreable files
158 | *.nuget.props
159 | *.nuget.targets
160 |
161 | # Microsoft Azure Build Output
162 | csx/
163 | *.build.csdef
164 |
165 | # Microsoft Azure Emulator
166 | ecf/
167 | rcf/
168 |
169 | # Microsoft Azure ApplicationInsights config file
170 | ApplicationInsights.config
171 |
172 | # Windows Store app package directory
173 | AppPackages/
174 | BundleArtifacts/
175 |
176 | # Visual Studio cache files
177 | # files ending in .cache can be ignored
178 | *.[Cc]ache
179 | # but keep track of directories ending in .cache
180 | !*.[Cc]ache/
181 |
182 | # Others
183 | ClientBin/
184 | [Ss]tyle[Cc]op.*
185 | ~$*
186 | *~
187 | *.dbmdl
188 | *.dbproj.schemaview
189 | *.pfx
190 | *.publishsettings
191 | node_modules/
192 | orleans.codegen.cs
193 |
194 | # RIA/Silverlight projects
195 | Generated_Code/
196 |
197 | # Backup & report files from converting an old project file
198 | # to a newer Visual Studio version. Backup files are not needed,
199 | # because we have git ;-)
200 | _UpgradeReport_Files/
201 | Backup*/
202 | UpgradeLog*.XML
203 | UpgradeLog*.htm
204 |
205 | # SQL Server files
206 | *.mdf
207 | *.ldf
208 |
209 | # Business Intelligence projects
210 | *.rdl.data
211 | *.bim.layout
212 | *.bim_*.settings
213 |
214 | # Microsoft Fakes
215 | FakesAssemblies/
216 |
217 | # GhostDoc plugin setting file
218 | *.GhostDoc.xml
219 |
220 | # Node.js Tools for Visual Studio
221 | .ntvs_analysis.dat
222 |
223 | # Visual Studio 6 build log
224 | *.plg
225 |
226 | # Visual Studio 6 workspace options file
227 | *.opt
228 |
229 | # Visual Studio LightSwitch build output
230 | **/*.HTMLClient/GeneratedArtifacts
231 | **/*.DesktopClient/GeneratedArtifacts
232 | **/*.DesktopClient/ModelManifest.xml
233 | **/*.Server/GeneratedArtifacts
234 | **/*.Server/ModelManifest.xml
235 | _Pvt_Extensions
236 |
237 | # LightSwitch generated files
238 | GeneratedArtifacts/
239 | ModelManifest.xml
240 |
241 | # Paket dependency manager
242 | .paket/paket.exe
243 |
244 | # FAKE - F# Make
245 | .fake/
--------------------------------------------------------------------------------
/Platonus Tester/Helper/UInterfaceHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Drawing;
3 | using System.IO;
4 | using System.Windows;
5 | using System.Windows.Controls;
6 | using System.Windows.Media;
7 | using System.Windows.Media.Imaging;
8 | using System.Windows.Threading;
9 | using Image = System.Windows.Controls.Image;
10 |
11 | namespace Platonus_Tester.Helper
12 | {
13 | ///
14 | /// Класс для вспомогательных функций обработки компонентов формы, чтобы сделать код в UI классах чище
15 | /// До версии 2.0 была необходимость в использовании Dispatcher/Invoke для обновления компонентов
16 | /// не из UI потока
17 | ///
18 | public abstract class UInterfaceHelper
19 | {
20 | public static void SetWidth(Control label, int width)
21 | {
22 | Application.Current.Dispatcher.BeginInvoke(
23 | DispatcherPriority.Background,
24 | new Action(() => label.Width = width));
25 |
26 | //label.Dispatcher.Invoke(DispatcherPriority.Normal,
27 | // new Action(w => label.Width = w), width);
28 | }
29 |
30 |
31 | public static void SetText(ContentControl control, string text)
32 | {
33 | control.Dispatcher.Invoke(DispatcherPriority.Normal,
34 | new Action(s => control.Content = s), text);
35 | }
36 |
37 | public static void SetEnable(Control control, bool state)
38 | {
39 | control.Dispatcher.Invoke(DispatcherPriority.Normal,
40 | new Action(s => control.IsEnabled = s), state);
41 | }
42 |
43 | public static void SetVisible(ContentControl control, bool state)
44 | {
45 | var visibiliy = state ? Visibility.Visible : Visibility.Hidden;
46 | control.Dispatcher.Invoke(DispatcherPriority.Normal,
47 | new Action(s => control.Visibility = s), visibiliy);
48 | }
49 |
50 | public static void SetVisible(Image control, bool state)
51 | {
52 | var visibiliy = state ? Visibility.Visible : Visibility.Hidden;
53 | control.Dispatcher.Invoke(DispatcherPriority.Normal,
54 | new Action(s => control.Visibility = s), visibiliy);
55 | }
56 |
57 | public static ImageSource GetImageSource(System.Drawing.Image s)
58 | {
59 | ImageSource result = null;
60 | using (var memory = new MemoryStream())
61 | {
62 | s.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
63 | memory.Position = 0;
64 | var bitmapimage = new BitmapImage();
65 | bitmapimage.BeginInit();
66 | bitmapimage.StreamSource = memory;
67 | bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
68 | bitmapimage.EndInit();
69 |
70 | result = bitmapimage;
71 | }
72 | return result;
73 | }
74 |
75 | public static void SetImage(Image control, System.Drawing.Image image)
76 | {
77 |
78 | Func convert = delegate(System.Drawing.Image s)
79 | {
80 | using (var memory = new MemoryStream())
81 | {
82 | s.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
83 | memory.Position = 0;
84 | var bitmapimage = new BitmapImage();
85 | bitmapimage.BeginInit();
86 | bitmapimage.StreamSource = memory;
87 | bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
88 | bitmapimage.EndInit();
89 |
90 | var toReturn = bitmapimage;
91 | return toReturn;
92 | }
93 | };
94 |
95 | Application.Current.Dispatcher.Invoke(
96 | DispatcherPriority.Normal,
97 | new Action(() => control.Source = convert(image) ));
98 |
99 | }
100 |
101 | public static string GetContent(ContentControl control)
102 | {
103 | Func convert = c => (string) c.Content;
104 | string result = null;
105 | Application.Current.Dispatcher.Invoke(
106 | DispatcherPriority.Normal,
107 | new Action(() => result = convert(control)));
108 | return result;
109 | }
110 |
111 |
112 | public static void SetProgressValue(ProgressBar control, int value)
113 | {
114 | control.Dispatcher.Invoke(DispatcherPriority.Normal,
115 | new Action(s => control.Value = s), value);
116 | }
117 |
118 | public static void PaintBackColor(ContentControl sender, bool rigth)
119 | {
120 | sender.Background = new SolidColorBrush(rigth ? Const.CorrectColor : Const.IncorrectColor );
121 | }
122 |
123 | public static void PaintBackColor(System.Windows.Shapes.Shape sender, bool rigth)
124 | {
125 | sender.Fill = new SolidColorBrush(rigth ? Const.CorrectColor : Const.IncorrectColor);
126 | }
127 |
128 | public static void SetText(TextBlock serviceTextBox, string text)
129 | {
130 | //Dispatcher.
131 |
132 | serviceTextBox.Dispatcher.Invoke(DispatcherPriority.Normal,
133 | new Action(s => serviceTextBox.Text = s), text);
134 | }
135 |
136 | public static void SetBackground(RadioButton rb, System.Windows.Media.Color ligthBackgroundColor)
137 | {
138 | Application.Current.Dispatcher.BeginInvoke(
139 | DispatcherPriority.Normal,
140 | new Action(() => rb.Background = new SolidColorBrush(ligthBackgroundColor)));
141 | }
142 | }
143 | }
--------------------------------------------------------------------------------
/Platonus Tester/Properties/Resources.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 | text/microsoft-resx
107 |
108 |
109 | 2.0
110 |
111 |
112 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
113 |
114 |
115 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
--------------------------------------------------------------------------------
/Platonus Tester/Platonus Tester.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {CAF474A8-0A6C-4CB0-B38E-E23644D58E77}
8 | WinExe
9 | Properties
10 | Platonus_Tester
11 | Platonus Tester
12 | v4.5.2
13 | 512
14 | {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
15 | 4
16 | true
17 |
18 |
19 | AnyCPU
20 | true
21 | full
22 | false
23 | bin\Debug\
24 | DEBUG;TRACE
25 | prompt
26 | 4
27 |
28 |
29 | AnyCPU
30 | pdbonly
31 | true
32 | bin\Release\
33 | TRACE
34 | prompt
35 | 4
36 | bin\Release\Platonus Tester.XML
37 |
38 |
39 | Media\icon.ico
40 |
41 |
42 |
43 | False
44 | bin\Release\DocX.dll
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 | 4.0
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 | MSBuild:Compile
65 | Designer
66 |
67 |
68 | ErrorWindow.xaml
69 |
70 |
71 | ResultWindow.xaml
72 |
73 |
74 | SettingsForm.xaml
75 |
76 |
77 | Designer
78 | MSBuild:Compile
79 |
80 |
81 | MSBuild:Compile
82 | Designer
83 |
84 |
85 | App.xaml
86 | Code
87 |
88 |
89 |
90 |
91 |
92 | MainWindow.xaml
93 | Code
94 |
95 |
96 | Designer
97 | MSBuild:Compile
98 |
99 |
100 | Designer
101 | MSBuild:Compile
102 |
103 |
104 |
105 |
106 |
107 | Code
108 |
109 |
110 | True
111 | True
112 | Resources.resx
113 |
114 |
115 | True
116 | Settings.settings
117 | True
118 |
119 |
120 | ResXFileCodeGenerator
121 | Resources.Designer.cs
122 |
123 |
124 |
125 | SettingsSingleFileGenerator
126 | Settings.Designer.cs
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 | {A41424E6-309B-4F20-9988-DE56038A02B6}
139 | Platest
140 |
141 |
142 | {83D12892-8383-44B3-BC52-585C6909ECBF}
143 | ResultComments
144 |
145 |
146 |
147 |
148 |
149 |
150 |
157 |
--------------------------------------------------------------------------------
/Platest/Controllers/SourceController.cs:
--------------------------------------------------------------------------------
1 | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
2 | // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.IO;
7 | using System.Linq;
8 | using System.Text;
9 | using System.Threading;
10 | using System.Threading.Tasks;
11 | using System.Windows.Threading;
12 | using Novacode;
13 | using Platest.Helpers;
14 | using Platest.Interfaces;
15 | using Platest.Models;
16 | using Image = System.Drawing.Image;
17 |
18 | namespace Platest.Controllers
19 | {
20 | ///
21 | /// Класс для управления входным файлом. За основу взята библиотека
22 | /// Novacode.DocX, как бесплатная и легкодоступная. Из проблем библиотеки
23 | /// стоит отметить то, что работает она в одном потоке, и в ней нет функций async / await
24 | /// Это значит, что мне нужно организовать работу в фоне, так как загрузка файла docx/doc
25 | /// Может занимать достаточное для глаза время блокировки UI треда.
26 | /// Например, тест по ИнфБез открывается около 6 секунд
27 | ///
28 | public class SourceController
29 | {
30 | private readonly ISourceLoadListener _listener;
31 | private string _fileName;
32 | private readonly List _errorList;
33 |
34 | public SourceController(ISourceLoadListener listener)
35 | {
36 | _listener = listener;
37 | _errorList = new List(0);
38 | }
39 |
40 | ///
41 | /// Инициализация. Здесь же определяю и Background worker
42 | /// Об этой функции узнал недавно (04.06.2016), так как были проблемы с Thread.Start
43 | /// Создание отедльного треда вынудило использовать кучу костылей в обновлении UI компонентов,
44 | /// Доходило до того, что я и компонент, и переменную для обновления (внутри лямбда функции)
45 | /// вызывал через Dispatcher
46 | /// Вывод: в WinForm создание треда было проще (или просто мне понятней)
47 | ///
48 | ///
49 | public void ProcessSourceFileAsync(string fileName)
50 | {
51 | _fileName = fileName;
52 | var file = GetSourceFile();
53 | StartProcessing(file);
54 | }
55 |
56 | private SourceFile GetSourceFile()
57 | {
58 | if (_fileName == null)
59 | {
60 | throw new InvalidOperationException("Имя файла равно null");
61 | }
62 |
63 | var extension = Path.GetExtension(_fileName);
64 | SourceFile file = null;
65 | switch (extension)
66 | {
67 | case ".txt":
68 | file = GetTxt(_fileName);
69 | break;
70 |
71 | case ".docx":
72 | case ".doc":
73 | file = GetDocXText(_fileName);
74 | break;
75 | }
76 | if (file != null)
77 | {
78 |
79 | }
80 | return file;
81 | }
82 | public IEnumerable GetErrors()
83 | {
84 | if (_errorList.Count <= 0) return null;
85 | var tmp = _errorList;
86 | _errorList.Clear();
87 | return tmp;
88 | }
89 |
90 | ///
91 | /// Whenever you update your UI elements from a thread other than the main thread, you need to use: Dispatcher.BeginInvoke(new Action(() => {GetGridData(null, 0)}));
92 | /// https://stackoverflow.com/questions/9732709/the-calling-thread-cannot-access-this-object-because-a-different-thread-owns-it
93 | /// http://www.vbforums.com/showthread.php?731799-RESOLVED-WPF-Dispatcher-BeginInvoke-parameter-mismatch
94 | ///
95 | ///
96 | private void StartProcessing(SourceFile result)
97 | {
98 | var file = new CurrentDispatcherFile()
99 | {
100 | Dispatcher = Dispatcher.CurrentDispatcher,
101 | SourceFile = result
102 | };
103 |
104 | Task task = new Task(() => _listener.OnSourceLoaded(file));
105 | task.Start();
106 | }
107 |
108 | ///
109 | /// Если был передан обыкновенный текстовый файл
110 | ///
111 | private SourceFile GetTxt(string filename)
112 | {
113 | StreamReader reader = null;
114 | string text = null;
115 | try
116 | {
117 | reader = new StreamReader(filename, Encoding.Default);
118 | text = reader.ReadToEnd();
119 | reader.Close();
120 | }
121 | catch (Exception ex)
122 | {
123 | _errorList.Add(ex);
124 | }
125 | finally
126 | {
127 | reader?.Close();
128 | reader?.Dispose();
129 | }
130 | return new SourceFile(text, null, Path.GetFileName(filename));
131 | }
132 |
133 | ///
134 | /// Эта функция берет файл и создает документ-контейнер для него.
135 | /// Это занимает некоторое время, что вынуждает использовать раздельные потоки
136 | ///
137 | private SourceFile GetDocXText(string filename)
138 | {
139 | try
140 | {
141 | var document = DocX.Load(filename);
142 | var text = string.Empty;
143 | text = text
144 | .ReplaceImages(document)
145 | .ReplaceTables(document);
146 | //
147 | var images = document.Images;
148 | text = text
149 | .Replace("", "\r\n")
150 | .Replace("", "\r\n");
151 |
152 | return new SourceFile(text, images, Path.GetFileName(filename));
153 | }
154 | catch (Exception ex)
155 | {
156 | _errorList.Add(ex);
157 | }
158 | return null;
159 | }
160 |
161 | private List ConvertImages(IEnumerable pictures, IEnumerable images)
162 | {
163 | var result = new List(0);
164 | var enumerable = images as Novacode.Image[] ?? images.ToArray();
165 | foreach (var pic in pictures)
166 | {
167 | Novacode.Image image = null;
168 | foreach (var img in enumerable)
169 | {
170 | if (pic.FileName != img.FileName) continue;
171 | image = img;
172 | break;
173 | }
174 | if (image == null) continue;
175 | result.Add(Image.FromStream(image.GetStream(FileMode.Open, FileAccess.Read)));
176 | }
177 | return result;
178 | }
179 | }
180 | }
--------------------------------------------------------------------------------
/Platonus Tester/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
42 |
43 |
44 |
45 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
--------------------------------------------------------------------------------
/Platonus Tester/bin/Release/Platonus Tester.XML:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Platonus Tester
5 |
6 |
7 |
8 |
9 | Логика взаимодействия для ErrorWindow.xaml
10 |
11 |
12 | ErrorWindow
13 |
14 |
15 |
16 |
17 | InitializeComponent
18 |
19 |
20 |
21 |
22 | Логика взаимодействия для ResultWindow.xaml
23 |
24 |
25 | ResultWindow
26 |
27 |
28 |
29 |
30 | InitializeComponent
31 |
32 |
33 |
34 |
35 | Логика взаимодействия для SettingsForm.xaml
36 |
37 |
38 | SettingsForm
39 |
40 |
41 |
42 |
43 | InitializeComponent
44 |
45 |
46 |
47 |
48 | Логика взаимодействия для App.xaml
49 |
50 |
51 | App
52 |
53 |
54 |
55 |
56 | InitializeComponent
57 |
58 |
59 |
60 |
61 | Application Entry Point.
62 |
63 |
64 |
65 |
66 | Класс для управления настройками. Настройки записываются в XML формате в файл в той же директории
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 | Загрузка настроек из файла. Если происходит ошибка, возвращаются станлартные настройки
78 |
79 |
80 |
81 |
82 |
83 | Here I tryed to make an imitation of String resource file
84 | This variables a assigned to Control-components contents and titles
85 | Also here Color const placed.
86 |
87 |
88 |
89 |
90 | Класс для вспомогательных функций обработки компонентов формы, чтобы сделать код в UI классах чище
91 | До версии 2.0 была необходимость в использовании Dispatcher/Invoke для обновления компонентов
92 | не из UI потока
93 |
94 |
95 |
96 |
97 | настройки программы, записывающиеся в XML формате
98 |
99 |
100 |
101 |
102 | Установить лимит вопросов (25 обычно), как на тестировании
103 |
104 |
105 |
106 |
107 | Показать ругательные комментарии
108 |
109 |
110 |
111 |
112 | Загружать ли комментарии с репозитория
113 |
114 |
115 |
116 |
117 | Будет добавлена в будущем поддержка двух цветовых схем.
118 |
119 |
120 |
121 |
122 | Количество лимита
123 |
124 |
125 |
126 |
127 | Логика взаимодействия для MainWindow.xaml
128 |
129 |
130 | MainWindow
131 |
132 |
133 |
134 |
135 | Обработка файла, который "скинули" в форму
136 |
137 |
138 |
139 |
140 |
141 |
142 | Обработка исходоного файла. Загрузка в лейблы.
143 |
144 |
145 |
146 |
147 |
148 | Создание диалогового окна выбора файла и вызов обработки, если файл соответсвует валидации
149 |
150 |
151 |
152 |
153 |
154 | Валидация имени файла. Пока что только проверка на расширение файла
155 |
156 |
157 |
158 |
159 |
160 |
161 | Функция считывает тайтл варианта ответа, который был отмечен, и записывает его в новый объект -
162 | отвеченный вопрос, добавляя к массиву отвеченных
163 |
164 |
165 |
166 |
167 | Отобрадение прогресса отвеченных вопрсов в отношении всего массива
168 | Just for Fun
169 |
170 |
171 |
172 |
173 |
174 | InitializeComponent
175 |
176 |
177 |
178 |
179 | Класс ресурсов со строгим типом для поиска локализованных строк и пр.
180 |
181 |
182 |
183 |
184 | Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
185 |
186 |
187 |
188 |
189 | Переопределяет свойство CurrentUICulture текущего потока для всех
190 | подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
191 |
192 |
193 |
194 |
195 |
--------------------------------------------------------------------------------
/Platest/Helpers/QuestionProcessor.cs:
--------------------------------------------------------------------------------
1 | // This is an open source non-commercial project. Dear PVS-Studio, please check it.
2 | // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
3 |
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Drawing;
7 | using System.IO;
8 | using System.Linq;
9 | using Platest.Interfaces;
10 | using Platest.Models;
11 |
12 | namespace Platest.Helpers
13 | {
14 | ///
15 | /// Класс-кор проекта. Обработчик текста вопросов в хэш вопросов-объектов
16 | ///
17 | public class QuestionProcessor : IQuestionProvider
18 | {
19 | private SourceFile _file;
20 | private List _errorList;
21 |
22 | public QuestionProcessor()
23 | {
24 | _errorList = new List(0);
25 | }
26 |
27 | ///
28 | /// Функция-инициализатор обработки. Определяю количество вхождений слова question в тегах
29 | /// для того, чтобы определить количество итераций.
30 | ///
31 | /// Объект содержит текст и картинки
32 | /// Массив тестовых вопросов
33 | public List GetQuestionList(SourceFile file)
34 | {
35 | _file = file;
36 | var text = file.SourceText;
37 | var result = new List(0);
38 | text = ProcessText(text);
39 |
40 | var questionCount = GetWordCount("", text);
41 | for (var i = 0; i < questionCount; i++)
42 | {
43 | text = text.Substring(GetIndex("", text) + 10);
44 | var endPos = GetIndex("", text);
45 | var questionText = text.Substring(0, endPos > -1 ? GetIndex("", text) : text.Length);
46 |
47 | if (endPos > -1)
48 | text = text.Substring(endPos);
49 |
50 | var question = GetQuestion(questionText);
51 | if (question != null)
52 | {
53 | result.Add(question);
54 | }
55 | else
56 | {
57 | // MessageBox.Show("Возникла ошибка на этапе обработки вопроса " + i);
58 | }
59 |
60 | }
61 | // ShowErrors();
62 | return result;
63 | }
64 |
65 | ///
66 | /// Здесь планирую сделать замену TAMOS формата в Platonus формат
67 | ///
68 | ///
69 | ///
70 | private static string ProcessText(string text)
71 | {
72 | /*
73 | * TODO:
74 | * TestQuestion > [q]3:1:
75 | * variant > [a] ( variant > [a]+)
76 | *
77 | */
78 |
79 | var result = text.Replace("\t", "");
80 |
81 | return result;
82 | }
83 |
84 | public const string MissingVariant = "Ошибка: отсутствует вариант ответа";
85 | ///
86 | /// Функция, возвращающая тестовый вопрос
87 | ///
88 | ///
89 | ///
90 | public TestQuestion GetQuestion(string text)
91 | {
92 | try
93 | {
94 | var varCount = GetWordCount("", text);
95 |
96 | var quest = text.Substring(0, GetIndex("\r\n", text));
97 | var image = GetImage(quest);
98 | quest = RemovePictureText(quest);
99 | text = text.Substring(GetIndex("", text));
100 |
101 | var hash = new List(0);
102 |
103 | for (var j = 0; j < varCount; j++)
104 | {
105 | try
106 | {
107 | text = text.Substring(GetIndex("", text) + "".Length);
108 | var pos = GetIndex("\r\n", text);
109 | var variant = "";
110 | if (pos != -1)
111 | {
112 | variant = text.Substring(0, pos);
113 | }
114 | else
115 | {
116 | //
117 | if (GetWordCount("", text) == 0 && text.Length > 0)
118 | variant = text;
119 | }
120 | hash.Add(variant);
121 | text = text.Substring(pos + 2);
122 | }
123 | catch (Exception ex)
124 | {
125 | _errorList.Add("Проблема в обработке вопроса: \r\n" + quest + "\r\n" + ex.Message);
126 | }
127 | }
128 |
129 | for (var i = hash.Count; i < 5; i++)
130 | {
131 | hash.Add(MissingVariant);
132 | }
133 |
134 | var result = new TestQuestion
135 | {
136 | AskQuestion = quest,
137 | CorrectAnswer = hash[0],
138 | AnswerList = hash,
139 | Picture = image
140 | };
141 | return result;
142 | }
143 | catch (Exception ex)
144 | {
145 | _errorList.Add($"Проблема в обработке вопроса: \r\n{text}\r\n{ex.Message}");
146 | return null;
147 | }
148 | }
149 |
150 | ///
151 | /// Поиск и удаление всех вхождений тегов picture
152 | ///
153 | /// Исходный текст для форматирования
154 | /// Текст без тегов картинок
155 | private string RemovePictureText(string text)
156 | {
157 | if (GetIndex("<#picture= ", text) == -1)
158 | {
159 | return text;
160 | }
161 |
162 | var picName = GetPictureName(text);
163 | var result = text.Replace($"<#picture= {picName} #>", "");
164 | return result;
165 | }
166 |
167 | private string GetPictureName(string text)
168 | {
169 | try
170 | {
171 | var index = GetIndex("<#picture= ", text);
172 | var size = "<#picture= ".Length;
173 | var picName = text.Substring(index + size);
174 | picName = picName.Substring(0, GetIndex(" #>", picName));
175 | return picName;
176 | }
177 | catch (Exception ex)
178 | {
179 | return null;
180 | }
181 | }
182 |
183 | ///
184 | /// Функция - вычислитель количество вхождений слова в тексте
185 | ///
186 | /// Искомое слово
187 | /// Текст, в котором ищется слово
188 | /// Количество вхождений
189 | private int GetWordCount(string word, string source)
190 | {
191 | return (source.Length - source.Replace(word, "").Length) / word.Length;
192 | }
193 |
194 | public IEnumerable GetErrors()
195 | {
196 | if (_errorList == null || _errorList.Count <= 0) return null;
197 | var tmp = _errorList;
198 | _errorList = new List(0);
199 | return tmp;
200 | }
201 |
202 | private Image GetImage(string question)
203 | {
204 | if (GetIndex("<#picture= ", question) == -1)
205 | {
206 | return null;
207 | }
208 |
209 | var picName = GetPictureName(question);
210 | return FindImageByName(picName);
211 | }
212 |
213 | private int GetIndex(string search, string text)
214 | {
215 | return text.IndexOf(search, StringComparison.Ordinal);
216 | }
217 |
218 | ///
219 | /// Поиск и возврат картинки по названию
220 | ///
221 | ///
222 | ///
223 | private Image FindImageByName(string name)
224 | {
225 | Image result = null;
226 | foreach (var img in _file.Images)
227 | {
228 | if (name != img.FileName) continue;
229 | result = Image.FromStream(img.GetStream(FileMode.Open, FileAccess.Read));
230 | break;
231 | }
232 | return result;
233 | }
234 | }
235 | }
--------------------------------------------------------------------------------
/license.md:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright (c) 2015 Maxim Gorbatyuk
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
--------------------------------------------------------------------------------
/Platonus Tester/MainWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.IO;
5 | using System.Linq;
6 | using System.Reflection;
7 | using System.Text;
8 | using System.Threading.Tasks;
9 | using System.Windows;
10 | using System.Windows.Controls;
11 | using System.Windows.Data;
12 | using System.Windows.Documents;
13 | using System.Windows.Input;
14 | using System.Windows.Media;
15 | using System.Windows.Media.Imaging;
16 | using System.Windows.Navigation;
17 | using System.Windows.Shapes;
18 | using System.Windows.Threading;
19 | using Microsoft.Win32;
20 | using Platonus_Tester.Controller;
21 | using Platonus_Tester.Helper;
22 | using Platest.Controllers;
23 | using Platest.Interfaces;
24 | using Platest.Models;
25 | using ResultComments.Models;
26 |
27 | namespace Platonus_Tester
28 | {
29 | ///
30 | /// Логика взаимодействия для MainWindow.xaml
31 | ///
32 | public partial class MainWindow : Window, ISourceLoadListener
33 | {
34 |
35 | private IQuestionManager _questionManager;
36 | private TestQuestion _currentQuestion;
37 | private List _answered;
38 | private int _count;
39 | private bool _loadedFile;
40 | private string _fileName = "";
41 | private SourceController _sourceController;
42 | //-------------------------
43 | private Settings _settings;
44 | private Comment _goodComment, _badComment;
45 | private SourceFile _sourcefile = null;
46 |
47 | private readonly List _radioButtonsList;
48 | private readonly List _recList;
49 | private readonly List _tbList;
50 |
51 |
52 | public MainWindow()
53 | {
54 |
55 | InitializeComponent();
56 | Title = Const.ApplicationName;
57 | WelcomeTextBlock.Text = Const.WelcomeText;
58 | DescrTextBlock.Text = Const.DescriptionText;
59 | serviceTextBox.Text = Const.InviteToLoadFile;
60 | InformationLabel.Content = "";
61 | VersionLabel.Content = $"Версия: {Const.Version}";
62 | SettingsButton.Content = Const.SettingsText;
63 | _radioButtonsList = new List
64 | {
65 | RbVariant1,
66 | RBVariant2,
67 | RBVariant3,
68 | RBVariant4,
69 | RBVariant5,
70 | };
71 | RbVariant1.IsChecked = true;
72 | _recList = new List
73 | {
74 | Rc1,
75 | Rc2,
76 | Rc3,
77 | Rc4,
78 | Rc5,
79 | };
80 |
81 | _tbList = new List
82 | {
83 | V1TextBlock,
84 | V2TextBlock,
85 | V3TextBlock,
86 | V4TextBlock,
87 | V5TextBlock,
88 | };
89 |
90 | }
91 |
92 | private void ChangeColorSchemeClick(object sender, RoutedEventArgs e)
93 | {
94 | //throw new NotImplementedException();
95 |
96 | //var resource = (Style)FindResource(value ? "LigthWindowStyle" : "DarkWindowStyle");
97 | //MainWindow1.Style = resource;
98 | //StartGrid.Style = resource;
99 | //QuestionGrid.Style = resource;
100 | //value = !value;
101 | }
102 |
103 | ///
104 | /// Обработка файла, который "скинули" в форму
105 | ///
106 | ///
107 | ///
108 | private void StartGrid_OnDrop(object sender, DragEventArgs e)
109 | {
110 | if (!e.Data.GetDataPresent(DataFormats.FileDrop)) return;
111 |
112 | var files = e.Data.GetData(DataFormats.FileDrop) as string[];
113 | if (files == null)
114 | {
115 | return;
116 | }
117 |
118 | if (files.Length <= 0) return;
119 | OpenFile(files[0]);
120 | }
121 |
122 | private void StartGrid_OnDragOver(object sender, DragEventArgs e)
123 | {
124 | e.Effects = DragDropEffects.Move;
125 | e.Handled = true;
126 | }
127 |
128 | private void Window_Loaded(object sender, RoutedEventArgs e)
129 | {
130 | _questionManager = new QuestionManager();
131 | // _settings = SettingsController.Load();
132 | _sourceController = new SourceController(this);
133 |
134 | _goodComment = new Comment();
135 | _badComment = new Swear();
136 | //---
137 | // Point renderedLocation = StartGrid.TranslatePoint(new Point(0, 0), MainWindow1);
138 | StartGrid.TranslatePoint(new Point(0, 0), MainWindow1);
139 | StartButton.Content = Const.LoadSourceFile;
140 | _settings = SettingsController.Load();
141 | SwearLabel.Content = _settings.ShowSwearing ? Const.SwearsEnabled : Const.SwearsDisabled;
142 | LimitLabel.Content = _settings.EnableLimit ? Const.LimitEnabled : Const.LimitDisabled;
143 | }
144 |
145 | ///
146 | /// Обработка исходоного файла. Загрузка в лейблы.
147 | ///
148 | ///
149 | private async void ProcessSourceFile(SourceFile source)
150 | {
151 | _questionManager.SetSourceList(source);
152 | if (_settings.EnableLimit)
153 | {
154 | _questionManager.SetQuestionLimit(_settings.QuestionLimitCount);
155 | }
156 | //----------------------------
157 | _currentQuestion = _questionManager.GetNext();
158 | _count += 1;
159 | LoadToLabels(_currentQuestion);
160 | var remain = !_settings.EnableLimit
161 | ? _questionManager.GetCount() - _answered.Count
162 | : _settings.QuestionLimitCount - _answered.Count;
163 |
164 | InformationLabel.Content = $"Осталось {remain} вопр.";
165 | LimitLabel.Content = _settings.EnableLimit ? Const.LimitEnabled : Const.LimitDisabled;
166 | SwearLabel.Content = _settings.ShowSwearing ? Const.SwearsEnabled : Const.SwearsDisabled;
167 | //
168 | var count = _questionManager.GetCount();
169 | if (count > 0)
170 | {
171 | serviceTextBox.Text = $"Файл {source.FileName} загружен. Нажмите \"Начать\". Вопросов {count}";
172 | _loadedFile = true;
173 | StartButton.IsEnabled = true;
174 | }
175 | else
176 | {
177 | serviceTextBox.Text = $"Возникли проблемы с обработкой вопросов";
178 | }
179 | //--------------------------
180 | NextButton.Content = Const.NextQuestion;
181 | CheckButton.Content = Const.CheckQuestion;
182 | //UInterfaceHelper.SetProgressValue(progressBar, 100);
183 |
184 | var errors = _questionManager.GetErrors();
185 | if (errors != null)
186 | {
187 | new ErrorWindow(errors.ToList()).ShowDialog();
188 | }
189 | }
190 |
191 | private void LoadToLabels(Question test)
192 | {
193 | if (test == null) return;
194 | questionTextBlock.Text = test.AskQuestion;
195 |
196 | if (test.Picture != null)
197 | {
198 | image1.Source = UInterfaceHelper.GetImageSource(test.Picture);
199 | }
200 | image1.Visibility = test.Picture != null ? Visibility.Visible : Visibility.Hidden;
201 |
202 | var hash = new List(0);
203 | hash.AddRange(test.AnswerList);
204 | //-----------------
205 | for (var i = 0; i < _radioButtonsList.Count; i++)
206 | {
207 | var rb = _radioButtonsList[i];
208 | var rec = _recList[i];
209 | rb.Background = new SolidColorBrush(Const.LigthBackgroundColor);
210 | rec.Fill = new SolidColorBrush(Const.LigthBackgroundColor);
211 | //rec.Fill = new SolidColorBrush(Const.LigthBackgroundColor );
212 |
213 | _tbList[i].Text = GetRandomItem(hash, i);
214 | // rb.Content = GetRandomItem(hash, i);
215 | // hash.Remove((string) rb.Content);
216 | hash.Remove(_tbList[i].Text);
217 | }
218 | //---------------------------
219 | }
220 |
221 | private static string GetRandomItem(IList hash, int i)
222 | {
223 | var random = new Random(DateTime.Now.Millisecond + i);
224 | return hash[random.Next(hash.Count)];
225 | }
226 |
227 | private void StartButton_Click(object sender, RoutedEventArgs e)
228 | {
229 | if (_loadedFile)
230 | {
231 | StartGrid.Visibility = Visibility.Hidden;
232 | }
233 | else
234 | {
235 | OpenFile();
236 | }
237 | }
238 |
239 | private void LoadSettings()
240 | {
241 | serviceTextBox.Background = new SolidColorBrush(Const.LigthBackgroundColor);
242 | _settings = SettingsController.Load();
243 | _answered = new List(0);
244 | StartGrid.Visibility = Visibility.Visible;
245 | if (_fileName == "") return;
246 |
247 | StartButton.IsEnabled = false;
248 | progressBar.Value = 0;
249 | _sourceController.ProcessSourceFileAsync(_fileName);
250 | LimitLabel.Content = _settings.EnableLimit ? Const.LimitEnabled : Const.LimitDisabled;
251 | SwearLabel.Content = _settings.ShowSwearing ? Const.SwearsEnabled : Const.SwearsDisabled;
252 |
253 | var errors = _sourceController.GetErrors();
254 | if (errors != null)
255 | {
256 | new ErrorWindow(errors.Select(x => $"Проблема при открытии файла вопросов: {x.Message}").ToList()).ShowDialog();
257 | }
258 | }
259 |
260 | ///
261 | /// Создание диалогового окна выбора файла и вызов обработки, если файл соответсвует валидации
262 | ///
263 | ///
264 | private void OpenFile(string dragname = null)
265 | {
266 | serviceTextBox.Background = new SolidColorBrush(Const.LigthBackgroundColor);
267 | if (dragname == null)
268 | {
269 | var openFileDialog1 = new OpenFileDialog
270 | {
271 | //InitialDirectory = Directory.GetCurrentDirectory(),
272 | InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
273 | FilterIndex = 2,
274 | RestoreDirectory = true
275 | };
276 | //--------------------------
277 | var result = openFileDialog1.ShowDialog();
278 | if (!result ?? false) return;
279 | _fileName = openFileDialog1.FileName;
280 | }
281 | else
282 | {
283 | _fileName = dragname;
284 | }
285 | if (!ValidateFilename(_fileName))
286 | {
287 | serviceTextBox.Text = Const.WrongFilename;
288 | return;
289 | }
290 | serviceTextBox.Text = Const.FileProcessing;
291 | progressBar.IsIndeterminate = true;
292 | progressBar.Visibility = Visibility.Visible;
293 | //UInterfaceHelper.SetText(serviceTextBox, Const.FileProcessing);
294 | LoadSettings();
295 | }
296 |
297 | ///
298 | /// Валидация имени файла. Пока что только проверка на расширение файла
299 | ///
300 | ///
301 | ///
302 | private static bool ValidateFilename(string file)
303 | {
304 | return file.IndexOf(".docx", StringComparison.Ordinal) > -1 ||
305 | file.IndexOf(".doc", StringComparison.Ordinal) > -1 ||
306 | file.IndexOf(".txt", StringComparison.Ordinal) > -1;
307 | }
308 |
309 | private void StartGrid_DragEnter(object sender, DragEventArgs e)
310 | {
311 | serviceTextBox.Text = Const.DraggingFiles;
312 | serviceTextBox.Background = new SolidColorBrush(Const.LigthBlack);
313 | e.Effects = e.Data.GetDataPresent(DataFormats.FileDrop) ?
314 | DragDropEffects.Move :
315 | DragDropEffects.None;
316 | }
317 |
318 | private void MainWindow1_Initialized(object sender, EventArgs e)
319 | {
320 | // StartGrid
321 | }
322 |
323 | private void AboutMenuItem_Click(object sender, RoutedEventArgs e)
324 | {
325 | Process.Start(
326 | "https://github.com/maximgorbatyuk/Platonus-Tester/#platonus-tester");
327 | }
328 |
329 | private void SettingsButton_Click(object sender, RoutedEventArgs e)
330 | {
331 | var settingsView = new SettingsForm();
332 | settingsView.Closed += SettingsViewOnClosed;
333 | settingsView.ShowDialog();
334 | }
335 |
336 | private void SettingsViewOnClosed(object sender, EventArgs eventArgs)
337 | {
338 | _settings = SettingsController.Load();
339 | LimitLabel.Content = _settings.EnableLimit ? Const.LimitEnabled : Const.LimitDisabled;
340 | SwearLabel.Content = _settings.ShowSwearing ? Const.SwearsEnabled : Const.SwearsDisabled;
341 | }
342 |
343 | ///
344 | /// Функция считывает тайтл варианта ответа, который был отмечен, и записывает его в новый объект -
345 | /// отвеченный вопрос, добавляя к массиву отвеченных
346 | ///
347 | private void CheckQuestion()
348 | {
349 | if (_currentQuestion == null) return;
350 | var answer = new AnsweredQuestion
351 | {
352 | AskQuestion = _currentQuestion.AskQuestion,
353 | CorrectAnswer = _currentQuestion.CorrectAnswer
354 | };
355 | //------------------------
356 | foreach (var rb in _radioButtonsList)
357 | {
358 | var tb = (TextBlock)rb.Content;
359 | if (rb.IsChecked != null && rb.IsChecked.Value)
360 | {
361 | answer.ChosenAnswer = tb.Text;
362 | }
363 | }
364 | answer.IsItCorrect = answer.ChosenAnswer == answer.CorrectAnswer;
365 | _answered.Add(answer);
366 | }
367 |
368 | private void FinishTesting()
369 | {
370 | if ((_answered != null) && (_answered.Count > 0))
371 | {
372 | new ResultWindow(_answered, _goodComment, _badComment).ShowDialog();
373 | }
374 | StartGrid.Visibility = Visibility.Visible;
375 | _loadedFile = false;
376 | serviceTextBox.Text = Const.InviteToLoadFile;
377 | StartButton.Content = Const.LoadSourceFile;
378 | InformationLabel.Content = "";
379 | }
380 |
381 | private void SettingsMenuItem_OnClick(object sender, RoutedEventArgs e)
382 | {
383 | SettingsButton_Click(sender, e);
384 | }
385 |
386 | private void CheckButton_Click(object sender, RoutedEventArgs e)
387 | {
388 | if (_currentQuestion == null) return;
389 |
390 | for (var index = 0; index < _radioButtonsList.Count; index++)
391 | {
392 | var rb = _radioButtonsList[index];
393 | var tb = (TextBlock)rb.Content;
394 | if (tb.Text == _currentQuestion.CorrectAnswer)
395 | {
396 | UInterfaceHelper.PaintBackColor(_recList[index], true);
397 | }
398 | else if (rb.IsChecked ?? false)
399 | {
400 | UInterfaceHelper.PaintBackColor(_recList[index], false);
401 | }
402 | }
403 | }
404 |
405 | ///
406 | /// Отобрадение прогресса отвеченных вопрсов в отношении всего массива
407 | /// Just for Fun
408 | ///
409 | ///
410 | private void DisplayProgress(int position)
411 | {
412 | var count = _settings.EnableLimit ? _settings.QuestionLimitCount : _questionManager.GetCount();
413 | count = count > 0 ? count : 1;
414 | var pValue = (double)position / count * 100;
415 | pValue = pValue > 100 ? 100 : pValue;
416 | progressBar.Value = pValue;
417 | }
418 |
419 | private void NextButton_Click(object sender, RoutedEventArgs e)
420 | {
421 | CheckQuestion();
422 | _currentQuestion = _questionManager.GetNext();
423 | LoadToLabels(_currentQuestion);
424 | DisplayProgress(_questionManager.GetCurrentPosition());
425 |
426 | var remain = !_settings.EnableLimit ?
427 | _questionManager.GetCount() - _answered.Count :
428 | _settings.QuestionLimitCount - _answered.Count;
429 |
430 | InformationLabel.Content = $"Осталось вопросов: {remain}";
431 |
432 | if (remain == 1)
433 | {
434 | NextButton.Content = Const.ShowResult;
435 | }
436 | foreach (var rb in _radioButtonsList)
437 | {
438 | rb.IsChecked = false;
439 | }
440 | var cond = _answered.Count == _questionManager.GetFirstListCount() ||
441 | (_answered.Count == _settings.QuestionLimitCount && _settings.EnableLimit == true);
442 | if (cond)
443 | {
444 | FinishTesting();
445 | }
446 | }
447 |
448 |
449 | private void StartAgainMenuItem_OnClick(object sender, RoutedEventArgs e)
450 | {
451 | if (_fileName == "") return;
452 | UInterfaceHelper.SetText(InformationLabel, "");
453 | UInterfaceHelper.SetText(serviceTextBox, Const.FileProcessing);
454 | LoadSettings();
455 | }
456 |
457 | private void LoadSourceMenuItem_OnClick(object sender, RoutedEventArgs e)
458 | {
459 | OpenFile();
460 | }
461 |
462 | private void FinishMenuItem_OnClick(object sender, RoutedEventArgs e)
463 | {
464 | FinishTesting();
465 | }
466 |
467 | public void OnSourceLoaded(object currentDispatcher)
468 | {
469 | CurrentDispatcherFile sourcefile = (CurrentDispatcherFile)currentDispatcher;
470 | sourcefile.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new RunProcessDelegate(RunProcess), sourcefile.SourceFile);
471 | }
472 | public delegate void RunProcessDelegate(SourceFile sourcefile);
473 |
474 | public void RunProcess(object sourcefile)
475 | {
476 | // TODO Maxim: here we set a value from another thread. This logic should be changed
477 | _sourcefile = (SourceFile)sourcefile;
478 | if (_sourcefile?.SourceText == null)
479 | {
480 | serviceTextBox.Text = Const.InviteToLoadFile;
481 | StartButton.IsEnabled = true;
482 | return;
483 | }
484 | StartButton.Content = Const.StartTesting;
485 | progressBar.IsIndeterminate = false;
486 | progressBar.Value = 0;
487 | ProcessSourceFile(_sourcefile);
488 | }
489 | }
490 | }
491 |
--------------------------------------------------------------------------------