示例#1
0
        /// <summary>
        /// Copies to.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="progressDelegate">The progress delegate.</param>
        /// <remarks>Documented by Dev03, 2009-01-13</remarks>
        public void CopyTo(ICopy target, CopyToProgress progressDelegate)
        {
            CopyBase.Copy(this, target, typeof(ICard), progressDelegate);

            //copy media objects
            ICard targetCard = target as ICard;

            if (targetCard != null)
            {
                foreach (IMedia media in QuestionMedia)
                {
                    targetCard.AddMedia(media, Side.Question);
                }
                foreach (IMedia media in AnswerMedia)
                {
                    targetCard.AddMedia(media, Side.Answer);
                }
                try
                {
                    if (targetCard is MLifter.DAL.XML.XmlCard)
                    {
                        (targetCard as MLifter.DAL.XML.XmlCard).Id = Id;
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Tried to set the card id for XML but failed: " + ex.ToString());
                }
            }
        }
        public void ICardRemoveMediaTest()
        {
            TestInfrastructure.DebugLineStart(TestContext);
            if (TestInfrastructure.IsActive(TestContext))
            {
                using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser))
                {
                    ICard  card       = writeLM.Cards.AddNew();
                    string testImage  = TestInfrastructure.GetTestImage();
                    IMedia mediaImage = card.CreateMedia(EMedia.Image, testImage, true, true, true);
                    card.AddMedia(mediaImage, Side.Question);
                    string testAudio  = TestInfrastructure.GetTestAudio();
                    IMedia mediaAudio = card.CreateMedia(EMedia.Audio, testAudio, true, true, true);
                    card.AddMedia(mediaAudio, Side.Answer);
                    card.RemoveMedia(mediaAudio);
                    Assert.AreEqual(1, card.QuestionMedia.Count, "Media was removed at the wrong Place (QuestionSide instead of AnswerSide)");
                    Assert.AreEqual(0, card.AnswerMedia.Count, "Media couldn't be removed from ICard");
                    try { File.Delete(testImage); }
                    catch { }
                    try { File.Delete(testAudio); }
                    catch { }
                }
            }

            TestInfrastructure.DebugLineEnd(TestContext);
        }
        public void ICardClearAllMediaTest()
        {
            TestInfrastructure.DebugLineStart(TestContext);
            if (TestInfrastructure.IsActive(TestContext))
            {
                using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser))
                {
                    ICard  card      = writeLM.Cards.AddNew();
                    string testImage = TestInfrastructure.GetTestImage();
                    IMedia media     = card.CreateMedia(EMedia.Image, testImage, true, true, true);

                    for (int i = 0; i < 5; i++)
                    {
                        card.AddMedia(media, Side.Question);
                        card.AddMedia(media, Side.Answer);
                    }
                    card.ClearAllMedia();
                    Assert.AreEqual(0, card.AnswerMedia.Count, "Media couldn't be cleared from ICard");
                    Assert.AreEqual(0, card.QuestionMedia.Count, "Media couldn't be cleared from ICard");
                    try { File.Delete(testImage); }
                    catch { }
                }
            }

            TestInfrastructure.DebugLineEnd(TestContext);
        }
示例#4
0
        public void ICardAddImagePerformanceTest()
        {
            TestInfrastructure.DebugLineStart(TestContext);
            IMedia media;

            if (TestInfrastructure.IsActive(TestContext))
            {
                using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser))
                {
                    Tools.TestStopWatch.Start(TestContext);
                    ICard  card      = writeLM.Cards.AddNew();
                    string testImage = TestInfrastructure.GetLargeTestImage();
                    media = card.CreateMedia(EMedia.Image, testImage, true, true, true);
                    card.AddMedia(media, Side.Question);
                    Assert.AreEqual(1, card.QuestionMedia.Count, "ICard doesn't save a QuestionMedia (image) with the method 'card.AddMedia(Media, Side.Question)'");
                    Assert.AreEqual(0, card.AnswerMedia.Count, "ICard saves a QuestionMedia (image) to an AnswerMedia");
                    card.ClearAllMedia();
                    Tools.TestStopWatch.Stop(TestContext);
                    try { File.Delete(testImage); }
                    catch { }
                }
            }

            TestInfrastructure.DebugLineEnd(TestContext);
        }
        public void MediaServerTestGetMediaTest()
        {
            TestInfrastructure.DebugLineStart(TestContext);
            if (TestInfrastructure.IsActive(TestContext))
            {
                if (!(TestContext.DataRow["type"].ToString().ToLower() == "file"))
                {
                    using (MLifter.DAL.Interfaces.IDictionary testLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser))
                    {
                        Dictionary <int, int>       mediaIds = new Dictionary <int, int>();                 //key: idCounter, value: mediaId
                        Dictionary <string, byte[]> testData = new Dictionary <string, byte[]>();
                        //Filling DB with Test Data
                        for (int i = 0; i < TestInfrastructure.Loopcount; i++)
                        {
                            string testMedia = TestInfrastructure.GetTestImage();
                            testData.Add(testMedia, File.ReadAllBytes(testMedia));
                        }
                        int idCounter = 0;
                        //Putting Test Data into db
                        foreach (string testMedia in testData.Keys)
                        {
                            ICard  card  = testLM.Cards.Create();
                            IMedia media = card.AddMedia(card.CreateMedia(EMedia.Image, testMedia, true, true, false), Side.Question);
                            mediaIds[idCounter++] = media.Id;
                        }

                        //Create a new MediaServerInstance
                        DbMediaServer myMediaServer = DbMediaServer.Instance(8080, testLM.Parent);
                        myMediaServer.Start();

                        //Wait until server is ready
                        while (!myMediaServer.IsReady)
                        {
                            ;
                        }

                        //Verify
                        idCounter = 0;
                        foreach (string testMedia in testData.Keys)
                        {
                            Uri       theServerUri_itme = DbMediaServer.Instance(testLM.Parent).GetMediaURI(mediaIds[idCounter++]);
                            WebClient client            = new WebClient();
                            byte[]    downloadData_item = client.DownloadData(theServerUri_itme.ToString());
                            byte[]    b = testData[testMedia];

                            for (int i = 0; i < b.Length; i++)
                            {
                                Assert.IsTrue(b[i].Equals(downloadData_item[i]), "Test Data does not match");
                            }
                        }

                        //Stop the Media Server again
                        myMediaServer.Stop();
                    }
                }
            }
            TestInfrastructure.DebugLineEnd(TestContext);
        }
示例#6
0
        /// <summary>
        /// Copies to.
        /// </summary>
        /// <param name="target">The target.</param>
        /// <param name="progressDelegate">The progress delegate.</param>
        /// <remarks>Documented by Dev03, 2009-03-23</remarks>
        public void CopyTo(ICopy target, CopyToProgress progressDelegate)
        {
            CopyBase.Copy(this, target, typeof(ICard), progressDelegate);

            //copy media objects
            ICard targetCard = target as ICard;

            if (targetCard != null)
            {
                foreach (IMedia media in QuestionMedia)
                {
                    targetCard.AddMedia(media, Side.Question);
                }
                foreach (IMedia media in AnswerMedia)
                {
                    targetCard.AddMedia(media, Side.Answer);
                }
            }
        }
        public void ICardNullObjectMediaTest()
        {
            TestInfrastructure.DebugLineStart(TestContext);
            if (TestInfrastructure.IsActive(TestContext))
            {
                using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser))
                {
                    ICard card = writeLM.Cards.AddNew();
                    card.AddMedia(null, Side.Question);
                }
            }
            else
            {
                throw new NullReferenceException();
            }

            TestInfrastructure.DebugLineEnd(TestContext);
        }
        public void ICardSetGetAnswerMedia()
        {
            TestInfrastructure.DebugLineStart(TestContext);
            if (TestInfrastructure.IsActive(TestContext))
            {
                using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser))
                {
                    IChapter chapter = writeLM.Chapters.AddNew();
                    ICard    card    = writeLM.Cards.AddNew();
                    card.Chapter = chapter.Id;

                    string testImage = TestInfrastructure.GetTestImage();
                    IMedia media     = card.CreateMedia(EMedia.Image, testImage, true, true, true);
                    card.AddMedia(media, Side.Answer);
                    Assert.IsTrue(writeLM.Cards.Get(card.Id).AnswerMedia[0] != null, "Couldn't get AnswerMediaFile from IDictionary");
                    try { File.Delete(testImage); }
                    catch { }
                }
            }
            TestInfrastructure.DebugLineEnd(TestContext);
        }
