Esempio n. 1
0
        public void TestFormConstructors()
        {
            Program.CreateVhfFolder();
            Program.CreateVhrFolder();
            VocabularyBook book = new VocabularyBook()
            {
                MotherTongue = "Deutsch", ForeignLang = "Englisch"
            };

            new MainForm().Dispose();
            new AboutBox().Dispose();
            new AddWordDialog(book).Dispose();
            new CreateBackup().Dispose();
            // new EditWordDialog(book: null, word: null).Dispose();
            new EvaluationInfoDialog().Dispose();
            new MergeFiles().Dispose();
            new PracticeCountDialog(book).Dispose();
            // new PracticeDialog(book: null, practiceList: null).Dispose();
            // new PracticeResultList(book: null, practiceList: null).Dispose();
            new PrintWordSelection(book).Dispose();
            new RestoreBackup(null).Dispose();
            new SettingsDialog().Dispose();
            new SpecialCharKeyboard().Dispose();
            new SpecialCharManage().Dispose();
            new SplashScreen().Dispose();
            new VocabularyBookSettings(book).Dispose();
            new VocabularyWordDialog(book).Dispose();
        }
Esempio n. 2
0
        private void AddBooks(IEnumerable <FileInfo> files, ZipArchive archive, BackupMeta backup, ref int counter)
        {
            foreach (var fileInfo in files)
            {
                var book = new VocabularyBook();
                if (VocabularyFile.ReadVhfFile(fileInfo.FullName, book))
                {
                    var vhr      = VocabularyFile.ReadVhrFile(book);
                    var success  = TryAddFile(fileInfo.FullName, archive, $"vhf\\{counter}.vhf");
                    var success2 = false;

                    if (success && vhr && CbSaveResults.Checked)
                    {
                        success2 = TryAddFile(Path.Combine(Settings.Default.VhrPath, book.VhrCode + ".vhr"), archive,
                                              $"vhr\\{book.VhrCode}.vhr");
                    }
                    if (success)
                    {
                        backup.Books.Add(new BackupMeta.BookMeta(counter, BackupMeta.ShrinkPath(fileInfo.FullName),
                                                                 success2 ? book.VhrCode : ""));
                        counter++;

                        if (success2)
                        {
                            backup.Results.Add(book.VhrCode + ".vhr");
                        }
                    }
                }
            }
        }
Esempio n. 3
0
 private void ImportCsv(bool ansiEncoding = false)
 {
     using (OpenFileDialog openDialog = new OpenFileDialog
     {
         Title = Words.Import,
         Filter = $"CSV (*.csv)|*.csv"
     })
     {
         if (openDialog.ShowDialog() == DialogResult.OK)
         {
             if (CurrentBook != null)
             {
                 VocabularyFile.ImportCsvFile(openDialog.FileName, CurrentBook, false, ansiEncoding);
             }
             else
             {
                 VocabularyBook book = new VocabularyBook();
                 if (VocabularyFile.ImportCsvFile(openDialog.FileName, book, true, ansiEncoding))
                 {
                     book.Notify();
                     book.UnsavedChanges = true;
                     LoadBook(book);
                 }
             }
         }
     }
 }
Esempio n. 4
0
 public PracticeCountDialog(VocabularyBook book)
 {
     InitializeComponent();
     this.book    = book;
     PracticeList = new List <VocabularyWordPractice>();
     Count        = book.Statistics.NotFullyPracticed;
 }
