Esempio n. 1
0
        private static string GetReaderSettings(CollectionSettings currentCollectionSettings)
        {
            var settingsPath = DecodableReaderTool.GetReaderToolsSettingsFilePath(currentCollectionSettings);

            // if file exists, return current settings
            if (RobustFile.Exists(settingsPath))
            {
                var result = RobustFile.ReadAllText(settingsPath, Encoding.UTF8);
                if (!string.IsNullOrWhiteSpace(result))
                {
                    return(result);
                }
            }

            // file does not exist, so make a new one
            // The literal string here defines our default reader settings for a collection.
            var settingsString = "{\"letters\":\"a b c d e f g h i j k l m n o p q r s t u v w x y z\","
                                 + "\"moreWords\":\"\","
                                 + "\"stages\":[{\"letters\":\"\",\"sightWords\":\"\"}],"
                                 + "\"levels\":[{\"maxWordsPerSentence\":2,\"maxWordsPerPage\":2,\"maxWordsPerBook\":20,\"maxUniqueWordsPerBook\":0,\"thingsToRemember\":[]},"
                                 + "{\"maxWordsPerSentence\":5,\"maxWordsPerPage\":5,\"maxWordsPerBook\":23,\"maxUniqueWordsPerBook\":8,\"thingsToRemember\":[]},"
                                 + "{\"maxWordsPerSentence\":7,\"maxWordsPerPage\":10,\"maxWordsPerBook\":72,\"maxUniqueWordsPerBook\":16,\"thingsToRemember\":[]},"
                                 + "{\"maxWordsPerSentence\":8,\"maxWordsPerPage\":18,\"maxWordsPerBook\":206,\"maxUniqueWordsPerBook\":32,\"thingsToRemember\":[]},"
                                 + "{\"maxWordsPerSentence\":12,\"maxWordsPerPage\":25,\"maxWordsPerBook\":500,\"maxUniqueWordsPerBook\":64,\"thingsToRemember\":[]},"
                                 + "{\"maxWordsPerSentence\":20,\"maxWordsPerPage\":50,\"maxWordsPerBook\":1000,\"maxUniqueWordsPerBook\":0,\"thingsToRemember\":[]}]}";

            RobustFile.WriteAllText(settingsPath, settingsString);

            return(settingsString);
        }