示例#9
0
        public void AddMediaObjectsTest()
        {
            string workingDirectory = Environment.CurrentDirectory;
            int    newcardid        = 0;
            int    newmediacount    = 0;

            using (IDictionary target = user.Open())
            {
                //get temp folder
                DirectoryInfo tempfolder;
                int           tempfolderindex = 0;
                do
                {
                    tempfolder = new DirectoryInfo(Path.Combine(Path.GetTempPath(), "MLifterTest" + tempfolderindex.ToString()));
                    tempfolderindex++;
                } while (tempfolder.Exists);
                tempfolder.Create();

                try
                {
                    List <KeyValuePair <FileInfo, EMedia> > mediafiles = new List <KeyValuePair <FileInfo, EMedia> >();

                    //get some Media files
                    foreach (ICard card in target.Cards.Cards)
                    {
                        foreach (IMedia media in card.QuestionMedia)
                        {
                            FileInfo mediafile = new FileInfo(media.Filename);
                            if (mediafile.Exists)
                            {
                                mediafile = mediafile.CopyTo(Path.Combine(tempfolder.FullName, mediafile.Name), true);
                                mediafiles.Add(new KeyValuePair <FileInfo, EMedia>(mediafile, media.MediaType));
                            }
                        }
                    }

                    Assert.IsTrue(mediafiles.Count > 0, "No Media file found in sample LM.");

                    //add the Media files to a new card
                    ICard newcard = target.Cards.AddNew();
                    newcardid = newcard.Id;

                    foreach (KeyValuePair <FileInfo, EMedia> mediafile in mediafiles)
                    {
                        IMedia media = newcard.CreateMedia(mediafile.Value, mediafile.Key.FullName, true, true, false);
                        if (GetRandBool())                         //both ways must work
                        {
                            newcard.AddMedia(media, Side.Question);
                        }
                        else
                        {
                            newcard.QuestionMedia.Add(media);
                        }
                        newmediacount++;
                    }

                    //AddMedia has changed the current directory
                    Environment.CurrentDirectory = workingDirectory;

                    target.Save();
                }
                finally
                {
                    if (tempfolder != null && tempfolder.Exists)
                    {
                        tempfolder.Delete(true);
                    }
                }
            }
            //reopen file
            using (IDictionary target = user.Open())
            {
                ICard card = target.Cards.Get(newcardid);

                //Assert.IsTrue(card.QuestionMedia.Count == newmediacount && card.AnswerMedia.Count == 0, "Not all Media files were added properly to the card.");
                //Can currently not be checked: Audio fils get cleaned up (only the last one survives) [ML-1320]

                int foundmediacount = 0;
                foreach (IMedia media in card.QuestionMedia)
                {
                    //check if file exists in Media directory
                    Assert.IsTrue(File.Exists(media.Filename), "Media file could not be found: " + media.Filename);
                    foundmediacount++;
                }
                Assert.IsTrue(newmediacount == 0 || foundmediacount > 0, "There were Media objects added, but could not be found afterwards.");
                target.Cards.Delete(newcardid);
                target.Save();
            }
        }
        public void ICardAddMediaTest()
        {
            TestInfrastructure.DebugLineStart(TestContext);
            IMedia media;

            if (TestInfrastructure.IsActive(TestContext))
            {
                using (IDictionary writeLM = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser))
                {
                    ICard  card      = writeLM.Cards.AddNew();
                    string testImage = TestInfrastructure.GetTestImage();
                    media = card.CreateMedia(EMedia.Image, testImage, true, true, true);
                    card.AddMedia(media, Side.Question);
                    Assert.AreEqual(1, card.QuestionMedia.Count, "ICard doesn't save a QuestionMedia (image) with the method 'card.AddMedia(Media, Side.Question)'");
                    Assert.AreEqual(0, card.AnswerMedia.Count, "ICard saves a QuestionMedia (image) to an AnswerMedia");
                    card.ClearAllMedia();
                    card.AddMedia(media, Side.Answer);
                    Assert.AreEqual(1, card.AnswerMedia.Count, "ICard doesn't save an AnswerMedia (image) with the method 'card.AddMedia(Media, Side.Answer)'");
                    Assert.AreEqual(0, card.QuestionMedia.Count, "ICard saves a AnswerMedia (image) to an QuestionMedia");
                    card.ClearAllMedia();

                    string testAudio = TestInfrastructure.GetTestAudio();
                    //With the following parameters, the audiofile is saved 2 times
                    media = card.CreateMedia(EMedia.Audio, testAudio, true, true, true);
                    card.AddMedia(media, Side.Question);
                    Assert.AreEqual(1, card.QuestionMedia.Count, "ICard doesn't save a QuestionMedia (audio) with the method 'card.AddMedia(Media, Side.Question)'");
                    Assert.AreEqual(0, card.AnswerMedia.Count, "ICard saves a QuestionMedia (audio) to an AnswerMedia");
                    card.ClearAllMedia();
                    card.AddMedia(media, Side.Answer);
                    Assert.AreEqual(1, card.AnswerMedia.Count, "ICard doesn't save an AnswerMedia (audio) with the method 'card.AddMedia(Media, Side.Answer)'");
                    Assert.AreEqual(0, card.QuestionMedia.Count, "ICard saves a AnswerMedia (audio) to an QuestionMedia");
                    card.ClearAllMedia();

                    media = card.CreateMedia(EMedia.Audio, testAudio, true, false, true);
                    card.AddMedia(media, Side.Question);
                    Assert.AreEqual(1, card.QuestionMedia.Count, "ICard doesn't save a QuestionMedia (audio) with the method 'card.AddMedia(Media, Side.Question)'");
                    Assert.AreEqual(0, card.AnswerMedia.Count, "ICard saves a QuestionMedia (audio) to an AnswerMedia");
                    card.ClearAllMedia();
                    card.AddMedia(media, Side.Answer);
                    Assert.AreEqual(1, card.AnswerMedia.Count, "ICard doesn't save an AnswerMedia (audio) with the method 'card.AddMedia(Media, Side.Answer)'");
                    Assert.AreEqual(0, card.QuestionMedia.Count, "ICard saves a AnswerMedia (audio) to an QuestionMedia");
                    card.ClearAllMedia();

                    media = card.CreateMedia(EMedia.Audio, testAudio, true, true, false);
                    card.AddMedia(media, Side.Question);
                    Assert.AreEqual(1, card.QuestionMedia.Count, "ICard doesn't save a QuestionMedia (audio) with the method 'card.AddMedia(Media, Side.Question)'");
                    Assert.AreEqual(0, card.AnswerMedia.Count, "ICard saves a QuestionMedia (audio) to an AnswerMedia");
                    card.ClearAllMedia();
                    card.AddMedia(media, Side.Answer);
                    Assert.AreEqual(1, card.AnswerMedia.Count, "ICard doesn't save an AnswerMedia (audio) with the method 'card.AddMedia(Media, Side.Answer)'");
                    Assert.AreEqual(0, card.QuestionMedia.Count, "ICard saves a AnswerMedia (audio) to an QuestionMedia");
                    card.ClearAllMedia();

                    media = card.CreateMedia(EMedia.Audio, testAudio, true, false, false);
                    card.AddMedia(media, Side.Question);
                    Assert.AreEqual(1, card.QuestionMedia.Count, "ICard doesn't save a QuestionMedia (audio) with the method 'card.AddMedia(Media, Side.Question)'");
                    Assert.AreEqual(0, card.AnswerMedia.Count, "ICard saves a QuestionMedia (audio) to an AnswerMedia");
                    card.ClearAllMedia();
                    card.AddMedia(media, Side.Answer);
                    Assert.AreEqual(1, card.AnswerMedia.Count, "ICard doesn't save an AnswerMedia (audio) with the method 'card.AddMedia(Media, Side.Answer)'");
                    Assert.AreEqual(0, card.QuestionMedia.Count, "ICard saves a AnswerMedia (audio) to an QuestionMedia");
                    card.ClearAllMedia();

                    string testVideo = TestInfrastructure.GetTestVideo();
                    media = card.CreateMedia(EMedia.Video, testVideo, true, true, true);
                    card.AddMedia(media, Side.Question);
                    Assert.AreEqual(1, card.QuestionMedia.Count, "ICard doesn't save a QuestionMedia (video) with the method 'card.AddMedia(Media, Side.Question)'");
                    Assert.AreEqual(0, card.AnswerMedia.Count, "ICard saves a QuestionMedia (video) to an AnswerMedia");
                    card.ClearAllMedia();
                    card.AddMedia(media, Side.Answer);
                    Assert.AreEqual(1, card.AnswerMedia.Count, "ICard doesn't save an AnswerMedia (video) with the method 'card.AddMedia(Media, Side.Answer)'");
                    Assert.AreEqual(0, card.QuestionMedia.Count, "ICard saves a AnswerMedia (video) to an QuestionMedia");
                    card.ClearAllMedia();

                    try { File.Delete(testImage); }
                    catch { }
                    try { File.Delete(testAudio); }
                    catch { }
                    try { File.Delete(testVideo); }
                    catch { }
                }
            }

            TestInfrastructure.DebugLineEnd(TestContext);
        }