Esempio n. 5
0
        public bool Export(string path, VocabularyBook book)
        {
            try
            {
                var config = new Configuration();
                config.RegisterClassMap(new EntryMap(book.MotherTongue, book.ForeignLang));

                using (TextWriter file = new StreamWriter(path, false, Encoding.UTF8))
                    using (var writer = new CsvWriter(file, config))
                    {
                        writer.WriteRecords(book.Words.Select(x => new Entry
                        {
                            MotherTongue = x.MotherTongue, ForeignLang = x.ForeignLangText
                        }));
                    }

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(Messages.CsvExportError, ex), Messages.UnexpectedErrorT,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(false);
        }
Esempio n. 6
0
        public bool Write(string path, VocabularyBook book)
        {
            string raw;

            using (StringWriter writer = new StringWriter())
            {
                writer.WriteLine("1.0");
                writer.WriteLine(book.VhrCode);
                writer.WriteLine(book.MotherTongue);
                writer.WriteLine(book.ForeignLang);

                foreach (VocabularyWord word in book.Words)
                {
                    writer.Write(word.MotherTongue);
                    writer.Write('#');
                    writer.Write(word.ForeignLang);
                    writer.Write('#');
                    writer.WriteLine(word.ForeignLangSynonym ?? "");
                }

                raw = writer.ToString();
            }

            try
            {
                WriteFile(path, raw);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(Messages.VocupFileWriteErrorEx, ex), Messages.VocupFileWriteErrorT, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            return(true);
        }
Esempio n. 7
0
 private void TsmiImport_Click(object sender, EventArgs e)
 {
     using (var openDialog = new OpenFileDialog
     {
         Title = Words.Import,
         Filter = "CSV (*.csv)|*.csv"
     })
     {
         if (openDialog.ShowDialog() == DialogResult.OK)
         {
             if (CurrentBook != null)
             {
                 VocabularyFile.ImportCsvFile(openDialog.FileName, CurrentBook, false);
             }
             else
             {
                 var book = new VocabularyBook();
                 if (VocabularyFile.ImportCsvFile(openDialog.FileName, book, true))
                 {
                     book.Notify();
                     book.UnsavedChanges = true;
                     LoadBook(book);
                 }
             }
         }
     }
 }
Esempio n. 8
0
        public PracticeResultList(VocabularyBook book, List <VocabularyWordPractice> practiceList)
        {
            InitializeComponent();
            Icon = Icon.FromHandle(Icons.BarChart.GetHicon());

            this.book         = book;
            this.practiceList = practiceList;
        }
Esempio n. 9
0
        public static bool WriteVhrFile(VocabularyBook book)
        {
            if (book == null)
            {
                throw new ArgumentNullException(nameof(book));
            }

            return(vhrFile.Write(book));
        }
Esempio n. 10
0
        private void BtnSave_Click(object sender, EventArgs e)
        {
            string path;

            using (var save = new SaveFileDialog
            {
                Title = Words.SaveVocabularyBook,
                FileName = TbMotherTongue.Text + " - " + TbForeignLang.Text,
                InitialDirectory = Settings.Default.VhfPath,
                Filter = Words.VocupVocabularyBookFile + " (*.vhf)|*.vhf"
            })
            {
                if (save.ShowDialog() == DialogResult.OK)
                {
                    path = save.FileName;
                }
                else
                {
                    DialogResult = DialogResult.Cancel;
                    return;
                }
            }

            Cursor.Current = Cursors.WaitCursor;

            var result = new VocabularyBook
            {
                MotherTongue = TbMotherTongue.Text,
                ForeignLang  = TbForeignLang.Text,
                FilePath     = path
            };

            foreach (var book in books)
            {
                foreach (var word in book.Words)
                {
                    CopyWord(word, result);
                }
            }

            result.GenerateVhrCode();

            if (!VocabularyFile.WriteVhfFile(path, result) ||
                !VocabularyFile.WriteVhrFile(result))
            {
                MessageBox.Show(Messages.VocupFileWriteError, Messages.VocupFileWriteErrorT, MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                DialogResult = DialogResult.Abort;
            }
            else
            {
                DialogResult = DialogResult.OK;
            }

            Cursor.Current = Cursors.Default;
        }
Esempio n. 11
0
        public VocabularyBookSettings(out VocabularyBook book) : this()
        {
            book      = new VocabularyBook();
            this.book = book;
            book.Notify();

            Text = Words.CreateVocabularyBook;
            Icon = Icon.FromHandle(Icons.File.GetHicon());
            GroupOptions.Enabled = false;
        }
Esempio n. 12
0
        public void ReadFile(string path)
        {
            var book = new VocabularyBook();

            if (VocabularyFile.ReadVhfFile(path, book))
            {
                VocabularyFile.ReadVhrFile(book);
                book.Notify();
                LoadBook(book);
            }
        }
Esempio n. 13
0
        public VocabularyBookSettings(VocabularyBook book) : this()
        {
            this.book = book;

            Text = Words.EditVocabularyBook;
            Icon = Icon.FromHandle(Icons.FileSettings.GetHicon());
            TbMotherTongue.Text           = book.MotherTongue;
            TbForeignLang.Text            = book.ForeignLang;
            RbModeAskForeignLang.Checked  = book.PracticeMode == PracticeMode.AskForForeignLang;
            RbModeAskMotherTongue.Checked = book.PracticeMode == PracticeMode.AskForMotherTongue;
            GroupOptions.Enabled          = true;
        }
Esempio n. 14
0
        public VocabularyWordDialog(VocabularyBook book)
        {
            InitializeComponent();

            specialCharDialog = new SpecialCharKeyboard();
            specialCharDialog.Initialize(this, BtnSpecialChar);

            this.book           = book;
            LbMotherTongue.Text = book.MotherTongue;
            LbForeignLang.Text  = book.ForeignLang;
            LbSynonym.Text      = $"{book.ForeignLang} ({Words.Synonym})";
        }
Esempio n. 15
0
        public static bool ExportCsvFile(string path, VocabularyBook book)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (book == null)
            {
                throw new ArgumentNullException(nameof(book));
            }

            return(csvFile.Export(path, book));
        }
Esempio n. 16
0
        public static bool ImportCsvFile(string path, VocabularyBook book, bool importSettings, bool ansiEncoding)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (book == null)
            {
                throw new ArgumentNullException(nameof(book));
            }

            return(csvFile.Import(path, book, importSettings, ansiEncoding));
        }
Esempio n. 17
0
        public static bool WriteVhfFile(string path, VocabularyBook book)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (book == null)
            {
                throw new ArgumentNullException(nameof(book));
            }

            return(vhfFile.Write(path, book));
        }