Esempio n. 2
0
        public void AttemptMissingImageReplacements(string pathToFolderOfReplacementImages = null)
        {
            using (var dlg = new ProgressDialogBackground())
            {
                dlg.ShowAndDoWork((progress, args) => DoChecksOfAllBooksBackgroundWork(dlg, pathToFolderOfReplacementImages));
                if (dlg.Progress.ErrorEncountered || dlg.Progress.WarningsEncountered)
                {
                    MessageBox.Show("There were some problems. Bloom will now open a log of the attempt to replace missing images.");
                }
                else
                {
                    MessageBox.Show("There are no more missing images. Bloom will now open a log of what it did.");
                }

                var path = Path.GetTempFileName() + ".txt";
                RobustFile.WriteAllText(path, dlg.ProgressString.Text);
                try
                {
                    PathUtilities.OpenFileInApplication(path);
                }
                catch (System.OutOfMemoryException)
                {
                    // This has happened at least once.  See https://silbloom.myjetbrains.com/youtrack/issue/BL-3431.
                    MessageBox.Show("Bloom ran out of memory trying to open the log.  You should quit and restart the program.  (Your books should all be okay.)");
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Returns 'true' unless we find we can't run Bloom, in which case it reports the condition and the caller should exit Bloom.
        /// In Oct of 2017, a Windows update to Defender on some machines set Protections on certain
        /// basic folders, like MyDocuments! This resulted in throwing an exception any time Bloom tried
        /// to write out CollectionSettings files!
        /// </summary>
        /// <param name="folderToCheck">An optional folder to test for this problem.</param>
        /// <returns></returns>
        public static bool CanWriteToDirectory(string folderToCheck = null)
        {
            if (!Platform.IsWindows)
            {
                return(true);
            }
            string testPath;

            testPath = !string.IsNullOrEmpty(folderToCheck) ? Path.Combine(folderToCheck, TestFileName) : GetMruProjectTestPath;
            try
            {
                RobustFile.WriteAllText(testPath, "test contents");
            }
            catch (Exception exc)
            {
                // Creating a previously non-existent file under these conditions just gives a WinIOError, "could not find file".
                ReportDefenderProblem(exc, Path.GetDirectoryName(testPath));
                return(false);
            }
            finally
            {
                Cleanup(testPath);
            }
            return(true);
        }
        private void SetupCssTests()
        {
            // create collection directory
            Directory.CreateDirectory(_collectionPath);

            // settingsCollectionStyles.css
            var cssFile = Path.Combine(_collectionPath, "settingsCollectionStyles.css");

            RobustFile.WriteAllText(cssFile, @".settingsCollectionStylesCssTest{}");

            // customCollectionStyles.css
            cssFile = Path.Combine(_collectionPath, "customCollectionStyles.css");
            RobustFile.WriteAllText(cssFile, @".customCollectionStylesCssTest{}");

            // create book directory
            var bookPath = Path.Combine(_collectionPath, "TestBook");

            Directory.CreateDirectory(bookPath);

            cssFile = Path.Combine(bookPath, "ForUnitTest-XMatter.css");
            RobustFile.WriteAllText(cssFile, @"This is the one in the book");

            // Factory-XMatter.css
            cssFile = Path.Combine(bookPath, "Factory-XMatter.css");
            RobustFile.WriteAllText(cssFile, @".factoryXmatterCssTest{}");

            // customBookStyles.css
            cssFile = Path.Combine(bookPath, "customBookStyles.css");
            RobustFile.WriteAllText(cssFile, @".customBookStylesCssTest{}");

            // miscStyles.css - a file name not distributed with or created by Bloom
            cssFile = Path.Combine(bookPath, "miscStyles.css");
            RobustFile.WriteAllText(cssFile, @".miscStylesCssTest{}");
        }
Esempio n. 5
0
        /// <summary>
        /// API Handler when the Auto Segment button is clicked
        ///
        /// Replies with the text read (with orthography conversion applied) if eSpeak completed successfully, or "' if there was an error.
        /// </summary>
        public void ESpeakPreview(ApiRequest request)
        {
            Logger.WriteEvent("AudioSegmentationApi.ESpeakPreview(): ESpeakPreview started.");

            // Parse the JSON containing the text segmentation data.
            string json = request.RequiredPostJson();
            ESpeakPreviewRequest requestParameters = JsonConvert.DeserializeObject <ESpeakPreviewRequest>(json);

            string requestedLangCode = requestParameters.lang;
            string langCode          = GetBestSupportedLanguage(requestedLangCode);

            Logger.WriteEvent($"AudioSegmentationApi.ESpeakPreview(): langCode={langCode ?? "null"}");

            string text = requestParameters.text;

            text = SanitizeTextForESpeakPreview(text);

            string collectionPath = _bookSelection.CurrentSelection.CollectionSettings.FolderPath;
            string orthographyConversionMappingPath = Path.Combine(collectionPath, $"convert_{requestedLangCode}_to_{langCode}.txt");

            if (RobustFile.Exists(orthographyConversionMappingPath))
            {
                text = ApplyOrthographyConversion(text, orthographyConversionMappingPath);
            }

            // Even though you theoretically can pass the text through on the command line, it's better to write it to file.
            // The way the command line handles non-ASCII characters is not guaranteed to be the same as when reading from file.
            // It's more straightforward to just read/write it from file.
            // This causes the audio to match the audio that Aeneas will hear when it calls its eSpeak dependency.
            //   (Well, actually it was difficult to verify the exact audio that Aeneas hears, but for -v el "άλφα", verified reading from file caused audio duration to match, but passing on command line caused discrepancy in audio duration)
            string textToSpeakFullPath = Path.GetTempFileName();

            RobustFile.WriteAllText(textToSpeakFullPath, text, Encoding.UTF8);

            // No need to wait for espeak before responding.
            var response = new ESpeakPreviewResponse()
            {
                text     = text,
                lang     = langCode,
                filePath = RobustFile.Exists(orthographyConversionMappingPath) ? Path.GetFileName(orthographyConversionMappingPath) : ""
            };
            string responseJson = JsonConvert.SerializeObject(response);

            request.ReplyWithJson(responseJson);

            string stdout;
            string command = $"espeak -v {langCode} -f \"{textToSpeakFullPath}\"";
            bool   success = !DoesCommandCauseError(command, out stdout);

            RobustFile.Delete(textToSpeakFullPath);
            Logger.WriteEvent("AudioSegmentationApi.ESpeakPreview() Completed with success = " + success);
            if (!success)
            {
                var message = L10NSharp.LocalizationManager.GetString(
                    "EditTab.Toolbox.TalkingBookTool.ESpeakPreview.Error",
                    "eSpeak failed.",
                    "This text is shown if an error occurred while running eSpeak. eSpeak is a piece of software that this program uses to do text-to-speech (have the computer read text out loud).");
                NonFatalProblem.Report(ModalIf.None, PassiveIf.All, message, null, null, false);                        // toast without allowing error report.
            }
        }
        public void CreateBookOnDiskFromShell_OriginalCC0_BookIsCC0()
        {
            var originalSource = Path.Combine(BloomFileLocator.SampleShellsDirectory, "Vaccinations");

            using (var tempFolder = new TemporaryFolder("VaccinationsCc0"))
                using (var destFolder = new TemporaryFolder("Vaccinations_BookIsCC0"))
                {
                    var source = Path.Combine(tempFolder.Path, "Vaccinations");
                    if (Directory.Exists(source))
                    {
                        Directory.Delete(source, true);
                    }
                    DirectoryUtilities.CopyDirectory(originalSource, tempFolder.Path);
                    var htmPath = Path.Combine(source, "Vaccinations.htm");
                    var content = RobustFile.ReadAllText(htmPath);
                    // insert cc0 stuff in data div
                    var patched = content.Replace("http://creativecommons.org/licenses/by-nc/3.0/", "http://creativecommons.org/publicdomain/zero/1.0/");
                    RobustFile.WriteAllText(htmPath, patched);
                    var bookPath       = GetPathToHtml(_starter.CreateBookOnDiskFromTemplate(source, destFolder.Path));
                    var assertThatBook = AssertThatXmlIn.HtmlFile(bookPath);
                    // For some reason Vaccinations specifies licenseUrl in three ways (no lang, lang="en", lang="*").
                    // We don't want any of them messed with.
                    assertThatBook.HasSpecifiedNumberOfMatchesForXpath("//div[@data-book='licenseUrl' and contains(text(), '/zero/1.0')]", 3);
                }
        }
        public void ForgetChanges_HtmlChange_UndoesIt()
        {
            using (var collectionFolder =
                       new TemporaryFolder("ForgetChanges_HtmlChange_UndoesIt_Collection"))
            {
                using (var repoFolder =
                           new TemporaryFolder("ForgetChanges_HtmlChange_UndoesIt_Repo"))
                {
                    var mockTcManager = new Mock <ITeamCollectionManager>();
                    var tc            = new TestFolderTeamCollection(mockTcManager.Object, collectionFolder.FolderPath,
                                                                     repoFolder.FolderPath);
                    var bookFolderPath = Path.Combine(collectionFolder.FolderPath, "My book");
                    Directory.CreateDirectory(bookFolderPath);
                    var bookPath = Path.Combine(bookFolderPath, "My book.htm");
                    RobustFile.WriteAllText(bookPath, "This is just a dummy");
                    tc.PutBook(bookFolderPath);
                    tc.AttemptLock("My book", "*****@*****.**");
                    RobustFile.WriteAllText(bookPath, "This is the edited content");

                    var changedFolders = tc.ForgetChangesCheckin("My book");

                    Assert.That(changedFolders.Count, Is.EqualTo(0));
                    Assert.That(RobustFile.ReadAllText(bookPath), Is.EqualTo("This is just a dummy"));
                    Assert.That(tc.GetStatus("My book").lockedBy, Is.Null);
                }
            }
        }
        public void ForgetChanges_RenameAndReplace_UndoesAndMoves()
        {
            using (var collectionFolder =
                       new TemporaryFolder("ForgetChanges_HtmlChangeAndRename_UndoesBoth_Collection"))
            {
                using (var repoFolder =
                           new TemporaryFolder("ForgetChanges_HtmlChangeAndRename_UndoesBoth_Repo"))
                {
                    var tc = MakeAndRenameBook(collectionFolder, repoFolder, out var bookPath,
                                               out var newBookFolderPath);
                    Directory.CreateDirectory(Path.GetDirectoryName(bookPath));
                    RobustFile.WriteAllText(bookPath, "This is some other book created after the rename");

                    var changedFolders = tc.ForgetChangesCheckin("Renamed book");

                    Assert.That(RobustFile.Exists(bookPath));
                    Assert.That(Directory.Exists(newBookFolderPath), Is.False);
                    Assert.That(RobustFile.ReadAllText(bookPath), Is.EqualTo("This is just a dummy"));
                    Assert.That(tc.GetStatus("My book").lockedBy, Is.Null);
                    Assert.That(changedFolders.Count, Is.EqualTo(3));
                    var movedFolder   = changedFolders[2];
                    var movedBookPath = Path.Combine(movedFolder,
                                                     Path.ChangeExtension(Path.GetFileName(movedFolder), "htm"));
                    Assert.That(RobustFile.ReadAllText(movedBookPath),
                                Is.EqualTo("This is some other book created after the rename"));
                }
            }
        }
        public void HandleModifiedFile_NoConflictBookChangedNotCheckedOut_RaisesCheckedOutByNoneAndNewStuffMessage()
        {
            // Simulate (sort of) that a book was just overwritten with the following new contents,
            // including that book.status does not indicate it's checked out
            const string bookFolderName = "My book";
            var          bookBuilder    = new BookFolderBuilder()
                                          .WithRootFolder(_collectionFolder.FolderPath)
                                          .WithTitle(bookFolderName)
                                          .WithHtm("This is pretending to be new content from remote")
                                          .Build();

            string bookFolderPath = bookBuilder.BuiltBookFolderPath;
            var    status         = _collection.PutBook(bookFolderPath);

            RobustFile.WriteAllText(bookBuilder.BuiltBookHtmPath, "This is pretending to be old content");
            // pretending this is what it was before the change.
            _collection.WriteLocalStatus(bookFolderName, status.WithChecksum(Bloom.TeamCollection.TeamCollection.MakeChecksum(bookFolderPath)));
            var prevMessages = _tcLog.Messages.Count;

            // System Under Test //
            _collection.HandleModifiedFile(new BookRepoChangeEventArgs()
            {
                BookFileName = $"{bookFolderName}.bloom"
            });

            // Verification
            var eventArgs = (BookStatusChangeEventArgs)_mockTcManager.Invocations[0].Arguments[0];

            Assert.That(eventArgs.CheckedOutByWhom, Is.EqualTo(CheckedOutBy.None));

            Assert.That(_tcLog.Messages[prevMessages].MessageType, Is.EqualTo(MessageAndMilestoneType.NewStuff));
        }
Esempio n. 10
0
        private void Save()
        {
            // We're checking this because the deserialization routine calls the property setters which triggers a save. We don't
            // want to save while loading.
            if (_loading)
            {
                return;
            }
            var prefs = JsonConvert.SerializeObject(this);

            Debug.Assert(!string.IsNullOrWhiteSpace(prefs));

            try
            {
                if (!string.IsNullOrWhiteSpace(prefs))
                {
                    var temp = new TempFileForSafeWriting(_filePath);
                    RobustFile.WriteAllText(temp.TempFilePath, prefs);
                    temp.WriteWasSuccessful();
                }
            }
            catch (Exception error)
            {
                //For https://silbloom.myjetbrains.com/youtrack/issue/BL-3222  we did a real fix for 3.6.
                //But this will cover us for future errors here, which are not worth stopping the user from doing work.
                NonFatalProblem.Report(ModalIf.Alpha, PassiveIf.All, "Problem saving book preferences", "book.userprefs could not be saved to " + _filePath, error);
            }
        }
Esempio n. 11
0
        private void SaveSettingsCollectionStylesCss()
        {
            string path = FolderPath.CombineForPath("settingsCollectionStyles.css");

            try
            {
                var sb = new StringBuilder();
                sb.AppendLine("/* These styles are controlled by the Settings dialog box in Bloom. */");
                sb.AppendLine("/* They many be over-ridden by rules in customCollectionStyles.css or customBookStyles.css */");
                AddSelectorCssRule(sb, "BODY", GetDefaultFontName(), false, 0, false);
                // note: css pseudo elements  cannot have a @lang attribute. So this is needed to show page numbers in scripts
                // not covered by Andika New Basic.
                AddSelectorCssRule(sb, ".numberedPage::after", DefaultLanguage1FontName, IsLanguage1Rtl, Language1LineHeight, Language1BreaksLinesOnlyAtSpaces);
                AddSelectorCssRule(sb, "[lang='" + Language1Iso639Code + "']", DefaultLanguage1FontName, IsLanguage1Rtl, Language1LineHeight, Language1BreaksLinesOnlyAtSpaces);
                AddSelectorCssRule(sb, "[lang='" + Language2Iso639Code + "']", DefaultLanguage2FontName, IsLanguage2Rtl, Language2LineHeight, Language2BreaksLinesOnlyAtSpaces);
                if (!string.IsNullOrEmpty(Language3Iso639Code))
                {
                    AddSelectorCssRule(sb, "[lang='" + Language3Iso639Code + "']", DefaultLanguage3FontName, IsLanguage3Rtl, Language3LineHeight, Language3BreaksLinesOnlyAtSpaces);
                }
                RobustFile.WriteAllText(path, sb.ToString());
            }
            catch (Exception error)
            {
                ErrorReport.NotifyUserOfProblem(error, "Bloom was unable to update this file: {0}", path);
            }
        }
Esempio n. 12
0
        public void MakeBloomPack_DoesntIncludeCorruptOrBakFiles()
        {
            var          srcBookPath    = MakeBook();
            const string excludedFile1  = BookStorage.PrefixForCorruptHtmFiles + ".htm";
            const string excludedFile2  = BookStorage.PrefixForCorruptHtmFiles + "2.htm";
            string       excludedBackup = Path.GetFileName(srcBookPath) + ".bak";

            RobustFile.WriteAllText(Path.Combine(srcBookPath, excludedFile1), "rubbish");
            RobustFile.WriteAllText(Path.Combine(srcBookPath, excludedFile2), "rubbish");
            RobustFile.WriteAllText(Path.Combine(srcBookPath, excludedBackup), "rubbish");
            var bloomPackName = Path.Combine(_folder.Path, "testPack.BloomPack");

            // Imitate LibraryModel.MakeBloomPack() without the user interaction
            MakeTestBloomPack(bloomPackName, false);

            // Don't do anything with the zip file except read in the filenames
            var actualFiles = GetActualFilenamesFromZipfile(bloomPackName);

            // +1 for collection-level css file, -3 for corrupt and .bak files, so the count is -2
            Assert.That(actualFiles.Count, Is.EqualTo(Directory.GetFiles(srcBookPath).Count() - 2));

            foreach (var filePath in actualFiles)
            {
                Assert.IsFalse(Equals(Path.GetFileName(filePath), excludedFile1));
                Assert.IsFalse(Equals(Path.GetFileName(filePath), excludedFile2));
                Assert.IsFalse(Equals(Path.GetFileName(filePath), excludedBackup));
            }
        }
Esempio n. 13
0
        public void DeletedBook_RaisesDeleteRepoBookFileEvent()
        {
            var bloomBookPath = Path.Combine(_repoFolder.FolderPath, "Books", "put book to delete.bloom");

            // Don't use PutBook here...changing the file immediately after putting it won't work,
            // because of the code that tries to prevent notifications of our own checkins.
            RobustFile.WriteAllText(bloomBookPath, @"This is original");             // no, not a zip at all

            var deletedBookName = "";

            _collection.StartMonitoring();
            ManualResetEvent bookDeletedRaised = new ManualResetEvent(false);
            EventHandler <DeleteRepoBookFileEventArgs> monitorFunction = (sender, args) =>
            {
                deletedBookName = args.BookFileName;
                bookDeletedRaised.Set();
            };

            _collection.DeleteRepoBookFile += monitorFunction;

            // sut (at least, triggers it and waits for it)
            RobustFile.Delete(bloomBookPath);

            var waitSucceeded = bookDeletedRaised.WaitOne(1000);

            // To avoid messing up other tests, clean up before asserting.
            _collection.DeleteRepoBookFile -= monitorFunction;
            _collection.StopMonitoring();

            Assert.That(waitSucceeded, "book deleted was not raised");
            Assert.That(deletedBookName, Is.EqualTo("put book to delete.bloom"));
        }
Esempio n. 14
0
        /// <summary>
        /// Saves off the library part to disk, stores the rest
        /// </summary>
        /// <param name="newDataString"></param>
        public void CollectJsonData(string newDataString)
        {
            if (string.IsNullOrEmpty(newDataString))
            {
                LocalData = "";
                return;
            }
            dynamic newData     = DynamicJson.Parse(newDataString);
            dynamic libraryData = null;

            if (newData.IsDefined("library"))
            {
                libraryData = newData.library;                 //a couple RuntimeBinderException errors are normal here, just keep going, it eventually gets past it.
            }
            //Now in LocalData, we want to save everything that isn't library data
            newData.Delete("library");
            LocalData = newData.ToString();
            if (libraryData == null)
            {
                return;                 //no library data in there, so we don't have anything to merge/save
            }
            var existingDataString = GetLibraryData();

            if (!string.IsNullOrEmpty(existingDataString))
            {
                DynamicJson existingData = DynamicJson.Parse(existingDataString);
                if (existingData.GetDynamicMemberNames().Contains("library"))
                {
                    libraryData = MergeJsonData(DynamicJson.Parse(existingDataString).library.ToString(), libraryData.ToString());
                }
            }

            RobustFile.WriteAllText(PathToLibraryJson, libraryData.ToString());
        }
Esempio n. 15
0
        public void BulkPublishBloomPubSettings_GivenBulkPublishSettingsInXml_LoadsProperly()
        {
            var collectionName         = "loadBulkPublishSettingsTest";
            var collectionSettingsPath = Path.Combine(_folder.Path, $"{collectionName}.bloomCollection");

            if (RobustFile.Exists(collectionSettingsPath))
            {
                RobustFile.Delete(collectionSettingsPath);
            }

            string fileContents = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Collection version=""0.2"">
  <BulkPublishBloomPubSettings>
    <MakeBookshelfFile>False</MakeBookshelfFile>
    <MakeBloomBundle>False</MakeBloomBundle>
    <BookshelfColor>#FF0000</BookshelfColor>
    <DistributionTag>distTag</DistributionTag>
    <BookshelfLabel>bookshelfLabel</BookshelfLabel>
  </BulkPublishBloomPubSettings>
</Collection>";

            RobustFile.WriteAllText(collectionSettingsPath, fileContents);

            // System under test
            var collectionSettings = new CollectionSettings(collectionSettingsPath);

            // Verification
            var bulkPublishSettings = collectionSettings.BulkPublishBloomPubSettings;

            Assert.That(bulkPublishSettings.makeBookshelfFile, Is.EqualTo(false), "makeBookshelfFile");
            Assert.That(bulkPublishSettings.makeBloomBundle, Is.EqualTo(false), "makeBloomBundle");
            Assert.That(bulkPublishSettings.bookshelfColor, Is.EqualTo("#FF0000"));
            Assert.That(bulkPublishSettings.distributionTag, Is.EqualTo("distTag"));
            Assert.That(bulkPublishSettings.bookshelfLabel, Is.EqualTo("bookshelfLabel"));
        }
Esempio n. 16
0
        public static TempFile CreateHtm5FromXml(XmlNode dom)
        {
            var temp = TempFile.WithFilenameInTempFolder("tempHtml.htm");

            RobustFile.WriteAllText(temp.Path, CreateHtml5StringFromXml(dom));

            return(temp);
        }
        /// <summary>
        /// Convert the DOM (which is expected to be XHTML5) to HTML5
        /// </summary>
        public static string SaveDOMAsHtml5(XmlDocument dom, string targetPath)
        {
            var html = ConvertDomToHtml5(dom);

            RobustFile.WriteAllText(targetPath, html, Encoding.UTF8);

            return(targetPath);
        }
Esempio n. 18
0
 public void WriteAllTextExceptions()
 {
     using (var temp = new TempFile())
     {
         Assert.Throws <ArgumentNullException>(() => RobustFile.WriteAllText(temp.Path, null));
         Assert.Throws <ArgumentNullException>(() => RobustFile.WriteAllText(null, "nonsense"));
     }
 }
Esempio n. 19
0
        private void _seeDetails_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var temp = TempFile.WithExtension(".txt");

            RobustFile.WriteAllText(temp.Path, GetFullDescriptionContents(true));
            Process.Start(temp.Path);
            //yes, we're leaking this temp file
        }
Esempio n. 20
0
        public TempLiftFile(string fileName, TemporaryFolder parentFolder, string xmlOfEntries, string claimedLiftVersion)
            : base(false)
        {
            _path = parentFolder.Combine(fileName);

            string liftContents = string.Format("<?xml version='1.0' encoding='utf-8'?><lift version='{0}'>{1}</lift>", claimedLiftVersion, xmlOfEntries);

            RobustFile.WriteAllText(_path, liftContents);
        }
Esempio n. 21
0
        public TempLiftFile(string fileName, TemporaryFolder parentFolder, string xmlOfEntries, string claimedLiftVersion)
            : base(true)             // True means "I'll set the the pathname, thank you very much." Otherwise, the temp one 'false' creates will stay forever, and fill the hard drive up.
        {
            Path = parentFolder.Combine(fileName);

            string liftContents = string.Format("<?xml version='1.0' encoding='utf-8'?><lift version='{0}'>{1}</lift>", claimedLiftVersion, xmlOfEntries);

            RobustFile.WriteAllText(Path, liftContents);
        }
Esempio n. 22
0
 public void WriteAllTextEncodingExceptions()
 {
     using (var temp = new TempFile())
     {
         Assert.Throws <ArgumentNullException>(() => RobustFile.WriteAllText(temp.Path, null, Encoding.UTF8));
         Assert.Throws <ArgumentNullException>(() => RobustFile.WriteAllText(null, "nonsense", Encoding.BigEndianUnicode));
         Assert.Throws <ArgumentNullException>(() => RobustFile.WriteAllText(temp.Path, "nonsense", null));
     }
 }
Esempio n. 23
0
        /// <summary>
        /// Convert the DOM (which is expected to be XHTML5) to HTML5
        /// </summary>
        public static string SaveDOMAsHtml5(XmlDocument dom, string targetPath)
        {
            // First we write the DOM out to string

            var settings = new XmlWriterSettings {
                Indent = true, CheckCharacters = true, OmitXmlDeclaration = true
            };
            var xmlStringBuilder = new StringBuilder();

            using (var writer = XmlWriter.Create(xmlStringBuilder, settings))
            {
                dom.WriteContentTo(writer);
                writer.Close();
            }

            // HTML Tidy will mess that xml up, so we have this work around to make it "safe from libtidy"
            var xml = xmlStringBuilder.ToString();

            xml = AddFillerToKeepTidyFromRemovingEmptyElements(xml);

            // Now re-write as html, indented nicely
            string html;

            using (var tidy = Document.FromString(xml))
            {
                tidy.ShowWarnings        = false;
                tidy.Quiet               = true;
                tidy.AddTidyMetaElement  = false;
                tidy.OutputXml           = false;
                tidy.OutputHtml          = true;
                tidy.DocType             = DocTypeMode.Html5;
                tidy.MergeDivs           = AutoBool.No;
                tidy.MergeSpans          = AutoBool.No;
                tidy.PreserveEntities    = true;
                tidy.JoinStyles          = false;
                tidy.IndentBlockElements = AutoBool.Auto;                 //instructions say avoid 'yes'
                tidy.WrapAt              = 9999;
                tidy.IndentSpaces        = 4;
                tidy.CharacterEncoding   = EncodingType.Utf8;
                tidy.CleanAndRepair();
                using (var stream = new MemoryStream())
                {
                    tidy.Save(stream);
                    stream.Flush();
                    stream.Seek(0L, SeekOrigin.Begin);
                    using (var sr = new StreamReader(stream, Encoding.UTF8))
                        html = sr.ReadToEnd();
                }
            }

            // Now revert the stuff we did to make it "safe from libtidy"
            html = RemoveFillerInEmptyElements(html);
            RobustFile.WriteAllText(targetPath, html, Encoding.UTF8);

            return(targetPath);
        }
Esempio n. 24
0
        private BookStorage GetInitialStorageWithCustomHtml(string html)
        {
            RobustFile.WriteAllText(_bookPath, html);
            var projectFolder      = new TemporaryFolder("BookStorageTests_ProjectCollection");
            var collectionSettings = new CollectionSettings(Path.Combine(projectFolder.Path, "test.bloomCollection"));
            var storage            = new BookStorage(_folder.Path, _fileLocator, new BookRenamedEvent(), collectionSettings);

            storage.Save();
            return(storage);
        }
        public void ConnectToTeamCollection_SetsUpRequiredFiles()
        {
            using (var collectionFolder = new TemporaryFolder("FolderTeamCollectionTests2_Collection"))
            {
                using (var sharedFolder = new TemporaryFolder("FolderTeamCollectionTests2_Shared"))
                {
                    var bookFolderName1 = "Some book";
                    SyncAtStartupTests.MakeFakeBook(collectionFolder.FolderPath, bookFolderName1, "Something");
                    // BL-9573 tests cases where the book name isn't exactly the same as the folder name
                    var bookFolderName2 = "Some other book";
                    SyncAtStartupTests.MakeFakeBook(collectionFolder.FolderPath, "Some other name altogether",
                                                    "Strange book content", bookFolderName2);
                    var settingsFileName =
                        Path.ChangeExtension(Path.GetFileName(collectionFolder.FolderPath), "bloomCollection");
                    var settingsPath = Path.Combine(collectionFolder.FolderPath, settingsFileName);

                    // As an aside, this is a convenient place to check that a TC manager created when TC settings does not exist
                    // functions and does not have a current collection.
                    var tcManager = new TeamCollectionManager(settingsPath, null, new BookRenamedEvent(),
                                                              new BookStatusChangeEvent(), null, null);
                    Assert.That(tcManager.CurrentCollection, Is.Null);

                    RobustFile.WriteAllText(settingsPath, "This is a fake settings file");
                    FolderTeamCollection.CreateTeamCollectionLinkFile(collectionFolder.FolderPath,
                                                                      sharedFolder.FolderPath);

                    var nonBookFolder = Path.Combine(collectionFolder.FolderPath, "Some other folder");
                    Directory.CreateDirectory(nonBookFolder);
                    tcManager = new TeamCollectionManager(settingsPath, null, new BookRenamedEvent(),
                                                          new BookStatusChangeEvent(), null, null);
                    var collection = tcManager.CurrentCollection;

                    // sut
                    (collection as FolderTeamCollection)?.SetupTeamCollection(sharedFolder.FolderPath,
                                                                              new NullWebSocketProgress());

                    Assert.That(collection, Is.Not.Null);
                    var joinCollectionPath =
                        Path.Combine(sharedFolder.FolderPath, "Join this Team Collection.JoinBloomTC");
                    Assert.That(File.Exists(joinCollectionPath));

                    var teamCollectionLinkPath =
                        Path.Combine(collectionFolder.FolderPath, TeamCollectionManager.TeamCollectionLinkFileName);
                    Assert.That(File.Exists(teamCollectionLinkPath));
                    var collectionFileContent = RobustFile.ReadAllText(teamCollectionLinkPath);
                    Assert.That(collectionFileContent, Is.EqualTo(sharedFolder.FolderPath));
                    var sharedSettingsPath = Path.Combine(collectionFolder.FolderPath, settingsFileName);
                    Assert.That(RobustFile.ReadAllText(sharedSettingsPath), Is.EqualTo("This is a fake settings file"));
                    var bookPath = Path.Combine(sharedFolder.FolderPath, "Books", bookFolderName1 + ".bloom");
                    Assert.That(File.Exists(bookPath));
                    var bookPath2 = Path.Combine(sharedFolder.FolderPath, "Books", bookFolderName2 + ".bloom");
                    Assert.That(File.Exists(bookPath2));
                }
            }
        }
Esempio n. 26
0
 /// <summary>
 /// Remove language specific style settings for unwanted languages from all CSS files in the given directory.
 /// </summary>
 public static void RemoveUnwantedLanguageRulesFromCssFiles(string dirName, IEnumerable <string> wantedLanguages)
 {
     foreach (var filepath in Directory.EnumerateFiles(dirName, "*.css"))
     {
         var cssTextOrig = RobustFile.ReadAllText(filepath);
         var cssText     = HtmlDom.RemoveUnwantedLanguageRulesFromCss(cssTextOrig, wantedLanguages);
         if (cssText != cssTextOrig)
         {
             RobustFile.WriteAllText(filepath, cssText);
         }
     }
 }
Esempio n. 27
0
        public void WriteToFolder(string bookFolderPath)
        {
            var publishSettingsPath = PublishSettingsPath(bookFolderPath);

            try
            {
                RobustFile.WriteAllText(publishSettingsPath, Json);
            }
            catch (Exception e)
            {
                ErrorReport.NotifyUserOfProblem(e, "Bloom could not save your publish settings.");
            }
        }
Esempio n. 28
0
        void UpdateLocalBook(string name, string content, bool updateChecksum = true)
        {
            var folderPath = Path.Combine(_collectionFolder.FolderPath, name);
            var bookPath   = Path.Combine(folderPath, Path.ChangeExtension(name, "htm"));

            RobustFile.WriteAllText(bookPath, "<html><body>" + content + "</body></html>");
            if (updateChecksum)
            {
                var status = _collection.GetLocalStatus(name);
                status.checksum = Bloom.TeamCollection.TeamCollection.MakeChecksum(folderPath);
                _collection.WriteLocalStatus(name, status);
            }
        }
Esempio n. 29
0
        public static void GetUnusedFilenameTests(string basename, string expectedResult)
        {
            const string extension = ".txt";

            using (var folder = new TemporaryFolder("UnusedFilenameTest"))
            {
                var basePath = Path.Combine(folder.Path, basename + extension);
                RobustFile.Delete(basePath);                 // just in case
                RobustFile.WriteAllText(basePath, "test contents");
                var filename = ImageUtils.GetUnusedFilename(Path.GetDirectoryName(basePath), basename, extension);
                Assert.That(Path.GetFileNameWithoutExtension(filename), Is.EqualTo(expectedResult));
            }
        }
        public void ChangeToFileInOther_FromLocal_DoesNothingUnexpected()
        {
            using (var collectionFolder =
                       new TemporaryFolder("ChangeToFileInOther_FromLocal_DoesNothingUnexpected"))
            {
                using (var repoFolder =
                           new TemporaryFolder("ChangeToFileInOther_FromLocal_DoesNothingUnexpected"))
                {
                    var mockTcManager = new Mock <ITeamCollectionManager>();
                    var tc            = new TestFolderTeamCollection(mockTcManager.Object, collectionFolder.FolderPath,
                                                                     repoFolder.FolderPath);
                    var otherPath = Path.Combine(collectionFolder.FolderPath,
                                                 Path.GetFileName(collectionFolder.FolderPath) + ".bloomCollection");
                    // this test doesn't need this folder except that StartMonitoring does.
                    Directory.CreateDirectory(Path.Combine(repoFolder.FolderPath, "Books"));
                    File.WriteAllText(otherPath, "This is the initial value");
                    tc.CopyRepoCollectionFilesFromLocal(collectionFolder.FolderPath);

                    var eventWasRaised = false;

                    tc.StartMonitoring();

                    ManualResetEvent collectionChangedRaised = new ManualResetEvent(false);
                    // This action should be invoked (by test code, due to an override handler on the
                    // low-level event handler for the watcher).
                    tc.OnCollectionChangedCalled = () => collectionChangedRaised.Set();
                    EventHandler <EventArgs> monitorFunction = (sender, args) =>
                    {
                        // This should not happen because we should know we're writing locally.
                        eventWasRaised = true;
                        collectionChangedRaised.Set();
                    };
                    tc.RepoCollectionFilesChanged += monitorFunction;

                    // sut (at least, triggers it and waits for it)
                    RobustFile.WriteAllText(otherPath, @"This is changed");
                    tc.CopyRepoCollectionFilesFromLocal(collectionFolder.FolderPath);

                    var waitSucceeded = collectionChangedRaised.WaitOne(1000);

                    // To avoid messing up other tests, clean up before asserting.
                    tc.RepoCollectionFilesChanged -= monitorFunction;
                    tc.StopMonitoring();

                    Assert.That(waitSucceeded, "file change was not detected");
                    Assert.That(eventWasRaised, Is.False, "event was wrongly raised");
                }
            }
        }