示例#11
0
        public void ExportHelperTest()
        {
            TestInfrastructure.DebugLineStart(TestContext);
            if (TestInfrastructure.IsActive(TestContext))
            {
                using (IDictionary target = TestInfrastructure.GetLMConnection(TestContext, TestInfrastructure.GetAdminUser))
                {
                    IChapter chapter = target.Chapters.AddNew();

                    List <int>    cardIds         = new List <int>();
                    List <string> testImages      = new List <string>();
                    List <string> testAudios      = new List <string>();
                    List <string> largeTestAudios = new List <string>();
                    List <string> testVideos      = new List <string>();
                    List <string> exportFiles     = new List <string>();
                    for (int i = 0; i < 10; i++)
                    {
                        ICard card = target.Cards.AddNew();
                        card.Chapter = chapter.Id;
                        cardIds.Add(card.Id);
                        string testImage = TestInfrastructure.GetTestImage();
                        IMedia image     = card.CreateMedia(EMedia.Image, testImage, true, true, true);
                        card.AddMedia(image, Side.Question);
                        card.AddMedia(image, Side.Answer);
                        string testAudio = TestInfrastructure.GetTestAudio();
                        IMedia audio     = card.CreateMedia(EMedia.Audio, testAudio, true, true, false);
                        card.AddMedia(audio, Side.Question);
                        card.AddMedia(audio, Side.Answer);
                        string largeTestAudio = TestInfrastructure.GetLargeTestAudio();
                        IMedia exaudio        = card.CreateMedia(EMedia.Audio, largeTestAudio, true, false, true);
                        card.AddMedia(exaudio, Side.Question);
                        card.AddMedia(exaudio, Side.Answer);
                        string testVideo = TestInfrastructure.GetTestVideo();
                        IMedia video     = card.CreateMedia(EMedia.Video, testVideo, true, false, false);
                        card.AddMedia(video, Side.Question);
                        card.AddMedia(video, Side.Answer);

                        testImages.Add(testImage);
                        testAudios.Add(testAudio);
                        largeTestAudios.Add(largeTestAudio);
                        testVideos.Add(testVideo);
                    }

                    MLifter.DAL.ImportExport.Exporter.ExportHelper exportHelper = new MLifter.DAL.ImportExport.Exporter.ExportHelper(target, Path.Combine(Path.GetTempPath(), "export.csv"));

                    for (int j = 0; j < target.Cards.Count; j++)
                    {
                        ICard card = target.Cards.Get(cardIds[j]);
                        foreach (IMedia media in card.QuestionMedia)
                        {
                            string fileName  = Path.Combine(Path.GetTempPath(), exportHelper.GetLocalFile(media.Filename, media.MediaType.ToString()));
                            string fileName2 = String.Empty;
                            exportFiles.Add(fileName);
                            switch (media.MediaType)
                            {
                            case EMedia.Audio:
                                if (media.Default.Value)
                                {
                                    fileName2 = testAudios[j];
                                }
                                else if (media.Example.Value)
                                {
                                    fileName2 = largeTestAudios[j];
                                }
                                else
                                {
                                    continue;
                                }
                                break;

                            case EMedia.Image:
                                fileName2 = testImages[j];
                                break;

                            case EMedia.Video:
                                fileName2 = testVideos[j];
                                break;

                            default:
                                continue;
                            }
                            byte[] eb = File.ReadAllBytes(fileName);
                            byte[] ib = File.ReadAllBytes(fileName2);

                            Assert.AreEqual <int>(ib.Length, eb.Length, String.Format("{0} and {1} are different in size! (loop={2})", fileName, fileName2, j));
                        }
                    }

                    foreach (string file in testImages)
                    {
                        try { File.Delete(file); }
                        catch { }
                    }
                    foreach (string file in testAudios)
                    {
                        try { File.Delete(file); }
                        catch { }
                    }
                    foreach (string file in largeTestAudios)
                    {
                        try { File.Delete(file); }
                        catch { }
                    }
                    foreach (string file in testVideos)
                    {
                        try { File.Delete(file); }
                        catch { }
                    }
                    foreach (string file in exportFiles)
                    {
                        try { File.Delete(file); }
                        catch { }
                    }
                }
            }

            TestInfrastructure.DebugLineEnd(TestContext);
        }
示例#12
0
        /// <summary>
        /// Updates the preview dictionary.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        /// <returns></returns>
        /// <remarks>Documented by Dev03, 2009-03-30</remarks>
        public static PreviewDictionary UpdatePreviewDictionary(PreviewDictionary dictionary)
        {
            using (XmlReader reader = XmlReader.Create(dictionary.Connection))
            {
                try
                {
                    ICard      card       = null;
                    IStatistic statistic  = null;
                    bool       imageFound = false;
                    while (reader.Read())
                    {
                        if (reader.IsEmptyElement || reader.NodeType == XmlNodeType.EndElement)
                        {
                            continue;
                        }
                        switch (reader.Name)
                        {
                        case "category":
                            int oldId, newId;
                            if (Int32.TryParse(reader.GetAttribute("id"), out newId) && (newId >= 0))
                            {
                                dictionary.Category = new Category(newId);
                            }
                            else if (Int32.TryParse(reader.ReadElementContentAsString(), out oldId) && (oldId >= 0))
                            {
                                dictionary.Category = new Category(oldId, false);
                            }
                            break;

                        case "author":
                            dictionary.Author = reader.ReadElementContentAsString().Trim();
                            break;

                        case "description":
                            dictionary.Description = reader.ReadElementContentAsString().Trim();
                            break;

                        case "sounddir":
                            dictionary.MediaDirectory = reader.ReadElementContentAsString().Trim();
                            break;

                        case "card":
                            card = dictionary.Cards.AddNew();
                            break;

                        case "answer":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                card.Answer.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
                            }
                            break;

                        case "question":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                card.Question.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
                            }
                            break;

                        case "answerexample":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                card.AnswerExample.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
                            }
                            break;

                        case "questionexample":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                card.QuestionExample.AddWords(Helper.SplitWordList(reader.ReadElementContentAsString()));
                            }
                            break;

                        case "questionimage":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                IMedia qmedia = card.CreateMedia(EMedia.Image, reader.ReadElementContentAsString(), true, false, false);
                                card.AddMedia(qmedia, Side.Question);
                                imageFound = true;
                            }
                            break;

                        case "answerimage":
                            if (imageFound)
                            {
                                continue;
                            }
                            if (card != null)
                            {
                                IMedia amedia = card.CreateMedia(EMedia.Image, reader.ReadElementContentAsString(), true, false, false);
                                card.AddMedia(amedia, Side.Question);
                            }
                            break;

                        case "stats":
                            statistic = new PreviewStatistic();
                            int sId;
                            if (Int32.TryParse(reader.GetAttribute("id"), out sId) && (sId >= 0))
                            {
                                (statistic as PreviewStatistic).Id = sId;
                            }
                            dictionary.Statistics.Add(statistic);
                            break;

                        case "start":
                            if (statistic != null)
                            {
                                statistic.StartTimestamp = XmlConvert.ToDateTime(reader.ReadElementContentAsString(), XmlDateTimeSerializationMode.RoundtripKind);
                            }
                            break;

                        case "end":
                            if (statistic != null)
                            {
                                statistic.EndTimestamp = XmlConvert.ToDateTime(reader.ReadElementContentAsString(), XmlDateTimeSerializationMode.RoundtripKind);
                            }
                            break;

                        case "right":
                            if (statistic != null)
                            {
                                statistic.Right = XmlConvert.ToInt32(reader.ReadElementContentAsString());
                            }
                            break;

                        case "wrong":
                            if (statistic != null)
                            {
                                statistic.Wrong = XmlConvert.ToInt32(reader.ReadElementContentAsString());
                            }
                            break;

                        default:
                            break;
                        }
                        //System.Threading.Thread.Sleep(5);
                    }
                }
                catch
                {
                    dictionary.Category = new Category(0);
                }
                dictionary.Id = 1;
                return(dictionary);
            }
        }