Esempio n. 18
0
        public EditWordDialog(VocabularyBook book, VocabularyWord word) : base(book)
        {
            this.word = word;

            Icon = Icon.FromHandle(Icons.Edit.GetHicon());
            Text = Words.EditWord;
            GroupOptions.Enabled = true;
            BtnContinue.Text     = Words.Ok;

            TbMotherTongue.Text       = word.MotherTongue;
            TbForeignLang.Text        = word.ForeignLang;
            TbForeignLangSynonym.Text = word.ForeignLangSynonym ?? "";
        }
Esempio n. 19
0
        public PracticeDialog(VocabularyBook book, List <VocabularyWordPractice> practiceList)
        {
            InitializeComponent();

            Icon = Icon.FromHandle(Icons.LightningBolt.GetHicon());

            evaluator = new Evaluator
            {
                OptionalExpressions     = Settings.Default.EvaluateOptionalExpressions,
                TolerateArticle         = Settings.Default.EvaluateTolerateArticle,
                TolerateNoSynonym       = Settings.Default.EvaluateTolerateNoSynonym,
                ToleratePunctuationMark = Settings.Default.EvaluateToleratePunctuationMark,
                TolerateSpecialChar     = Settings.Default.EvaluateTolerateSpecialChar,
                TolerateWhiteSpace      = Settings.Default.EvaluateTolerateWhiteSpace
            };

            player = new SoundPlayer();

            this.book         = book;
            this.practiceList = practiceList;
            index             = 0;
            currentPractice   = practiceList[0];
            currentWord       = currentPractice.VocabularyWord;

            specialCharDialog = new SpecialCharKeyboard();
            specialCharDialog.Initialize(this, BtnSpecialChar);

            if (Settings.Default.UserEvaluates)
            {
                MinimumSize = new Size(MinimumSize.Width, LogicalToDeviceUnits(380)); // All other controls are adjusted by anchor
            }

            LbMotherTongue.Text = book.MotherTongue;
            LbForeignLang.Text  = book.ForeignLang;

            if (book.PracticeMode == PracticeMode.AskForForeignLang)
            {
                GroupPractice.Text = string.Format(Words.TranslateFromTo, book.MotherTongue, book.ForeignLang);
            }
            else
            {
                GroupPractice.Text = string.Format(Words.TranslateFromTo, book.ForeignLang, book.MotherTongue);
            }
        }
