public DataManipulator(MessageStorage ms) { logger = ms._logger; fileStorage = ms._filestorage; cacheStorage = ms._cache; saveOrReadStorage = ms._saveOrReadStorage; }
/// <summary> /// Constructs by finding the file and folder of the xmatter pack, given the its key name e.g. "Factory", "SILIndonesia". /// The name of the file should be (key)-XMatter.htm. The name and the location of the folder is not our problem... /// we leave it to the supplied fileLocator to find it. /// </summary> /// <param name="nameOfXMatterPack">e.g. "Factory", "SILIndonesia"</param> /// <param name="fileLocator">The locator needs to be able tell use the path to an xmater html file, given its name</param> public XMatterHelper(HtmlDom bookDom, string nameOfXMatterPack, IFileLocator fileLocator) { _bookDom = bookDom; _nameOfXMatterPack = nameOfXMatterPack; string directoryName = nameOfXMatterPack + "-XMatter"; string directoryPath; try { directoryPath = fileLocator.LocateDirectoryWithThrow(directoryName); } catch (Exception error) { //NB: we don't want to put up a dialog for each one; one failure here often means 20 more are coming as the other books are loaded! throw new ApplicationException(String.Format("Could not find xmatter pack directory named " + directoryName), error); } string htmName = nameOfXMatterPack + "-XMatter.htm"; PathToXMatterHtml = directoryPath.CombineForPath(htmName); if (!File.Exists(PathToXMatterHtml)) { ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "Could not locate the file {0} in {1}", htmName, directoryPath); throw new ApplicationException(); } PathToStyleSheetForPaperAndOrientation = directoryPath.CombineForPath(GetStyleSheetFileName()); if (!File.Exists(PathToXMatterHtml)) { ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "Could not locate the file {0} in {1}", GetStyleSheetFileName(), directoryPath); throw new ApplicationException(); } XMatterDom = XmlHtmlConverter.GetXmlDomFromHtmlFile(PathToXMatterHtml, false); }
protected FileRepo(IFileLocator fileLocator, IEnumerable<TodoTask> tasks ) { _fileLocator = fileLocator; foreach (var task in tasks) Add(task); }
private static void CombineTextures(Texture baseTexture, IFileLocator locator, string filename) { Texture newTexture; using (Stream file = locator.Open(filename)) { newTexture = Texture.FromStream(file); newTexture.Name = Path.GetFileNameWithoutExtension(filename); } if (newTexture.Width != baseTexture.Width || newTexture.Height != baseTexture.Height) { return; } newTexture.Convert8To32(); int size = baseTexture.Width * baseTexture.Height; byte[] src = newTexture.ImageData; byte[] dst = baseTexture.ImageData; for (int i = 0; i < size; i++) { int a = src[i * 4 + 3]; dst[i * 4 + 0] = (byte)(dst[i * 4 + 0] * (255 - a) / 255 + src[i * 4 + 0] * a / 255); dst[i * 4 + 1] = (byte)(dst[i * 4 + 1] * (255 - a) / 255 + src[i * 4 + 1] * a / 255); dst[i * 4 + 2] = (byte)(dst[i * 4 + 2] * (255 - a) / 255 + src[i * 4 + 2] * a / 255); } }
public void GivenNoScripts() { var scripts = new[] {"Scripts/test1.sql", "Scripts/test2.sql"}; _fileLocator = Substitute.For<IFileLocator>(); _fileLocator.GetFilePaths("Scripts", "*.sql").Returns(scripts); }
/// <summary> /// Detects if the specified root from a locator is a disc. /// </summary> /// <param name="locator">The locator.</param> /// <param name="root">The root.</param> /// <param name="detect">The detection function.</param> /// <returns>A boolean.</returns> private static bool IsDisc(IFileLocator locator, string root, Func <Stream, bool> detect) { using (var file = locator.Open(root)) { return(detect(file)); } }
public Player(IFileLocator fileLocator) { wmp = new WindowsMediaPlayer(); fileLocator.TrackAdded += FileLocatorOnTrackAdded; foreach (var track in fileLocator.FindTracks()) Queue(track); }
//autofac uses this public BookStarter(IChangeableFileLocator fileLocator, BookStorage.Factory bookStorageFactory, CollectionSettings collectionSettings) { _fileLocator = fileLocator; _bookStorageFactory = bookStorageFactory; _collectionSettings = collectionSettings; _isSourceCollection = collectionSettings.IsSourceCollection; }
public void GivenNoScripts() { var scripts = new[] { "Scripts/test1.sql", "Scripts/test2.sql" }; _fileLocator = Substitute.For <IFileLocator>(); _fileLocator.GetFilePaths("Scripts", "*.sql").Returns(scripts); }
public void FindBinaryNegativeTest() { IFileLocator locator = GetLocator(); string dac = locator.FindPEImage(WellKnownDac, WellKnownDacTimeStamp + 1, WellKnownDacImageSize + 1, false); Assert.Null(dac); }
public delegate BookStarter Factory(); //autofac uses this public BookStarter(IChangeableFileLocator fileLocator, BookStorage.Factory bookStorageFactory, CollectionSettings collectionSettings) { _fileLocator = fileLocator; _bookStorageFactory = bookStorageFactory; _collectionSettings = collectionSettings; _isSourceCollection = collectionSettings.IsSourceCollection; }
/// <summary> /// Initializes the test fixture with the given file locator. /// </summary> /// <param name="fileLocator">The file locator.</param> public FileSandboxFeature(IFileLocator fileLocator) { _fileLocator = fileLocator; #if XUNIT || XUNIT2 SetUpSandbox(); #endif }
public AddPicturesTask(AddPicturesConfig config, LexEntryRepository lexEntryRepository, TaskMemoryRepository taskMemoryRepository, IFileLocator fileLocator) : base(config, lexEntryRepository, taskMemoryRepository) { _config = config; }
/// <summary> /// Create a new file sandbox. /// </summary> /// <param name="fileLocator">The file locator which resolves files.</param> public FileSandbox(IFileLocator fileLocator) { _fileLocator = fileLocator; _sandboxPath = System.IO.Path.Combine(GetSandboxBasePath(), Guid.NewGuid().ToString()); System.IO.Directory.CreateDirectory(_sandboxPath); }
public void FindBinaryTest() { IFileLocator locator = GetLocator(); string dac = locator.FindPEImage(WellKnownDac, WellKnownDacTimeStamp, WellKnownDacImageSize, false); Assert.NotNull(dac); Assert.True(File.Exists(dac)); }
public static IEnumerable <Layout> GetLayoutChoices(HtmlDom dom, IFileLocator fileLocator) { //here we walk through all the stylesheets, looking for one with the special style which tells us which page/orientations it supports foreach (XmlElement link in dom.SafeSelectNodes("//link[@rel='stylesheet']")) { var fileName = link.GetStringAttribute("href"); if (fileName.ToLowerInvariant().Contains("mode") || fileName.ToLowerInvariant().Contains("page") || fileName.ToLowerInvariant().Contains("matter") || fileName.ToLowerInvariant().Contains("languagedisplay") || fileName.ToLowerInvariant().Contains("origami")) { continue; } fileName = fileName.Replace("file://", "").Replace("%5C", "/").Replace("%20", " "); var path = fileLocator.LocateFile(fileName); if (string.IsNullOrEmpty(path)) { // We're looking for a block of json that is typically found in Basic Book.css or a comparable place for // a book based on some other template. Caling code is prepared for not finding this block. // It seems safe to ignore a reference to some missing style sheet. NonFatalProblem.Report(ModalIf.None, PassiveIf.Alpha, "Could not find " + fileName + " while looking for size choices"); continue; } var contents = RobustFile.ReadAllText(path); var start = contents.IndexOf("STARTLAYOUTS"); if (start < 0) { continue; //yield break; // continue;//move on to the next stylesheet } start += "STARTLAYOUTS".Length; var end = contents.IndexOf("ENDLAYOUTS", start); var s = contents.Substring(start, end - start); IEnumerable <Layout> layouts = null; try { layouts = Layout.GetConfigurationsFromConfigurationOptionsString(s); } catch (Exception e) { throw new ApplicationException("Problem parsing the 'layouts' comment of " + fileName + ". The contents were\r\n" + s, e); } foreach (var p in layouts) { yield return(p); } yield break; } //default to A5Portrait yield return(new Layout { SizeAndOrientation = FromString("A5Portrait") }); }
public void UpdateStyleSheetLinkPaths(IFileLocator fileLocator, string folderPath, IProgress log) { foreach (XmlElement linkNode in SafeSelectNodes("/html/head/link")) { var href = linkNode.GetAttribute("href"); if (href == null) { continue; } //TODO: see long comment on ProjectContextGetFileLocations() about linking to the right version of a css //TODO: what cause this to get encoded this way? Saw it happen when creating wall calendar href = href.Replace("%5C", "/"); var fileName = FileUtils.NormalizePath(Path.GetFileName(href)); if (!fileName.StartsWith("xx")) //I use xx as a convenience to temporarily turn off stylesheets during development { var path = fileLocator.LocateOptionalFile(fileName); //we want these stylesheets to come from the book folder if (string.IsNullOrEmpty(path) || path.Contains("languageDisplay.css")) { //look in the same directory as the book var local = Path.Combine(folderPath, fileName); if (File.Exists(local)) { path = local; } } //we want these stylesheets to come from the user's collection folder, not ones found in the templates directories else if (path.Contains("CollectionStyles.css")) //settingsCollectionStyles & custonCollectionStyles { //look in the parent directory of the book var pathInCollection = Path.Combine(Path.GetDirectoryName(folderPath), fileName); if (File.Exists(pathInCollection)) { path = pathInCollection; } } if (!string.IsNullOrEmpty(path)) { //this is here for geckofx 11... probably can remove it when we move up to modern gecko, as FF22 doesn't like it. //linkNode.SetAttribute("href", "file://" + path); linkNode.SetAttribute("href", path.ToLocalhost()); } else { throw new ApplicationException( string.Format("Bloom could not find the stylesheet '{0}', which is used in {1}", fileName, folderPath)); } } } }
public MessageStore(DirectoryInfo workingDirectory) { this.WorkingDirectory = workingDirectory; this.cache = new StoreCache(); this.log = new StoreLogger(); var fileStore = new FileStore(workingDirectory); this.store = fileStore; this.fileLocator = fileStore; }
public static Layout FromDomAndChoices(HtmlDom dom, Layout defaultIfMissing, IFileLocator fileLocator) { // If the stylesheet's special style which tells us which page/orientations it supports matches the default // page size and orientation in the template's bloom-page class, we don't need this method. // Otherwise, we need to make sure that the book's layout updates to something that really is a possibility. var layout = FromDom(dom, defaultIfMissing); layout = EnsureLayoutIsAmongValidChoices(dom, layout, fileLocator); return(layout); }
/// <summary> /// Initializes a new instance of the <see cref="SystemFileLocator"/> class. /// </summary> /// <param name="locator">A file locator.</param> /// <param name="root">The root path.</param> public SystemFileLocator(IFileLocator locator, string root) { if (locator == null && !Directory.Exists(root)) { throw new DirectoryNotFoundException(); } this.locator = locator; this.rootPath = root; }
public PictureControl(string pathToReferingFile, string storageFolderPath, IFileLocator fileLocator) { InitializeComponent(); _pathToReferingFile = pathToReferingFile; _storageFolderPath = storageFolderPath; _fileLocator = fileLocator; if (!Directory.Exists(storageFolderPath)) { Directory.CreateDirectory(storageFolderPath); } }
public static IEnumerable <Layout> GetLayoutChoices(HtmlDom dom, IFileLocator fileLocator) { //here we walk through all the stylesheets, looking for one with the special style which tells us which page/orientations it supports foreach (XmlElement link in dom.SafeSelectNodes("//link[@rel='stylesheet']")) { var fileName = link.GetStringAttribute("href"); if (fileName.ToLower().Contains("mode") || fileName.ToLower().Contains("page") || fileName.ToLower().Contains("matter") || fileName.ToLower().Contains("languagedisplay")) { continue; } fileName = fileName.Replace("file://", "").Replace("%5C", "/"); fileName = fileName.Replace("file://", "").Replace("%20", " "); var path = fileLocator.LocateFile(fileName); if (string.IsNullOrEmpty(path)) { throw new ApplicationException("Could not locate " + fileName); } var contents = File.ReadAllText(path); var start = contents.IndexOf("STARTLAYOUTS"); if (start < 0) { continue; //yield break; // continue;//move on to the next stylesheet } start += "STARTLAYOUTS".Length; var end = contents.IndexOf("ENDLAYOUTS", start); var s = contents.Substring(start, end - start); IEnumerable <Layout> layouts = null; try { layouts = Layout.GetConfigurationsFromConfigurationOptionsString(s); } catch (Exception e) { throw new ApplicationException("Problem parsing the 'layouts' comment of " + fileName + ". The contents were\r\n" + s, e); } foreach (var p in layouts) { yield return(p); } yield break; } //default to A5Portrait yield return(new Layout { SizeAndOrientation = FromString("A5Portrait") }); }
/// <summary> /// Initializes a new instance of the <see cref="ArchiveFileLocator"/> class. /// </summary> /// <param name="locator">A file locator.</param> /// <param name="root">The root path.</param> public ArchiveFileLocator(IFileLocator locator, string root) { if (locator != null) { this.fileStream = locator.Open(root); this.archive = ArchiveFactory.Open(this.fileStream); } else { this.archive = ArchiveFactory.Open(root); } }
/// <summary> /// Initializes a new instance of the <see cref="DiscFsFileLocator"/> class. /// </summary> /// <param name="locator">A file locator.</param> /// <param name="root">The root path.</param> /// <param name="create">The create function.</param> protected DiscFsFileLocator(IFileLocator locator, string root, Func <Stream, DiscFileSystem> create) { if (locator != null) { this.fileStream = locator.Open(root); } else { this.fileStream = File.OpenRead(root); } this.disc = create(this.fileStream); }
public static string GetBestDeviceXMatterAvailable(string xmatterName, IFileLocator fileLocator) { if (xmatterName.EndsWith("Device")) { return(xmatterName); } var deviceXmatterName = $"{xmatterName}-Device"; var directoryPath = GetXMatterDirectory(deviceXmatterName, fileLocator, null, false, true); // if "{xmatterName}-Device" is unavailable, use the default Device xmatter which is just named "Device" return(directoryPath != null ? deviceXmatterName : "Device"); }
public static Stream OpenVisualFile(string modelFile, IFileLocator fileLocator) { var visualFile = Path.ChangeExtension(modelFile, ".visual"); // pre 10.0 Stream stream; if (fileLocator.TryOpenRead(visualFile, out stream)) { return(stream); } visualFile = Path.ChangeExtension(modelFile, ".visual_processed"); // post 10.0 return(fileLocator.OpenRead(visualFile)); }
public static string GetXMatterDirectory(string nameOfXMatterPack, IFileLocator fileLocator, string errorMsg, bool throwIfError, bool silent = false) { var directoryName = nameOfXMatterPack + "-XMatter"; if (Program.RunningHarvesterMode) { // Get a new file locator that also searches the Custom XMatter directory. // This allows the Harvseter to preserve custom branding if those books are uploaded to web. (See BL-BL-9084) var extraSearchPaths = new string[] { BloomFileLocator.GetCustomXMatterDirectory() }; fileLocator = fileLocator.CloneAndCustomize(extraSearchPaths); } if (silent) { // Using LocateDirectoryWithThrow is quite expensive for directories we don't find...the Exception it creates, which we don't use, // includes a concatenation of a long list of paths it searched in. (It's quite common now to search for an xmatter directory // we don't often find, such as looking for one called Traditional-Device when publishing something with Traditional xmatter // on a device. try { var result = fileLocator.LocateDirectory(directoryName); if (result == null || !Directory.Exists(result)) { return(null); } return(result); } catch (ApplicationException) { return(null); } } try { return(fileLocator.LocateDirectoryWithThrow(directoryName)); } catch (ApplicationException error) { if (silent) { return(null); } var frontBackMatterProblem = LocalizationManager.GetString("Errors.XMatterProblemLabel", "Front/Back Matter Problem", "This shows in the 'toast' that pops up to notify the user of a non-fatal problem."); NonFatalProblem.Report(ModalIf.None, PassiveIf.All, frontBackMatterProblem, errorMsg, error); if (throwIfError) { throw new ApplicationException(errorMsg); } } return(null); }
public static Stream OpenPrimitiveFile(string modelFile, IFileLocator fileLocator) { var primitiveFile = Path.ChangeExtension(modelFile, ".primitives"); // pre 10.0 Stream stream; if (fileLocator.TryOpenRead(primitiveFile, out stream)) { return(stream); } primitiveFile = Path.ChangeExtension(modelFile, ".primitives_processed"); // post 10.0 return(fileLocator.OpenRead(primitiveFile)); }
public UpdateService(IFileLocator dbLocator) : base(dbLocator) { var asm = Assembly.GetExecutingAssembly().GetManifestResourceNames().ToList(); _views = (from asset in asm where asset.StartsWith("Probel.Gehova.Business.Assets.views_") select asset).ToList(); _updates = (from asset in asm where asset.StartsWith("Probel.Gehova.Business.Assets.Scripts") orderby asset select asset).ToList(); _assetManager = new AssetManager(this); }
/// <summary> /// stick in a json with various settings we want to make available to the javascript /// </summary> public static void AddUISettingsToDom(HtmlDom pageDom, BookData bookData, IFileLocator fileLocator) { CheckDynamicStrings(); XmlElement existingElement = pageDom.RawDom.SelectSingleNode("//script[@id='ui-settings']") as XmlElement; XmlElement element = pageDom.RawDom.CreateElement("script"); element.SetAttribute("type", "text/javascript"); element.SetAttribute("id", "ui-settings"); var d = new Dictionary <string, string>(); //d.Add("urlOfUIFiles", "file:///" + fileLocator.LocateDirectory("ui", "ui files directory")); if (!String.IsNullOrEmpty(Settings.Default.LastSourceLanguageViewed)) { d.Add("defaultSourceLanguage", Settings.Default.LastSourceLanguageViewed); } d.Add("languageForNewTextBoxes", bookData.Language1.Iso639Code); d.Add("isSourceCollection", bookData.CollectionSettings.IsSourceCollection.ToString()); // BL-2357 To aid in smart ordering of source languages in source bubble if (!String.IsNullOrEmpty(bookData.Language2IsoCode)) { d.Add("currentCollectionLanguage2", bookData.Language2IsoCode); } if (!String.IsNullOrEmpty(bookData.Language3IsoCode)) { d.Add("currentCollectionLanguage3", bookData.Language3IsoCode); } d.Add("browserRoot", FileLocationUtilities.GetDirectoryDistributedWithApplication(BloomFileLocator.BrowserRoot).ToLocalhost()); element.InnerText = String.Format("function GetSettings() {{ return {0};}}", JsonConvert.SerializeObject(d)); var head = pageDom.RawDom.SelectSingleNode("//head"); if (existingElement != null) { head.ReplaceChild(element, existingElement); } else { head.InsertAfter(element, head.LastChild); } _collectDynamicStrings = false; }
/// <summary> /// Write the files from a file locator. /// </summary> /// <param name="locator">A file locator.</param> /// <param name="root">The root path.</param> public void WriteAll(IFileLocator locator, string root) { if (locator == null) { throw new ArgumentNullException("locator"); } foreach (var file in locator.EnumerateFiles(root)) { using (var stream = locator.Open(file)) { this.Write(file, stream); } } }
public ScriptProcessor( string environment, string baseScriptFolder, string fileMatchPattern, IFileLocator fileLocator, IScriptHistory scriptHistory, IExecutor executor) { _environment = environment; _baseScriptFolder = baseScriptFolder; _fileMatchPattern = fileMatchPattern; _fileLocator = fileLocator; _scriptHistory = scriptHistory; _executor = executor; }
// Make it a requirement // Constructor public MessageStore(IStoreWriter writer, IStoreReader reader, IFileLocator fileLocator) { if (writer == null) throw new ArgumentNullException("Writer"); if (reader == null) throw new ArgumentNullException("Reader"); if (fileLocator == null) throw new ArgumentNullException("FileLocator"); this.fileLocator = fileLocator; this.writer = writer; this.reader = reader; }
private static Stream OpenTexture(IFileLocator fileLocator, string path) { Stream stream; if (fileLocator.TryOpenRead(path, out stream)) { return(stream); } if (Path.GetExtension(path) == ".tga") { path = Path.ChangeExtension(path, ".dds"); return(fileLocator.OpenRead(path)); } throw new FileNotFoundException("file not found", path); }
/// <summary> /// 根据文件的ID返回文件的物理路径 /// </summary> /// <param name="fileIds"></param> /// <returns></returns> public string[] GetFilePath(params int[] fileIds) { IFileLocator locator = null; if (fileIds.IsEmpty()) { return(new string[0]); } var files = _article.GetAllInCatalog(SystemTypes.Root.Id) .Where(f => fileIds.Contains(f.Id)) .ToList() .Select(f => locator.GetFilePath(f.GetExtStr(SystemTypes.Root.Key))) .ToArray(); return(files); }
public static string GetXMatterDirectory(string nameOfXMatterPack, IFileLocator fileLocator, string errorMsg, bool throwIfError) { try { var directoryName = nameOfXMatterPack + "-XMatter"; return(fileLocator.LocateDirectoryWithThrow(directoryName)); } catch (ApplicationException error) { var frontBackMatterProblem = LocalizationManager.GetString("Errors.XMatterProblemLabel", "Front/Back Matter Problem", "This shows in the 'toast' that pops up to notify the user of a non-fatal problem."); NonFatalProblem.Report(ModalIf.None, PassiveIf.All, frontBackMatterProblem, errorMsg, error); if (throwIfError) { throw new ApplicationException(errorMsg); } } return(null); }
/// <summary> /// Constructs by finding the file and folder of the xmatter pack, given the its key name e.g. "Factory", "SILIndonesia". /// The name of the file should be (key)-XMatter.htm. The name and the location of the folder is not our problem... /// we leave it to the supplied fileLocator to find it. /// </summary> /// <param name="nameOfXMatterPack">e.g. "Factory", "SILIndonesia"</param> /// <param name="fileLocator">The locator needs to be able tell us the path to an xmater html file, given its name</param> public XMatterHelper(HtmlDom bookDom, string nameOfXMatterPack, IFileLocator fileLocator) { _bookDom = bookDom; _nameOfXMatterPack = nameOfXMatterPack; string directoryName = nameOfXMatterPack + "-XMatter"; string directoryPath; try { directoryPath = fileLocator.LocateDirectoryWithThrow(directoryName); } catch(ApplicationException error) { var errorTemplate = LocalizationManager.GetString("Errors.XMatterNotFound", "This Book called for Front/Back Matter pack named '{0}', but Bloom couldn't find that on this computer. You can either install a Bloom Pack that will give you '{0}', or go to Settings:Book Making and change to another Front/Back Matter Pack."); var msg = string.Format(errorTemplate, nameOfXMatterPack); ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), msg); //NB: we don't want to put up a dialog for each one; one failure here often means 20 more are coming as the other books are loaded! throw new ApplicationException(msg); } var htmName = nameOfXMatterPack + "-XMatter.html"; PathToXMatterHtml = directoryPath.CombineForPath(htmName); if(!RobustFile.Exists(PathToXMatterHtml)) { htmName = nameOfXMatterPack + "-XMatter.htm"; // pre- Bloom 3.7 PathToXMatterHtml = directoryPath.CombineForPath(htmName); } if (!RobustFile.Exists(PathToXMatterHtml)) { ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "Could not locate the file {0} in {1} (also checked .html)", htmName, directoryPath); throw new ApplicationException(); } PathToStyleSheetForPaperAndOrientation = directoryPath.CombineForPath(GetStyleSheetFileName()); if (!RobustFile.Exists(PathToXMatterHtml)) { ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "Could not locate the file {0} in {1}", GetStyleSheetFileName(), directoryPath); throw new ApplicationException(); } XMatterDom = XmlHtmlConverter.GetXmlDomFromHtmlFile(PathToXMatterHtml, false); }
/// <summary> /// Constructs by finding the file and folder of the xmatter pack, given the its key name e.g. "Factory", "SILIndonesia". /// The name of the file should be (key)-XMatter.htm. The name and the location of the folder is not our problem... /// we leave it to the supplied fileLocator to find it. /// </summary> /// <param name="nameOfXMatterPack">e.g. "Factory", "SILIndonesia"</param> /// <param name="fileLocator">The locator needs to be able tell use the path to an xmater html file, given its name</param> public XMatterHelper(HtmlDom bookDom, string nameOfXMatterPack, IFileLocator fileLocator) { _bookDom = bookDom; _nameOfXMatterPack = nameOfXMatterPack; string directoryName = nameOfXMatterPack + "-XMatter"; var directoryPath = fileLocator.LocateDirectory(directoryName, "xmatter pack directory named " + directoryName); string htmName = nameOfXMatterPack + "-XMatter.htm"; PathToXMatterHtml = directoryPath.CombineForPath(htmName); if(!File.Exists(PathToXMatterHtml)) { ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "Could not locate the file {0} in {1}", htmName, directoryPath); throw new ApplicationException(); } PathToStyleSheetForPaperAndOrientation = directoryPath.CombineForPath(GetStyleSheetFileName()); if (!File.Exists(PathToXMatterHtml)) { ErrorReport.NotifyUserOfProblem(new ShowOncePerSessionBasedOnExactMessagePolicy(), "Could not locate the file {0} in {1}", GetStyleSheetFileName(), directoryPath); throw new ApplicationException(); } XMatterDom = XmlHtmlConverter.GetXmlDomFromHtmlFile(PathToXMatterHtml, false); }
/// <summary> /// stick in a json with various settings we want to make available to the javascript /// </summary> public static void AddUISettingsToDom(HtmlDom pageDom, CollectionSettings collectionSettings, IFileLocator fileLocator) { XmlElement element = pageDom.RawDom.SelectSingleNode("//script[@id='ui-settings']") as XmlElement; if (element != null) element.ParentNode.RemoveChild(element); element = pageDom.RawDom.CreateElement("script"); element.SetAttribute("type", "text/javascript"); element.SetAttribute("id", "ui-settings"); var d = new Dictionary<string, string>(); //d.Add("urlOfUIFiles", "file:///" + fileLocator.LocateDirectory("ui", "ui files directory")); if (!String.IsNullOrEmpty(Settings.Default.LastSourceLanguageViewed)) { d.Add("defaultSourceLanguage", Settings.Default.LastSourceLanguageViewed); } d.Add("languageForNewTextBoxes", collectionSettings.Language1Iso639Code); d.Add("bloomBrowserUIFolder", FileLocator.GetDirectoryDistributedWithApplication("BloomBrowserUI")); var topics = new[] { "Agriculture", "Animal Stories", "Business", "Culture", "Community Living", "Dictionary", "Environment", "Fiction", "Health", "How To", "Math", "Non Fiction", "Spiritual", "Personal Development", "Primer", "Science", "Traditional Story" }; var builder = new StringBuilder(); builder.Append("["); foreach (var topic in topics) { var localized = LocalizationManager.GetDynamicString("Bloom", "Topics." + topic, topic, "shows in the topics chooser in the edit tab"); builder.Append("\""+localized+"\", "); } builder.Append("]"); d.Add("topics", builder.ToString().Replace(", ]","]")); // d.Add("topics", "['Agriculture', 'Animal Stories', 'Business', 'Culture', 'Community Living', 'Dictionary', 'Environment', 'Fiction', 'Health', 'How To', 'Math', 'Non Fiction', 'Spiritual', 'Personal Development', 'Primer', 'Science', 'Tradition']".Replace("'", "\\\"")); element.InnerText = String.Format("function GetSettings() {{ return {0};}}", JsonConvert.SerializeObject(d)); var head = pageDom.RawDom.SelectSingleNode("//head"); head.InsertAfter(element, head.LastChild); }
public static IEnumerable<Layout> GetLayoutChoices(HtmlDom dom, IFileLocator fileLocator) { //here we walk through all the stylesheets, looking for one with the special style which tells us which page/orientations it supports foreach (XmlElement link in dom.SafeSelectNodes("//link[@rel='stylesheet']")) { var fileName = link.GetStringAttribute("href"); if (fileName.ToLower().Contains("mode") || fileName.ToLower().Contains("page") || fileName.ToLower().Contains("matter") || fileName.ToLower().Contains("languagedisplay")) continue; fileName = fileName.Replace("file://", "").Replace("%5C", "/"); var path = fileLocator.LocateFile(fileName); if(string.IsNullOrEmpty(path)) { throw new ApplicationException("Could not locate "+fileName); } var contents = File.ReadAllText(path); var start = contents.IndexOf("STARTLAYOUTS"); if (start < 0) continue; //yield break; // continue;//move on to the next stylesheet start += "STARTLAYOUTS".Length; var end = contents.IndexOf("ENDLAYOUTS",start); var s = contents.Substring(start, end - start); IEnumerable<Layout> layouts = null; try { layouts = Layout.GetConfigurationsFromConfigurationOptionsString(s); } catch (Exception e) { throw new ApplicationException("Problem parsing the 'layouts' comment of " + fileName + ". The contents were\r\n" + s, e); } foreach (var p in layouts) { yield return p; } yield break; } //default to A5Portrait yield return new Layout {SizeAndOrientation = FromString("A5Portrait")}; }
public BinaryFileRepo(IFileLocator fileLocator, RepoBase repoToClone) : base(fileLocator, repoToClone.GetRawList()) { }
public BinaryFileRepo(IFileLocator fileLocator) : base(fileLocator) { }
// /// <summary> // /// Creates a relative path from one file or folder to another. // /// </summary> // /// <param name="fromPath">Contains the directory that defines the start of the relative path.</param> // /// <param name="toPath">Contains the path that defines the endpoint of the relative path.</param> // /// <param name="dontEscape">Boolean indicating whether to add uri safe escapes to the relative path</param> // /// <returns>The relative path from the start directory to the end path.</returns> // /// <exception cref="ArgumentNullException"></exception> // public static String MakeRelativePath(String fromPath, String toPath) // { // if (String.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath"); // if (String.IsNullOrEmpty(toPath)) throw new ArgumentNullException("toPath"); // // //the stuff later on needs to see directory names trailed by a "/" or "\". // fromPath = fromPath.Trim(); // if (!fromPath.EndsWith(Path.DirectorySeparatorChar.ToString())) // { // if (Directory.Exists(fromPath)) // { // fromPath = fromPath + Path.DirectorySeparatorChar; // } // } // Uri fromUri = new Uri(fromPath); // Uri toUri = new Uri(toPath); // // Uri relativeUri = fromUri.MakeRelativeUri(toUri); // String relativePath = Uri.UnescapeDataString(relativeUri.ToString()); // // return relativePath.Replace('/', Path.DirectorySeparatorChar); // } private void UpdateStyleSheetLinkPaths(HtmlDom dom, IFileLocator fileLocator, IProgress log) { foreach (XmlElement linkNode in dom.SafeSelectNodes("/html/head/link")) { var href = linkNode.GetAttribute("href"); if (href == null) { continue; } //TODO: see long comment on ProjectContextGetFileLocations() about linking to the right version of a css //TODO: what cause this to get encoded this way? Saw it happen when creating wall calendar href = href.Replace("%5C", "/"); var fileName = Path.GetFileName(href); if (!fileName.StartsWith("xx")) //I use xx as a convenience to temporarily turn off stylesheets during development { var path = fileLocator.LocateOptionalFile(fileName); //we want these stylesheets to come from the book folder if (string.IsNullOrEmpty(path)|| path.Contains("languageDisplay.css")) { //look in the same directory as the book var local = Path.Combine(_folderPath, fileName); if (File.Exists(local)) path = local; } //we want these stylesheets to come from the user's collection folder, not ones found in the templates directories else if (path.Contains("CollectionStyles.css")) //settingsCollectionStyles & custonCollectionStyles { //look in the parent directory of the book var pathInCollection = Path.Combine(Path.GetDirectoryName(_folderPath), fileName); if (File.Exists(pathInCollection)) path = pathInCollection; } if (!string.IsNullOrEmpty(path)) { //this is here for geckofx 11... probably can remove it when we move up to modern gecko, as FF22 doesn't like it. linkNode.SetAttribute("href", "file://" + path); } else { throw new ApplicationException(string.Format("Bloom could not find the stylesheet '{0}', which is used in {1}", fileName, _folderPath)); } } } }
public static Layout FromDomAndChoices(HtmlDom dom, Layout defaultIfMissing, IFileLocator fileLocator) { // If the stylesheet's special style which tells us which page/orientations it supports matches the default // page size and orientation in the template's bloom-page class, we don't need this method. // Otherwise, we need to make sure that the book's layout updates to something that really is a possibility. var layout = FromDom(dom, defaultIfMissing); layout = EnsureLayoutIsAmongValidChoices(dom, layout, fileLocator); return layout; }
public static IEnumerable<Layout> GetLayoutChoices(HtmlDom dom, IFileLocator fileLocator) { //here we walk through all the stylesheets, looking for one with the special style which tells us which page/orientations it supports foreach (XmlElement link in dom.SafeSelectNodes("//link[@rel='stylesheet']")) { var fileName = link.GetStringAttribute("href"); if (fileName.ToLowerInvariant().Contains("mode") || fileName.ToLowerInvariant().Contains("page") || fileName.ToLowerInvariant().Contains("matter") || fileName.ToLowerInvariant().Contains("languagedisplay")) continue; fileName = fileName.Replace("file://", "").Replace("%5C", "/").Replace("%20", " "); var path = fileLocator.LocateFile(fileName); if(string.IsNullOrEmpty(path)) { // We're looking for a block of json that is typically found in Basic Book.css or a comparable place for // a book based on some other template. Caling code is prepared for not finding this block. // It seems safe to ignore a reference to some missing style sheet. NonFatalProblem.Report(ModalIf.None, PassiveIf.Alpha, "Could not find " + fileName+" while looking for size choices"); continue; } var contents = RobustFile.ReadAllText(path); var start = contents.IndexOf("STARTLAYOUTS"); if (start < 0) continue; //yield break; // continue;//move on to the next stylesheet start += "STARTLAYOUTS".Length; var end = contents.IndexOf("ENDLAYOUTS",start); var s = contents.Substring(start, end - start); IEnumerable<Layout> layouts = null; try { layouts = Layout.GetConfigurationsFromConfigurationOptionsString(s); } catch (Exception e) { throw new ApplicationException("Problem parsing the 'layouts' comment of " + fileName + ". The contents were\r\n" + s, e); } foreach (var p in layouts) { yield return p; } yield break; } //default to A5Portrait yield return new Layout {SizeAndOrientation = FromString("A5Portrait")}; }
public void Start() { FileLocator = new FileLocator(); }
public FlatFileRepo(IFileLocator fileLocator) : base(fileLocator) { }
protected FileRepo(IFileLocator fileLocator) { _fileLocator = fileLocator; }
public FlatFileRepo(IFileLocator fileLocator) { _fileLocator = fileLocator; }
public void GivenNoScripts() { _fileLocator = Substitute.For<IFileLocator>(); _fileLocator.GetFilePaths("Scripts", "*.sql").Returns(Enumerable.Empty<string>()); }
public FlatFileRepo(IFileLocator fileLocator, FlatFileRepo repoToClone) { _fileLocator = fileLocator; _list = repoToClone._list; }
/// <summary> /// stick in a json with various settings we want to make available to the javascript /// </summary> public static void AddUISettingsToDom(HtmlDom pageDom, CollectionSettings collectionSettings, IFileLocator fileLocator) { CheckDynamicStrings(); XmlElement existingElement = pageDom.RawDom.SelectSingleNode("//script[@id='ui-settings']") as XmlElement; XmlElement element = pageDom.RawDom.CreateElement("script"); element.SetAttribute("type", "text/javascript"); element.SetAttribute("id", "ui-settings"); var d = new Dictionary<string, string>(); //d.Add("urlOfUIFiles", "file:///" + fileLocator.LocateDirectory("ui", "ui files directory")); if (!String.IsNullOrEmpty(Settings.Default.LastSourceLanguageViewed)) { d.Add("defaultSourceLanguage", Settings.Default.LastSourceLanguageViewed); } d.Add("languageForNewTextBoxes", collectionSettings.Language1Iso639Code); d.Add("isSourceCollection", collectionSettings.IsSourceCollection.ToString()); // BL-2357 To aid in smart ordering of source languages in source bubble if (!String.IsNullOrEmpty(collectionSettings.Language2Iso639Code)) { d.Add("currentCollectionLanguage2", collectionSettings.Language2Iso639Code); } if (!String.IsNullOrEmpty(collectionSettings.Language3Iso639Code)) { d.Add("currentCollectionLanguage3", collectionSettings.Language3Iso639Code); } d.Add("browserRoot", FileLocator.GetDirectoryDistributedWithApplication(BloomFileLocator.BrowserRoot).ToLocalhost()); element.InnerText = String.Format("function GetSettings() {{ return {0};}}", JsonConvert.SerializeObject(d)); var head = pageDom.RawDom.SelectSingleNode("//head"); if (existingElement != null) head.ReplaceChild(element, existingElement); else head.InsertAfter(element, head.LastChild); _collectDynamicStrings = false; }
private static Layout EnsureLayoutIsAmongValidChoices(HtmlDom dom, Layout layout, IFileLocator fileLocator) { var layoutChoices = SizeAndOrientation.GetLayoutChoices(dom, fileLocator); if (layoutChoices.Any(l => l.SizeAndOrientation.ClassName == layout.SizeAndOrientation.ClassName)) return layout; return layoutChoices.Any() ? layoutChoices.First() : layout; }