示例#13
0
        /// <summary>
        /// Sets the card values.
        /// </summary>
        /// <param name="card">The card.</param>
        /// <remarks>Documented by Dev05, 2007-10-12</remarks>
        private void SetCardValues(ICard card)
        {
            card.Answer.ClearWords();
            card.Question.ClearWords();
            card.Answer.AddWords(GetWord(Side.Answer).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
            card.Question.AddWords(GetWord(Side.Question).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
            card.AnswerDistractors.ClearWords();
            card.QuestionDistractors.ClearWords();
            card.AnswerDistractors.AddWords(GetDistractors(Side.Answer).ToArray());
            card.QuestionDistractors.AddWords(GetDistractors(Side.Question).ToArray());

            card.AnswerExample.ClearWords();
            card.AnswerExample.AddWord(card.AnswerExample.CreateWord(textBoxAnswerExample.Text, WordType.Sentence, false));
            card.QuestionExample.ClearWords();
            card.QuestionExample.AddWord(card.QuestionExample.CreateWord(textBoxQuestionExample.Text, WordType.Sentence, false));

            if (comboBoxChapter.SelectedItem != null && comboBoxChapter.SelectedItem is IChapter)
                card.Chapter = ((IChapter)comboBoxChapter.SelectedItem).Id;
            card.Active = checkBoxActive.Checked;

            card.ClearAllMedia(false);

            try
            {
                this.Parent.Enabled = false;        //ML-2413, maintain doesn't block user inputs while loading stuff into db
                //currently only the DB can show a progress bar
                card.CreateMediaProgressChanged += new StatusMessageEventHandler(card_CreateMediaProgressChanged);
                statusDialog = new LoadStatusMessage(Resources.CARDEDIT_LOADING_MEDIA_TO_DB, 100, dictionary.IsDB);
                if (!(card is DAL.Preview.PreviewCard)) statusDialog.Show();
                statusDialog.SetProgress(0);

                //Image
                if (pictureBoxAnswer.Tag as IImage != null)
                {
                    if (checkBoxResizeAnswer.Checked)
                        ResizePicture(pictureBoxAnswer);
                    card.AddMedia(pictureBoxAnswer.Tag as IMedia, Side.Answer);
                }
                if (pictureBoxQuestion.Tag as IImage != null)
                {
                    if (checkBoxResizeQuestion.Checked)
                        ResizePicture(pictureBoxQuestion);

                    IMedia media = pictureBoxQuestion.Tag as IMedia;
                    media = card.AddMedia(media, Side.Question);

                    if (checkBoxSamePicture.Checked)
                        card.AddMedia(media, Side.Answer);
                }

                //Audio
                if (buttonAnswerAudio.Tag as IAudio != null)
                    card.AddMedia(buttonAnswerAudio.Tag as IMedia, Side.Answer);
                if (buttonAnswerExampleAudio.Tag as IAudio != null)
                    card.AddMedia(buttonAnswerExampleAudio.Tag as IMedia, Side.Answer);
                if (buttonQuestionAudio.Tag as IAudio != null)
                    card.AddMedia(buttonQuestionAudio.Tag as IMedia, Side.Question);
                if (buttonQuestionExampleAudio.Tag as IAudio != null)
                    card.AddMedia(buttonQuestionExampleAudio.Tag as IMedia, Side.Question);

                //video
                if (buttonAnswerVideo.Tag as IVideo != null)
                    card.AddMedia(buttonAnswerVideo.Tag as IMedia, Side.Answer);
                if (buttonQuestionVideo.Tag as IVideo != null)
                    card.AddMedia(buttonQuestionVideo.Tag as IMedia, Side.Question);

                if (card.Active)
                {
                    int oldBox = card.Box;
                    card.Box = comboBoxCardBox.SelectedIndex;
                    int newBox = card.Box;

                    if (oldBox != newBox)
                    {
                        LearnLogStruct lls = new LearnLogStruct();
                        lls.CardsID = card.Id;
                        lls.SessionID = Log.LastSessionID;
                        lls.MoveType = MoveType.Manual;
                        lls.OldBox = oldBox;
                        lls.NewBox = newBox;
                        //Dummy values:
                        lls.TimeStamp = DateTime.Now;
                        lls.Duration = 0;
                        lls.CaseSensitive = false;
                        lls.CorrectOnTheFly = false;
                        lls.Direction = EQueryDirection.Question2Answer;
                        lls.LearnMode = EQueryType.Word;

                        Log.CreateLearnLogEntry(lls, dictionary.DictionaryDAL.Parent);
                    }
                }

                CardID = card.Id;
                Modified = false;
            }
            catch
            {
                throw;
            }
            finally
            {
                this.Parent.Enabled = true;
                card.CreateMediaProgressChanged -= new StatusMessageEventHandler(card_CreateMediaProgressChanged);
                if (statusDialog != null)
                {
                    statusDialog.Close();
                    statusDialog = null;
                }
            }
        }
示例#14
0
        /// <summary>
        /// Modifies the multiple cards.
        /// </summary>
        /// <remarks>Documented by Dev05, 2007-10-12</remarks>
        private void ModifyMultipleCards()
        {
            if (!Multiselect)
            {
                return;
            }

            Cursor = Cursors.WaitCursor;
            LoadStatusMessage statusMessage = new LoadStatusMessage(string.Format(Properties.Resources.CARDEDIT_STATUS_SAVING, cards.Length), cards.Length, true);

            statusMessage.Show();

            string[] question = GetWord(Side.Question).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            string[] answer   = GetWord(Side.Answer).Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            string questionExample = textBoxQuestionExample.Text;
            string answerExample   = textBoxAnswerExample.Text;

            foreach (int id in cards)
            {
                Dictionary.Cards.ChangeCardOnDifference(id, question, answer, questionExample, answerExample,
                                                        (comboBoxChapter.SelectedItem is IChapter ? ((IChapter)comboBoxChapter.SelectedItem).Id : -1), Resources.MAINTAIN_UNCHANGED);

                ICard card = Dictionary.Cards.GetCardByID(id).BaseCard;
                if (checkBoxActive.CheckState != CheckState.Indeterminate)
                {
                    if (card.Active != checkBoxActive.Checked)
                    {
                        card.Active = checkBoxActive.Checked;
                    }
                }

                if (comboBoxCardBox.SelectedIndex != -1 && card.Active)
                {
                    card.Box = comboBoxCardBox.SelectedIndex;
                }

                //Save old Media objects
                Dictionary <string, IMedia> oldMedia = new Dictionary <string, IMedia>();
                IMedia media = null;
                if ((media = Dictionary.Cards.GetImageObject(card, Side.Answer, true)) != null)
                {
                    oldMedia.Add("answerImage", media);
                }
                if ((media = Dictionary.Cards.GetImageObject(card, Side.Question, true)) != null)
                {
                    oldMedia.Add("questionImage", media);
                }
                if ((media = Dictionary.Cards.GetAudioObject(card, Side.Answer, true, false, true)) != null)
                {
                    oldMedia.Add("answerAudio", media);
                }
                if ((media = Dictionary.Cards.GetAudioObject(card, Side.Question, true, false, true)) != null)
                {
                    oldMedia.Add("questionAudio", media);
                }
                if ((media = Dictionary.Cards.GetAudioObject(card, Side.Answer, false, true, true)) != null)
                {
                    oldMedia.Add("answerExample", media);
                }
                if ((media = Dictionary.Cards.GetAudioObject(card, Side.Question, false, true, true)) != null)
                {
                    oldMedia.Add("questionExample", media);
                }
                if ((media = Dictionary.Cards.GetVideoObject(card, Side.Answer, true)) != null)
                {
                    oldMedia.Add("answerVideo", media);
                }
                if ((media = Dictionary.Cards.GetVideoObject(card, Side.Question, true)) != null)
                {
                    oldMedia.Add("questionVideo", media);
                }

                card.ClearAllMedia(false);

                //Image
                if (pictureBoxAnswer.Tag as IImage != null && checkBoxSamePicture.CheckState != CheckState.Unchecked)
                {
                    card.AddMedia(pictureBoxAnswer.Tag as IMedia, Side.Answer);
                }
                else if (pictureBoxAnswer.Tag is PreviousValueDummy && oldMedia.ContainsKey("answerImage") && checkBoxSamePicture.CheckState != CheckState.Unchecked)
                {
                    card.AddMedia(oldMedia["answerImage"], Side.Answer);
                }
                if (pictureBoxQuestion.Tag as IImage != null)
                {
                    IMedia image = pictureBoxQuestion.Tag as IMedia;
                    card.AddMedia(image, Side.Question);
                    if (checkBoxSamePicture.CheckState == CheckState.Checked)
                    {
                        card.AddMedia(image, Side.Answer);
                    }
                }
                else if (pictureBoxQuestion.Tag is PreviousValueDummy && oldMedia.ContainsKey("questionImage"))
                {
                    IMedia image = oldMedia["questionImage"];
                    card.AddMedia(image, Side.Question);
                    if (checkBoxSamePicture.CheckState == CheckState.Checked)
                    {
                        card.AddMedia(image, Side.Answer);
                    }
                }

                //Audio
                if (buttonAnswerAudio.Tag as IAudio != null)
                {
                    card.AddMedia(buttonAnswerAudio.Tag as IMedia, Side.Answer);
                }
                else if (buttonAnswerAudio.Tag is PreviousValueDummy && oldMedia.ContainsKey("answerAudio"))
                {
                    card.AddMedia(oldMedia["answerAudio"], Side.Answer);
                }
                if (buttonAnswerExampleAudio.Tag as IAudio != null)
                {
                    card.AddMedia(buttonAnswerExampleAudio.Tag as IMedia, Side.Answer);
                }
                else if (buttonAnswerExampleAudio.Tag is PreviousValueDummy && oldMedia.ContainsKey("answerExample"))
                {
                    card.AddMedia(oldMedia["answerExample"], Side.Answer);
                }
                if (buttonQuestionAudio.Tag as IAudio != null)
                {
                    card.AddMedia(buttonQuestionAudio.Tag as IMedia, Side.Question);
                }
                else if (buttonQuestionAudio.Tag is PreviousValueDummy && oldMedia.ContainsKey("questionAudio"))
                {
                    card.AddMedia(oldMedia["questionAudio"], Side.Question);
                }
                if (buttonQuestionExampleAudio.Tag as IAudio != null)
                {
                    card.AddMedia(buttonQuestionExampleAudio.Tag as IMedia, Side.Question);
                }
                else if (buttonQuestionExampleAudio.Tag is PreviousValueDummy && oldMedia.ContainsKey("questionExample"))
                {
                    card.AddMedia(oldMedia["questionExample"], Side.Question);
                }

                //Video
                if (buttonAnswerVideo.Tag as IVideo != null)
                {
                    card.AddMedia(buttonAnswerVideo.Tag as IMedia, Side.Answer);
                }
                else if (buttonAnswerVideo.Tag is PreviousValueDummy && oldMedia.ContainsKey("answerVideo"))
                {
                    card.AddMedia(oldMedia["answerVideo"], Side.Answer);
                }
                if (buttonQuestionVideo.Tag as IVideo != null)
                {
                    card.AddMedia(buttonQuestionVideo.Tag as IMedia, Side.Question);
                }
                else if (buttonQuestionVideo.Tag is PreviousValueDummy && oldMedia.ContainsKey("questionVideo"))
                {
                    card.AddMedia(oldMedia["questionVideo"], Side.Question);
                }

                statusMessage.ProgressStep();
            }

            statusMessage.Close();

            Modified = false;
            OnMultiEdit(EventArgs.Empty);
            Cursor = Cursors.Default;
        }
示例#15
0
        /// <summary>
        /// Imports to dictionary.
        /// </summary>
        /// <param name="dictionary">The dictionary.</param>
        /// <param name="data">The data.</param>
        /// <param name="chapter">The chapter to import to.</param>
        /// <param name="fields">The fields on which id the field is in the data.</param>
        /// <param name="worker">The worker to report the status; could be null.</param>
        /// <param name="cardTimeStamp">The card time stamp.</param>
        /// <param name="splitSynonyms">if set to <c>true</c> [split synonyms].</param>
        /// <remarks>Documented by Dev05, 2007-08-31</remarks>
        /// <remarks>Documented by Dev08, 2008-09-25</remarks>
        public static void ImportToDictionary(IDictionary dictionary, List <List <string> > data, IChapter chapter, Dictionary <Field, int> fields, BackgroundWorker worker, DateTime cardTimeStamp, bool splitSynonyms)
        {
            int    value            = 0;
            int    pos              = 0;
            string workingdirectory = Environment.CurrentDirectory;

            string[] synonymsSplitChar = splitSynonyms ? new string[] { " ,", " ;", ", ", "; ", ",", ";" } : new string[] { "\n" };             // following comment ist antiqued: "empty splitchar array would cause to split at space char -> split at newline char, which should not exist anymore in csv imported data"

            foreach (List <string> item in data)
            {
                ICard card = dictionary.Cards.AddNew();
                card.Timestamp = cardTimeStamp;
                card.Chapter   = chapter.Id;

                IMedia questionImage = null, questionSound = null, questionVideo = null, questionExampleSound = null;
                IMedia answerImage = null, answerSound = null, answerVideo = null, answerExampleSound = null;

                if (fields.ContainsKey(Field.Question) && fields[Field.Question] < item.Count)
                {
                    if (!string.IsNullOrEmpty(item[fields[Field.Question]]))
                    {
                        foreach (string word in item[fields[Field.Question]].Split(synonymsSplitChar, StringSplitOptions.RemoveEmptyEntries))
                        {
                            card.Question.AddWord(card.Question.CreateWord(word.Trim(), WordType.Word, true));
                        }
                    }
                }
                if (fields.ContainsKey(Field.QuestionDistractors) && fields[Field.QuestionDistractors] < item.Count)
                {
                    if (!string.IsNullOrEmpty(item[fields[Field.QuestionDistractors]]))
                    {
                        foreach (string word in item[fields[Field.QuestionDistractors]].Split(synonymsSplitChar, StringSplitOptions.RemoveEmptyEntries))
                        {
                            card.QuestionDistractors.AddWord(card.QuestionDistractors.CreateWord(word.Trim(), WordType.Distractor, false));
                        }
                    }
                }
                if (fields.ContainsKey(Field.QuestionImage) && fields[Field.QuestionImage] < item.Count)
                {
                    try
                    {
                        questionImage = card.CreateMedia(EMedia.Image, ExpandMediaPath(StripInvalidFileNameChars(item[fields[Field.QuestionImage]]), workingdirectory), true, true, false);
                    }
                    catch (FileNotFoundException)
                    {
                        Debug.WriteLine("A media file was not found.");
                    }
                    if (questionImage != null)
                    {
                        card.AddMedia(questionImage, Side.Question);
                    }
                }
                if (fields.ContainsKey(Field.QuestionSound) && fields[Field.QuestionSound] < item.Count)
                {
                    try
                    {
                        questionSound = card.CreateMedia(EMedia.Audio, ExpandMediaPath(StripInvalidFileNameChars(item[fields[Field.QuestionSound]]), workingdirectory), true, true, false);
                    }
                    catch (FileNotFoundException)
                    {
                        Debug.WriteLine("A media file was not found.");
                    }
                    if (questionSound != null)
                    {
                        card.AddMedia(questionSound, Side.Question);
                    }
                }
                if (fields.ContainsKey(Field.QuestionVideo) && fields[Field.QuestionVideo] < item.Count)
                {
                    try
                    {
                        questionVideo = card.CreateMedia(EMedia.Video, ExpandMediaPath(StripInvalidFileNameChars(item[fields[Field.QuestionVideo]]), workingdirectory), true, true, false);
                    }
                    catch (FileNotFoundException)
                    {
                        Debug.WriteLine("A media file was not found.");
                    }
                    if (questionVideo != null)
                    {
                        card.AddMedia(questionVideo, Side.Question);
                    }
                }
                if (fields.ContainsKey(Field.QuestionExample) && fields[Field.QuestionExample] < item.Count)
                {
                    card.QuestionExample.AddWord(card.QuestionExample.CreateWord(item[fields[Field.QuestionExample]].Trim(), WordType.Sentence, false));
                }
                if (fields.ContainsKey(Field.QuestionExampleSound) && fields[Field.QuestionExampleSound] < item.Count)
                {
                    try
                    {
                        questionExampleSound = card.CreateMedia(EMedia.Audio, ExpandMediaPath(StripInvalidFileNameChars(item[fields[Field.QuestionExampleSound]]), workingdirectory), true, false, true);
                    }
                    catch (FileNotFoundException)
                    {
                        Debug.WriteLine("A media file was not found.");
                    }
                    if (questionExampleSound != null)
                    {
                        card.AddMedia(questionExampleSound, Side.Question);
                    }
                }

                if (fields.ContainsKey(Field.Answer) && fields[Field.Answer] < item.Count)
                {
                    if (!string.IsNullOrEmpty(item[fields[Field.Answer]]))
                    {
                        foreach (string word in item[fields[Field.Answer]].Split(synonymsSplitChar, StringSplitOptions.RemoveEmptyEntries))
                        {
                            card.Answer.AddWord(card.Answer.CreateWord(word.Trim(), WordType.Word, true));
                        }
                    }
                }
                if (fields.ContainsKey(Field.AnswerDistractors) && fields[Field.AnswerDistractors] < item.Count)
                {
                    if (!string.IsNullOrEmpty(item[fields[Field.AnswerDistractors]]))
                    {
                        foreach (string word in item[fields[Field.AnswerDistractors]].Split(synonymsSplitChar, StringSplitOptions.RemoveEmptyEntries))
                        {
                            card.AnswerDistractors.AddWord(card.AnswerDistractors.CreateWord(word.Trim(), WordType.Distractor, false));
                        }
                    }
                }
                if (fields.ContainsKey(Field.AnswerImage) && fields[Field.AnswerImage] < item.Count)
                {
                    if (questionImage != null && item[fields[Field.QuestionImage]] == item[fields[Field.AnswerImage]])
                    {
                        answerImage = questionImage;
                    }
                    else
                    {
                        try
                        {
                            answerImage = card.CreateMedia(EMedia.Image, ExpandMediaPath(StripInvalidFileNameChars(item[fields[Field.AnswerImage]]), workingdirectory), true, true, false);
                        }
                        catch (FileNotFoundException)
                        {
                            Debug.WriteLine("A media file was not found.");
                        }
                    }
                    if (answerImage != null)
                    {
                        card.AddMedia(answerImage, Side.Answer);
                    }
                }
                if (fields.ContainsKey(Field.AnswerSound) && fields[Field.AnswerSound] < item.Count)
                {
                    if (questionSound != null && item[fields[Field.QuestionSound]] == item[fields[Field.AnswerSound]])
                    {
                        answerSound = questionSound;
                    }
                    else
                    {
                        try
                        {
                            answerSound = card.CreateMedia(EMedia.Audio, ExpandMediaPath(StripInvalidFileNameChars(item[fields[Field.AnswerSound]]), workingdirectory), true, true, false);
                        }
                        catch (FileNotFoundException)
                        {
                            Debug.WriteLine("A media file was not found.");
                        }
                    }
                    if (answerSound != null)
                    {
                        card.AddMedia(answerSound, Side.Answer);
                    }
                }
                if (fields.ContainsKey(Field.AnswerVideo) && fields[Field.AnswerVideo] < item.Count)
                {
                    if (questionVideo != null && item[fields[Field.QuestionVideo]] == item[fields[Field.AnswerVideo]])
                    {
                        answerVideo = questionVideo;
                    }
                    else
                    {
                        try
                        {
                            answerVideo = card.CreateMedia(EMedia.Video, ExpandMediaPath(StripInvalidFileNameChars(item[fields[Field.AnswerVideo]]), workingdirectory), true, true, false);
                        }
                        catch (FileNotFoundException)
                        {
                            Debug.WriteLine("A media file was not found.");
                        }
                    }
                    if (answerVideo != null)
                    {
                        card.AddMedia(answerVideo, Side.Answer);
                    }
                }
                if (fields.ContainsKey(Field.AnswerExample) && fields[Field.AnswerExample] < item.Count)
                {
                    card.AnswerExample.AddWord(card.AnswerExample.CreateWord(item[fields[Field.AnswerExample]].Trim(), WordType.Sentence, true));
                }
                if (fields.ContainsKey(Field.AnswerExampleSound) && fields[Field.AnswerExampleSound] < item.Count)
                {
                    if (questionExampleSound != null && item[fields[Field.QuestionExampleSound]] == item[fields[Field.AnswerExampleSound]])
                    {
                        answerExampleSound = questionExampleSound;
                    }
                    else
                    {
                        try
                        {
                            answerExampleSound = card.CreateMedia(EMedia.Audio, ExpandMediaPath(StripInvalidFileNameChars(item[fields[Field.AnswerExampleSound]]), workingdirectory), true, false, true);
                        }
                        catch (FileNotFoundException)
                        {
                            Debug.WriteLine("A media file was not found.");
                        }
                    }
                    if (answerExampleSound != null)
                    {
                        card.AddMedia(answerExampleSound, Side.Answer);
                    }
                }
                if (fields.ContainsKey(Field.Chapter) && fields[Field.Chapter] < item.Count && !string.IsNullOrEmpty(item[fields[Field.Chapter]]))
                {
                    string cardchapterstring = item[fields[Field.Chapter]].Trim();
                    if (cardchapterstring != string.Empty)
                    {
                        IChapter cardchapter = dictionary.Chapters.Find(cardchapterstring);
                        if (cardchapter == null)
                        {
                            IChapter newchapter = dictionary.Chapters.AddNew();
                            newchapter.Title = cardchapterstring;
                            card.Chapter     = newchapter.Id;
                        }
                        else
                        {
                            card.Chapter = cardchapter.Id;
                        }
                    }
                }

                pos++;
                if (worker != null)
                {
                    if (value < (int)((double)pos / (double)data.Count * 100))
                    {
                        value = (int)((double)pos / (double)data.Count * 100);
                        worker.ReportProgress(value);
                    }
                }
            }

            dictionary.Save();
        }
示例#16
0
        /// <summary>
        /// Adds the Media to the spezified card.
        /// </summary>
        /// <param name="cardID">The card ID.</param>
        /// <param name="filename">The filename.</param>
        /// <param name="type">The type.</param>
        /// <param name="side">The side.</param>
        /// <param name="active">if set to <c>true</c> the file is active.</param>
        /// <param name="standard">if set to <c>true</c> the file is the default file.</param>
        /// <param name="example">if set to <c>true</c> the file is the example.</param>
        /// <remarks>Documented by Dev05, 2007-09-03</remarks>
        public void AddMedia(int cardID, string filename, EMedia type, Side side, bool active, bool standard, bool example)
        {
            ICard card = cards.Get(cardID);

            card.AddMedia(card.CreateMedia(type, filename, active, standard, example), side);
        }
示例#17
0
        /// <summary>
        /// Loads dictionary from the old database format (ODF) and stores it to the current format.
        /// </summary>
        /// <param name="srcFile">The source database file.</param>
        /// <param name="dstFile">The destination database file.</param>
        /// <remarks>Documented by Dev03, 2007-07-26</remarks>
        public MLifter.DAL.Interfaces.IDictionary Load(string srcFile, string dstFile)
        {
            MLifter.DAL.Interfaces.IDictionary dictionary = null;
            int wbVersion;

#if !DEBUG
            try
            {
#endif
            string srcPath            = Path.GetDirectoryName(srcFile);
            _rBox_[] box_data         = new _rBox_[0];
            _rChapter_[] chapter_data = new _rChapter_[0];
            _rCards_[] cards_data     = new _rCards_[0];
            _rBoxes_[] boxes_data     = new _rBoxes_[0];
            _rBlob_[] blob_data       = new _rBlob_[0];
            _rStats_[] stats_data     = new _rStats_[0];

            string headerstr = string.Empty;
            UInt16 ssize;
            int len, rsize;

            using (FileStream DicFile = new FileStream(srcFile, FileMode.Open))
            {
                BinaryReader Dic = new BinaryReader(DicFile, System.Text.UnicodeEncoding.UTF8);
                // Check header first
                len = Dic.ReadInt32();
                if (len < 30)
                {
                    headerstr = byte2string(Dic.ReadBytes(len));
                }
                else
                {
                    headerstr = string.Empty;
                }
                // Check version byte
                wbVersion = Dic.ReadInt16();

                // Some code to correct "bugs" in previous dictionary versions
                if (wbVersion <= 0x0104)
                {
                    throw new DictionaryFormatNotSupported(wbVersion);
                }

                // Header has to be okay, and Version smaller than prog's version
                if (headerstr.Equals(m_odfFileHeaderString) && (wbVersion <= m_oldFileVersion))
                {
                    if (File.Exists(dstFile))
                    {
                        throw new DictionaryPathExistsException(dstFile);
                    }

                    IUser user = UserFactory.Create(m_loginCallback, new ConnectionStringStruct(DatabaseType.Xml, dstFile, false),
                                                    (DataAccessErrorDelegate) delegate { return; }, this);
                    dictionary = user.Open();
                    len        = Dic.ReadByte();
                    dictionary.DefaultSettings.QuestionCaption = byte2string(Dic.ReadBytes(20)).Substring(0, len);
                    len = Dic.ReadByte();
                    dictionary.DefaultSettings.AnswerCaption = byte2string(Dic.ReadBytes(20)).Substring(0, len);

                    Dic.ReadBytes(82);                    //SrcFont & DstFont
                    Dic.ReadBytes(2);                     //SrcCharSet & DstCharSet

                    Dic.ReadBoolean();                    //ReadOnly

                    ssize             = Dic.ReadUInt16();
                    dictionary.Author = byte2string(Dic.ReadBytes(ssize));

                    ssize = Dic.ReadUInt16();
                    dictionary.Description = byte2string(Dic.ReadBytes(ssize));

                    if (wbVersion >= 0x0104)
                    {
                        ssize = Dic.ReadUInt16();
                        string mediafolder = byte2string(Dic.ReadBytes(ssize)).TrimEnd(new char[] { Path.DirectorySeparatorChar });
                        if (Directory.Exists(mediafolder))
                        {
                            dictionary.MediaDirectory = mediafolder;
                        }
                    }

                    if (wbVersion >= 0x0107)
                    {
                        for (int i = 0; i < 12; i++)
                        {
                            ssize = Dic.ReadUInt16();
                            dictionary.DefaultSettings.CommentarySounds[CommentarySoundIdentifier.Create(i > 6 ? Side.Answer : Side.Question,
                                                                                                         (ECommentarySoundType)(i > 6 ? i - 6 : i))] =
                                new MLifter.DAL.XML.XmlAudio(SkinDir2RealDir(byte2string(Dic.ReadBytes(ssize)), Path.GetDirectoryName(dstFile), m_applicationPath),
                                                             new MLifter.DAL.Tools.ParentClass(user, dictionary));
                        }
                    }

                    if (wbVersion >= 0x0108)
                    {
                        Dic.ReadBytes(10);                         //Pwd
                    }
                    if (wbVersion >= 0x0109)
                    {
                        dictionary.Category = new Category((int)Dic.ReadByte(), false);
                    }
                    else
                    {
                        dictionary.Category = new Category(m_defaultCategory, true);
                    }

                    (dictionary as MLifter.DAL.XML.XmlDictionary).score = Dic.ReadInt32();
                    dictionary.HighScore = Dic.ReadInt32();

                    int queryChapter = 0;
                    rsize = Dic.ReadInt32();
                    dictionary.DefaultSettings.SelectedLearnChapters.Clear();
                    for (int i = 0; i < rsize; i++)
                    {
                        queryChapter = Math.Abs(Dic.ReadInt32());     // BUG?? what is the minus for??
                        if (queryChapter < 0)                         //chapterID starts with 1, should be zero-based
                        {
                            queryChapter++;
                        }
                        else
                        {
                            queryChapter--;
                        }

                        dictionary.DefaultSettings.SelectedLearnChapters.Add(queryChapter);
                    }

                    Dic.ReadUInt16();                       //the LastBox user property is not used anymore
                    EQueryDirection dir = (EQueryDirection)Dic.ReadByte();
                    switch (dir)
                    {
                    case EQueryDirection.Question2Answer:
                        dictionary.DefaultSettings.QueryDirections.Question2Answer = true;
                        break;

                    case EQueryDirection.Answer2Question:
                        dictionary.DefaultSettings.QueryDirections.Answer2Question = true;
                        break;

                    case EQueryDirection.Mixed:
                        dictionary.DefaultSettings.QueryDirections.Mixed = true;
                        break;
                    }

                    int queryType = Convert.ToInt32(Dic.ReadByte());
                    dictionary.DefaultSettings.QueryTypes.ImageRecognition       = ((((int)EQueryType.ImageRecognition) & queryType) > 0);
                    dictionary.DefaultSettings.QueryTypes.ListeningComprehension = ((((int)EQueryType.ListeningComprehension) & queryType) > 0);
                    dictionary.DefaultSettings.QueryTypes.MultipleChoice         = ((((int)EQueryType.MultipleChoice) & queryType) > 0);
                    dictionary.DefaultSettings.QueryTypes.Sentence = ((((int)EQueryType.Sentences) & queryType) > 0);
                    dictionary.DefaultSettings.QueryTypes.Word     = ((((int)EQueryType.Word) & queryType) > 0);

                    int queryOptions;
                    if (wbVersion >= 0x0103)
                    {
                        queryOptions = Convert.ToInt32(Dic.ReadUInt16());
                    }
                    else
                    {
                        queryOptions = Convert.ToInt32(Dic.ReadByte());
                    }

                    dictionary.DefaultSettings.CaseSensitive      = ((((int)EQueryOption.CaseSensitive) & queryOptions) > 0);
                    dictionary.DefaultSettings.EnableTimer        = ((((int)EQueryOption.CountDown) & queryOptions) > 0);
                    dictionary.DefaultSettings.ShowStatistics     = ((((int)EQueryOption.Stats) & queryOptions) > 0);
                    dictionary.DefaultSettings.ShowImages         = ((((int)EQueryOption.Images) & queryOptions) > 0);
                    dictionary.DefaultSettings.AutoplayAudio      = ((((int)EQueryOption.Sounds) & queryOptions) > 0);
                    dictionary.DefaultSettings.EnableCommentary   = ((((int)EQueryOption.Commentary) & queryOptions) > 0);
                    dictionary.DefaultSettings.CorrectOnTheFly    = ((((int)EQueryOption.Correct) & queryOptions) > 0);
                    dictionary.DefaultSettings.SkipCorrectAnswers = ((((int)EQueryOption.Skip) & queryOptions) > 0);
                    dictionary.DefaultSettings.SelfAssessment     = ((((int)EQueryOption.Self) & queryOptions) > 0);
                    dictionary.DefaultSettings.RandomPool         = ((((int)EQueryOption.RandomPool) & queryOptions) > 0);
                    dictionary.DefaultSettings.ConfirmDemote      = ((((int)EQueryOption.ConfirmDemote) & queryOptions) > 0);

                    if (wbVersion >= 0x0101)
                    {
                        EGradeSynonyms gradeS = (EGradeSynonyms)Dic.ReadByte();
                        switch (gradeS)
                        {
                        case EGradeSynonyms.AllKnown:
                            dictionary.DefaultSettings.GradeSynonyms.AllKnown = true;
                            break;

                        case EGradeSynonyms.HalfKnown:
                            dictionary.DefaultSettings.GradeSynonyms.HalfKnown = true;
                            break;

                        case EGradeSynonyms.OneKnown:
                            dictionary.DefaultSettings.GradeSynonyms.OneKnown = true;
                            break;

                        case EGradeSynonyms.FirstKnown:
                            dictionary.DefaultSettings.GradeSynonyms.FirstKnown = true;
                            break;

                        case EGradeSynonyms.Prompt:
                            dictionary.DefaultSettings.GradeSynonyms.Prompt = true;
                            break;
                        }
                    }
                    else
                    {
                        dictionary.DefaultSettings.GradeSynonyms.OneKnown = true;
                    }

                    dictionary.DefaultSettings.PoolEmptyMessageShown = Dic.ReadBoolean();
                    dictionary.DefaultSettings.UseLMStylesheets      = false;

                    ssize = Dic.ReadUInt16();
                    Dic.ReadBytes(ssize);                  //Skin
                    Dic.ReadBoolean();                     //UseSkin

                    string stripchars = String.Empty;
                    if (wbVersion >= 0x0102)
                    {
                        byte[] temp = Dic.ReadBytes(32);
                        for (int i = 0; i < 8; i++)
                        {
                            for (int j = 0; j < 8; j++)
                            {
                                if ((temp[i] & (0x0001 << j)) > 0)
                                {
                                    stripchars += (char)(i * 8 + j);
                                }
                            }
                        }
                        dictionary.DefaultSettings.StripChars = stripchars;
                    }

                    EGradeTyping gradeT = (EGradeTyping)Dic.ReadByte();
                    switch (gradeT)
                    {
                    case EGradeTyping.AllCorrect:
                        dictionary.DefaultSettings.GradeTyping.AllCorrect = true;
                        break;

                    case EGradeTyping.HalfCorrect:
                        dictionary.DefaultSettings.GradeTyping.HalfCorrect = true;
                        break;

                    case EGradeTyping.NoneCorrect:
                        dictionary.DefaultSettings.GradeTyping.NoneCorrect = true;
                        break;

                    case EGradeTyping.Prompt:
                        dictionary.DefaultSettings.GradeTyping.Prompt = true;
                        break;

                    default:
                        break;
                    }

                    if ((((int)ESnoozeMode.QuitProgram) & queryOptions) > 0)
                    {
                        dictionary.DefaultSettings.SnoozeOptions.SnoozeMode = ESnoozeMode.QuitProgram;
                    }
                    if ((((int)ESnoozeMode.SendToTray) & queryOptions) > 0)
                    {
                        dictionary.DefaultSettings.SnoozeOptions.SnoozeMode = ESnoozeMode.SendToTray;
                    }

                    if (!ReportProgressUpdate(5))
                    {
                        return(null);
                    }

                    if (wbVersion >= 0x0103)
                    {
                        int snoozeTime     = Convert.ToInt32(Dic.ReadByte());
                        int snoozeRights   = Convert.ToInt32(Dic.ReadByte());
                        int snoozeCards    = Convert.ToInt32(Dic.ReadByte());
                        int snoozeTimeLow  = Convert.ToInt32(Dic.ReadByte());
                        int snoozeTimeHigh = Convert.ToInt32(Dic.ReadByte());
                        if ((((int)ESnoozeMode.Time) & queryType) > 0)
                        {
                            dictionary.DefaultSettings.SnoozeOptions.EnableTime(snoozeTime);
                        }
                        if ((((int)ESnoozeMode.Rights) & queryType) > 0)
                        {
                            dictionary.DefaultSettings.SnoozeOptions.EnableRights(snoozeRights);
                        }
                        if ((((int)ESnoozeMode.Cards) & queryType) > 0)
                        {
                            dictionary.DefaultSettings.SnoozeOptions.EnableCards(snoozeCards);
                        }
                        dictionary.DefaultSettings.SnoozeOptions.SetSnoozeTimes(snoozeTimeLow, snoozeTimeHigh);
                    }
                    //box_data -> user
                    rsize    = Dic.ReadInt32();
                    box_data = (_rBox_[])SetLength(box_data, rsize);
                    for (int i = 0; i < box_data.Length; i++)
                    {
                        box_data[i]       = new _rBox_();
                        box_data[i].First = Dic.ReadInt32();
                        Dic.ReadInt32();                         // box_data[i].Last

                        if (i < box_data.Length - 2)
                        {
                            dictionary.Boxes.Box[i].MaximalSize = Dic.ReadInt32();
                        }
                        else
                        {
                            Dic.ReadInt32();                             //MaxLen for the last two boxes - not needed
                        }

                        if (wbVersion > 0x0106)
                        {
                            Dic.ReadInt32();                             // box_data[i].Len
                        }
                    }
                    // end of user -----------------------------------------------------------------

                    if (!ReportProgressUpdate(10))
                    {
                        return(null);
                    }

                    //chapter_data
                    rsize        = Dic.ReadInt32();
                    chapter_data = (_rChapter_[])SetLength(chapter_data, rsize);
                    for (int i = 0; i < chapter_data.Length; i++)
                    {
                        chapter_data[i] = new _rChapter_();
                        Dic.ReadUInt16();                         //ID
                        Dic.ReadUInt16();                         // SubID
                        len = Dic.ReadByte();
                        chapter_data[i].Title = byte2string(Dic.ReadBytes(30)).Substring(0, len);
                        len = Dic.ReadByte();
                        chapter_data[i].Description = byte2string(Dic.ReadBytes(256)).Substring(0, len);
                    }

                    if (!ReportProgressUpdate(15))
                    {
                        return(null);
                    }

                    //cards_data
                    rsize      = Dic.ReadInt32();
                    cards_data = (_rCards_[])SetLength(cards_data, rsize);
                    for (int i = 0; i < cards_data.Length; i++)
                    {
                        cards_data[i] = new _rCards_();
                        ssize         = Dic.ReadUInt16();
                        cards_data[i].Src.SpecialImportFormat = byte2string(Dic.ReadBytes(ssize));
                        ssize = Dic.ReadUInt16();
                        cards_data[i].Dst.SpecialImportFormat = byte2string(Dic.ReadBytes(ssize));
                        ssize = Dic.ReadUInt16();
                        cards_data[i].SentSrc = byte2string(Dic.ReadBytes(ssize));
                        ssize = Dic.ReadUInt16();
                        cards_data[i].SentDst   = byte2string(Dic.ReadBytes(ssize));
                        cards_data[i].ChapterID = Dic.ReadUInt16() - 1;                         //chapterID starts with 1, should be zero-based
                        cards_data[i].CardParts = Dic.ReadByte();
                        if (wbVersion >= 0x0107)
                        {
                            Dic.ReadByte();                             // Probability
                        }
                    }

                    if (!ReportProgressUpdate(20))
                    {
                        return(null);
                    }

                    //boxes_data
                    rsize      = Dic.ReadInt32();
                    boxes_data = (_rBoxes_[])SetLength(boxes_data, rsize);
                    for (int i = 0; i < boxes_data.Length; i++)
                    {
                        boxes_data[i]       = new _rBoxes_();
                        boxes_data[i].BoxID = Dic.ReadByte();
                        Dic.ReadBytes(3);                         //TODO BUG ?
                        boxes_data[i].CardID = Dic.ReadInt32();
                        boxes_data[i].Prior  = Dic.ReadInt32();
                        boxes_data[i].Next   = Dic.ReadInt32();
                    }

                    if (!ReportProgressUpdate(25))
                    {
                        return(null);
                    }

                    //blob_data
                    rsize     = Dic.ReadInt32();
                    blob_data = (_rBlob_[])SetLength(blob_data, rsize);
                    for (int i = 0; i < blob_data.Length; i++)
                    {
                        blob_data[i]        = new _rBlob_();
                        blob_data[i].SrcDst = (TBlobType)Dic.ReadByte();
                        len = Dic.ReadByte();
                        string tstr = byte2string(Dic.ReadBytes(101));
                        blob_data[i].Link = tstr.Substring(0, len);
                        blob_data[i].Link = blob_data[i].Link.Replace('/', '\\');                         // repair work
                        blob_data[i].Link = blob_data[i].Link.Replace("\\\\", "\\");                      // repair work
                        Dic.ReadByte();
                        blob_data[i].CardID = Dic.ReadInt32();
                    }

                    if (!ReportProgressUpdate(30))
                    {
                        return(null);
                    }

                    //stats_data
                    rsize      = Dic.ReadInt32();
                    stats_data = (_rStats_[])SetLength(stats_data, rsize);
                    for (int i = 0; i < stats_data.Length; i++)
                    {
                        stats_data[i]        = new _rStats_(m_nrBox);
                        stats_data[i].SStart = new System.DateTime(1899, 12, 30, 0, 0, 0);                       // startdate in delphi
                        stats_data[i].SStart = stats_data[i].SStart.AddDays(Dic.ReadDouble());
                        stats_data[i].SEnd   = new System.DateTime(1899, 12, 30, 0, 0, 0);                       // startdate in delphi
                        stats_data[i].SEnd   = stats_data[i].SEnd.AddDays(Dic.ReadDouble());
                        stats_data[i].Right  = Dic.ReadInt32();
                        stats_data[i].Wrong  = Dic.ReadInt32();
                        for (int j = 0; j < m_nrBox; j++)
                        {
                            stats_data[i].Boxes[j] = Dic.ReadInt32();
                        }
                    }

                    if (!ReportProgressUpdate(35))
                    {
                        return(null);
                    }

                    //chapters
                    for (int i = 0; i < chapter_data.Length; i++)
                    {
                        IChapter chapter = dictionary.Chapters.AddNew();
                        //chapter.Id = i; //Interface change
                        chapter.Title       = chapter_data[i].Title;
                        chapter.Description = chapter_data[i].Description;
                    }

                    if (!ReportProgressUpdate(40))
                    {
                        return(null);
                    }

                    //cards
                    for (int i = 0; i < cards_data.Length; i++)
                    {
                        if ((i % 10) == 0)
                        {
                            int progress = (int)Math.Floor(35.0 + ((90.0 - 35.0) * (i + 1) / cards_data.Length));
                            if (!ReportProgressUpdate(progress))
                            {
                                return(null);
                            }
                        }
                        ICard card = dictionary.Cards.AddNew();
                        //card.Id = i;  //Interface change
                        StringList words = new StringList();
                        words.CommaText = cards_data[i].Src.CommaText;
                        for (int k = 0; k < words.Count; k++)
                        {
                            IWord word = card.Question.CreateWord(words[k], WordType.Word, (k == 0));
                            card.Question.AddWord(word);
                        }
                        card.QuestionExample.AddWord(card.QuestionExample.CreateWord(cards_data[i].SentSrc, WordType.Sentence, false));
                        words.CommaText = cards_data[i].Dst.CommaText;
                        for (int k = 0; k < words.Count; k++)
                        {
                            IWord word = card.Answer.CreateWord(words[k], WordType.Word, (k == 0));
                            card.Answer.AddWord(word);
                        }
                        card.AnswerExample.AddWord(card.AnswerExample.CreateWord(cards_data[i].SentDst, WordType.Sentence, false));
                        card.Chapter   = cards_data[i].ChapterID;
                        card.Box       = 0;
                        card.Timestamp = DateTime.Now;

                        for (int j = 0; j < blob_data.Length; j++)
                        {
                            if (blob_data[j].CardID == i)
                            {
                                if (File.Exists(Path.Combine(srcPath, blob_data[j].Link)))
                                {
                                    blob_data[j].Link = Path.Combine(srcPath, blob_data[j].Link);
                                    if (blob_data[j].SrcDst.ToString().Equals("image"))
                                    {
                                        IMedia media = card.CreateMedia(EMedia.Image, blob_data[j].Link, true, false, false);
                                        card.AddMedia(media, Side.Question);
                                        card.AddMedia(media, Side.Answer);
                                    }
                                    else
                                    {
                                        IMedia media = null;
                                        Side   side  = Side.Question;
                                        switch (blob_data[j].SrcDst.ToString())
                                        {
                                        case "questionaudio":
                                            media = card.CreateMedia(EMedia.Audio, blob_data[j].Link, true, true, false);
                                            side  = Side.Question;
                                            break;

                                        case "questionexampleaudio":
                                            media = card.CreateMedia(EMedia.Audio, blob_data[j].Link, true, false, true);
                                            side  = Side.Question;
                                            break;

                                        case "questionvideo":
                                            media = card.CreateMedia(EMedia.Video, blob_data[j].Link, true, false, false);
                                            side  = Side.Question;
                                            break;

                                        case "questionimage":
                                            media = card.CreateMedia(EMedia.Image, blob_data[j].Link, true, false, false);
                                            side  = Side.Question;
                                            break;

                                        case "answeraudio":
                                            media = card.CreateMedia(EMedia.Audio, blob_data[j].Link, true, true, false);
                                            side  = Side.Answer;
                                            break;

                                        case "answerexampleaudio":
                                            media = card.CreateMedia(EMedia.Audio, blob_data[j].Link, true, false, true);
                                            side  = Side.Answer;
                                            break;

                                        case "answervideo":
                                            media = card.CreateMedia(EMedia.Video, blob_data[j].Link, true, false, false);
                                            side  = Side.Answer;
                                            break;

                                        case "answerimage":
                                            media = card.CreateMedia(EMedia.Image, blob_data[j].Link, true, false, false);
                                            side  = Side.Answer;
                                            break;

                                        case "unusedmedia":
                                        default:
                                            try
                                            {
                                                EMedia mType = Helper.GetMediaType(blob_data[j].Link);
                                                if (mType == EMedia.Unknown)
                                                {
                                                    media = card.CreateMedia(mType, blob_data[j].Link, false, false, false);
                                                    side  = Side.Question;                                                               //doesn't matter
                                                }
                                            }
                                            catch { }
                                            break;
                                        }
                                        if (media != null)
                                        {
                                            card.AddMedia(media, side);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (!ReportProgressUpdate(95))
                    {
                        return(null);
                    }

                    //stats
                    for (int i = 0; i < stats_data.Length; i++)
                    {
                        IStatistic stat = new MLifter.DAL.XML.XmlStatistic(dictionary as MLifter.DAL.XML.XmlDictionary, i, true);
                        dictionary.Statistics.Add(stat);
                        stat.StartTimestamp = stats_data[i].SStart;
                        stat.EndTimestamp   = stats_data[i].SEnd;
                        stat.Right          = stats_data[i].Right;
                        stat.Wrong          = stats_data[i].Wrong;
                        stat.Boxes.Clear();
                        for (int j = 0; j < stats_data[i].Boxes.Length; j++)
                        {
                            stat.Boxes.Add(stats_data[i].Boxes[j]);
                        }
                    }

                    DateTime start_of_year      = new DateTime(m_releaseYear, 1, 1);
                    int      additional_seconds = 1;

                    for (int i = box_data.Length - 1; i >= 0; i--)
                    {
                        int exitCounter = 0;
                        for (int j = box_data[i].First; j != (-1); j = boxes_data[j].Next)
                        {
                            try
                            {
                                ICard card = dictionary.Cards.Get(boxes_data[j].CardID);
                                card.Box       = boxes_data[j].BoxID;
                                card.Timestamp = start_of_year.AddSeconds(additional_seconds++).ToUniversalTime();
                            }
                            catch { }
                            //boxes_data seems to be a linked list which sometimes may be broken - this is the emergency exit
                            if (exitCounter++ > dictionary.Cards.Count)
                            {
                                break;
                            }
                        }
                    }

                    dictionary.Save();
                }
                else
                {
                    throw new InvalidImportFormatException(dstFile);
                }

                Dic.Close();
            }
#if !DEBUG
        }

        catch (DictionaryPathExistsException ex)
        {
            throw ex;
        }
        catch (DictionaryFormatNotSupported ex)
        {
            throw ex;
        }
        catch (InvalidImportFormatException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
#endif
            return(dictionary);
        }