Esempio n. 20
0
        public PrintWordSelection(VocabularyBook book)
        {
            InitializeComponent();
            Icon = Icon.FromHandle(Icons.Print.GetHicon());

            this.book = book;

            ListBox.BeginUpdate();
            foreach (var word in book.Words)
            {
                ListBox.Items.Add($"{word.MotherTongue} - {word.ForeignLangText}", true);
            }
            ListBox.EndUpdate();

            CbUnpracticed.Enabled        = book.Statistics.Unpracticed > 0;
            CbWronglyPracticed.Enabled   = book.Statistics.WronglyPracticed > 0;
            CbCorrectlyPracticed.Enabled = book.Statistics.CorrectlyPracticed > 0;
            CbFullyPracticed.Enabled     = book.Statistics.FullyPracticed > 0;
        }
Esempio n. 21
0
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            var addFile = new OpenFileDialog
            {
                Title            = Words.AddVocabularyBooks,
                InitialDirectory = Settings.Default.VhfPath,
                Filter           = Words.VocupVocabularyBookFile + " (*.vhf)|*.vhf",
                Multiselect      = true
            };

            if (addFile.ShowDialog() == DialogResult.OK)
            {
                foreach (var file in addFile.FileNames)
                {
                    var book = new VocabularyBook();
                    if (!VocabularyFile.ReadVhfFile(file, book))
                    {
                        continue;
                    }
                    VocabularyFile.ReadVhrFile(book);
                    var conflict = books
                                   .Where(x => x.FilePath.Equals(book.FilePath, StringComparison.OrdinalIgnoreCase))
                                   .FirstOrDefault();
                    if (conflict != null)
                    {
                        if (MessageBox.Show(Messages.MergeOverride, Messages.MergeOverrideT, MessageBoxButtons.YesNo,
                                            MessageBoxIcon.Warning) == DialogResult.No)
                        {
                            continue;
                        }
                        books.Remove(conflict);
                        LbFiles.Items.Remove(conflict.FilePath);
                    }

                    books.Add(book);
                    LbFiles.Items.Add(book.FilePath);
                }

                ValidateInput();
            }

            addFile.Dispose();
        }
Esempio n. 22
0
        public void LoadBook(VocabularyBook book)
        {
            var controller = new VocabularyBookController(book)
            {
                Parent = this
            };

            SplitContainer.Panel2.Controls.Add(controller.ListView);
            controller.ListView.PerformLayout();
            controller.ListView.BringToFront();

            CurrentBook       = book;
            CurrentController = controller;

            VocabularyBookLoaded(true);

            FileTreeView.SelectedPath = book.FilePath;

            Settings.Default.LastFile = book.FilePath;
            Settings.Default.Save();
        }
Esempio n. 23
0
        private void CopyWord(VocabularyWord word, VocabularyBook target)
        {
            VocabularyWord cloned = word.Clone(CbKeepResults.Checked);

            for (int i = 0; i < target.Words.Count; i++)
            {
                VocabularyWord comp = target.Words[i];
                if (cloned.MotherTongue == comp.MotherTongue &&
                    cloned.ForeignLang == comp.ForeignLang &&
                    cloned.ForeignLangSynonym == comp.ForeignLangSynonym)
                {
                    if (cloned.PracticeDate > comp.PracticeDate)
                    {
                        target.Words[i] = cloned;
                    }

                    return;
                }
            }

            target.Words.Add(cloned);
        }
Esempio n. 24
0
        public bool Write(VocabularyBook book)
        {
            string raw;

            using (var writer = new StringWriter())
            {
                writer.WriteLine(book.FilePath);
                writer.Write((int)book.PracticeMode);

                foreach (var word in book.Words)
                {
                    writer.WriteLine();

                    writer.Write(word.PracticeStateNumber);
                    writer.Write('#');
                    if (word.PracticeDate != DateTime.MinValue)
                    {
                        writer.Write(word.PracticeDate.ToString("dd.MM.yyyy HH:mm"));
                    }
                }

                raw = writer.ToString();
            }

            try
            {
                WriteFile(Path.Combine(Settings.Default.VhrPath, book.VhrCode + ".vhr"), raw);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(Messages.VocupFileWriteErrorEx, ex), Messages.VocupFileWriteErrorT,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            return(true);
        }
Esempio n. 25
0
 public AddWordDialog(VocabularyBook book) : base(book)
 {
     Icon = Icon.FromHandle(Icons.Plus.GetHicon());
     Text = Words.AddWord;
 }
Esempio n. 26
0
        public bool Read(VocabularyBook book)
        {
            if (string.IsNullOrWhiteSpace(book.VhrCode))
            {
                return(false);
            }
            FileInfo vhrInfo = new FileInfo(Path.Combine(Settings.Default.VhrPath, book.VhrCode + ".vhr"));

            if (!vhrInfo.Exists)
            {
                return(false);
            }

            string plaintext;

            try
            {
                plaintext = ReadFile(vhrInfo.FullName);
            }
            catch (FormatException)
            {
                DeleteInvalidFile(vhrInfo);
                return(false);
            }
            catch (System.Security.Cryptography.CryptographicException)
            {
                DeleteInvalidFile(vhrInfo);
                return(false);
            }

            using (StringReader reader = new StringReader(plaintext))
            {
                string path = reader.ReadLine();
                string mode = reader.ReadLine();

                if (string.IsNullOrWhiteSpace(path) ||
                    string.IsNullOrWhiteSpace(mode) || !int.TryParse(mode, out int imode) || !((PracticeMode)imode).IsValid())
                {
                    DeleteInvalidFile(vhrInfo);
                    return(false);
                }

                List <(int stateNumber, DateTime date)> results = new List <(int stateNumber, DateTime date)>();

                while (true)
                {
                    string line = reader.ReadLine();
                    if (line == null)
                    {
                        break;
                    }
                    string[] columns = line.Split('#');
                    if (columns.Length != 2 || !int.TryParse(columns[0], out int state) || !PracticeStateHelper.Parse(state).IsValid())
                    {
                        DeleteInvalidFile(vhrInfo);
                        return(false);
                    }
                    DateTime time = DateTime.MinValue;
                    if (!string.IsNullOrWhiteSpace(columns[1]) && !DateTime.TryParseExact(columns[1], "dd.MM.yyyy HH:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out time))
                    {
                        DeleteInvalidFile(vhrInfo);
                        return(false);
                    }
                    results.Add((state, time));
                }

                bool countMatch = book.Words.Count == results.Count;

                FileInfo vhfInfo  = new FileInfo(book.FilePath);
                FileInfo pathInfo = new FileInfo(path);

                if (vhfInfo.FullName.Equals(pathInfo.FullName, StringComparison.OrdinalIgnoreCase))
                {
                    if (!countMatch)
                    {
                        MessageBox.Show(Messages.VhrInvalidRowCount, Messages.VhrCorruptFileT, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        try { vhrInfo.Delete(); } catch { }
                        return(false);
                    }
                }
                else
                {
                    if (!countMatch)
                    {
                        MessageBox.Show(Messages.VhrInvalidRowCountAndOtherFile, Messages.VhrCorruptFileT, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return(false);
                    }

                    if (pathInfo.Exists)
                    {
                        book.GenerateVhrCode(); // Save new results file if the old one is in use by another file
                    }
                    book.UnsavedChanges = true;
                }

                book.PracticeMode = (PracticeMode)imode;

                for (int i = 0; i < book.Words.Count; i++)
                {
                    VocabularyWord word = book.Words[i];
                    (word.PracticeStateNumber, word.PracticeDate) = results[i];
                }
            }

            return(true);
        }
Esempio n. 27
0
        public bool Read(string path, VocabularyBook book)
        {
            string plaintext;

            try
            {
                plaintext = ReadFile(path);
            }
            catch (NotSupportedException)
            {
                MessageBox.Show(Messages.VhfMustUpdate, Messages.VhfMustUpdateT, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            catch (FormatException)
            {
                MessageBox.Show(Messages.VhfCorruptFile, Messages.VhfCorruptFileT, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }
            catch (System.Security.Cryptography.CryptographicException)
            {
                MessageBox.Show(Messages.VhfCorruptFile, Messages.VhfCorruptFileT, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(false);
            }

            using (StringReader reader = new StringReader(plaintext))
            {
                string version      = reader.ReadLine();
                string vhrCode      = reader.ReadLine();
                string motherTongue = reader.ReadLine();
                string foreignLang  = reader.ReadLine();

                if (string.IsNullOrWhiteSpace(version) || !Version.TryParse(version, out Version versionObj))
                {
                    MessageBox.Show(Messages.VhfInvalidVersion, Messages.VhfCorruptFileT, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }
                else if (versionObj.CompareTo(Util.AppInfo.FileVersion) == 1)
                {
                    MessageBox.Show(Messages.VhfMustUpdate, Messages.VhfMustUpdateT, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return(false);
                }

                if (vhrCode == null)
                {
                    MessageBox.Show(Messages.VhfInvalidVhrCode, Messages.VhfCorruptFileT, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }

                book.VhrCode  = vhrCode;
                book.FilePath = path;

                if (string.IsNullOrWhiteSpace(motherTongue) ||
                    string.IsNullOrWhiteSpace(foreignLang) ||
                    motherTongue == foreignLang)
                {
                    MessageBox.Show(Messages.VhfInvalidLanguages, Messages.VhfCorruptFileT, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }

                book.MotherTongue = motherTongue;
                book.ForeignLang  = foreignLang;

                while (true)
                {
                    string line = reader.ReadLine();
                    if (line == null)
                    {
                        break;
                    }
                    string[] columns = line.Split('#');
                    if (columns.Length != 3)
                    {
                        MessageBox.Show(Messages.VhfInvalidRow, Messages.VhfCorruptFileT, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return(false);
                    }
                    VocabularyWord word = new VocabularyWord()
                    {
                        Owner              = book,
                        MotherTongue       = columns[0],
                        ForeignLang        = columns[1],
                        ForeignLangSynonym = columns[2]
                    };
                    book.Words.Add(word);
                }
            }

            return(true);
        }
Esempio n. 28
0
        public bool Import(string path, VocabularyBook book, bool importSettings)
        {
            try
            {
                var config = new Configuration();
                config.RegisterClassMap(new EntryMap());

                using (var file = new StreamReader(path, true))
                    using (var reader = new CsvReader(file, config))
                    {
                        if (!reader.Read() || !reader.ReadHeader())
                        {
                            MessageBox.Show(Messages.CsvInvalidHeader, Messages.CsvInvalidHeaderT, MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                            return(false);
                        }

                        if (reader.Context.HeaderRecord.Length != 2)
                        {
                            MessageBox.Show(
                                string.Format(Messages.CsvInvalidHeaderColumns, reader.Context.HeaderRecord.Length),
                                Messages.CsvInvalidHeaderT, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            return(false);
                        }

                        if (importSettings)
                        {
                            book.MotherTongue = reader.Context.HeaderRecord[0];
                            book.ForeignLang  = reader.Context.HeaderRecord[1];
                        }
                        else if (reader.Context.HeaderRecord[0] != book.MotherTongue ||
                                 reader.Context.HeaderRecord[1] != book.ForeignLang)
                        {
                            var dialogResult = MessageBox.Show(
                                string.Format(Messages.CsvInvalidLanguages, reader.Context.HeaderRecord[0],
                                              reader.Context.HeaderRecord[1]),
                                Messages.CsvInvalidHeaderT, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                            if (dialogResult == DialogResult.No)
                            {
                                return(false);
                            }
                        }

                        foreach (var entry in reader.GetRecords <Entry>())
                        {
                            if (!book.Words.Any(x =>
                                                x.MotherTongue == entry.MotherTongue && x.ForeignLangText == entry.ForeignLang))
                            {
                                book.Words.Add(new VocabularyWord
                                {
                                    Owner           = book,
                                    MotherTongue    = entry.MotherTongue,
                                    ForeignLangText = entry.ForeignLang
                                });
                            }
                        }
                    }

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(Messages.CsvImportError, ex), Messages.UnexpectedErrorT,
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(false);
        }
Esempio n. 29
0
        public bool Import(string path, VocabularyBook book, bool importSettings, bool ansiEncoding)
        {
            try
            {
                using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    CsvConfiguration config = new CsvConfiguration(CultureInfo.CurrentCulture);

                    var encoding = ansiEncoding ? Encoding.GetEncoding(1252) : Encoding.UTF8;

                    using (var streamReader = new StreamReader(fileStream, encoding, detectEncodingFromByteOrderMarks: true, 1024, leaveOpen: true))
                    {
                        char delimiter = DetectDelimiter(streamReader, 10, new[] { ',', ';', '\t', '|' });
                        if (delimiter != 0)
                        {
                            config.Delimiter = delimiter.ToString();
                        }
                    }

                    // Reset to start of file and create a new StreamReader to detect byte order marks again
                    fileStream.Seek(0, SeekOrigin.Begin);

                    using (var streamReader = new StreamReader(fileStream, encoding, detectEncodingFromByteOrderMarks: true))
                        using (var reader = new CsvReader(streamReader, config))
                        {
                            reader.Context.RegisterClassMap(new EntryMap());

                            if (!reader.Read() || !reader.ReadHeader())
                            {
                                MessageBox.Show(Messages.CsvInvalidHeader, Messages.CsvInvalidHeaderT, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return(false);
                            }

                            if (reader.HeaderRecord.Length != 2)
                            {
                                MessageBox.Show(string.Format(Messages.CsvInvalidHeaderColumns, reader.HeaderRecord.Length),
                                                Messages.CsvInvalidHeaderT, MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return(false);
                            }

                            if (importSettings)
                            {
                                book.MotherTongue = reader.HeaderRecord[0];
                                book.ForeignLang  = reader.HeaderRecord[1];
                            }
                            else
                            {
                                if (!book.MotherTongue.Equals(reader.HeaderRecord[0], StringComparison.OrdinalIgnoreCase) ||
                                    !book.ForeignLang.Equals(reader.HeaderRecord[1], StringComparison.OrdinalIgnoreCase))
                                {
                                    DialogResult dialogResult = MessageBox.Show(
                                        string.Format(Messages.CsvInvalidLanguages, reader.HeaderRecord[0], reader.HeaderRecord[1]),
                                        Messages.CsvInvalidHeaderT, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                                    if (dialogResult == DialogResult.No)
                                    {
                                        return(false);
                                    }
                                }
                            }

                            foreach (Entry entry in reader.GetRecords <Entry>())
                            {
                                if (!book.Words.Any(x => x.MotherTongue == entry.MotherTongue && x.ForeignLangText == entry.ForeignLang))
                                {
                                    book.Words.Add(new VocabularyWord
                                    {
                                        Owner           = book,
                                        MotherTongue    = entry.MotherTongue,
                                        ForeignLangText = entry.ForeignLang
                                    });
                                }
                            }
                        }
                }

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format(Messages.CsvImportError, ex), Messages.UnexpectedErrorT, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return(false);
        }