Beispiel #1
0
 public DiskExtent(ExtentDescriptor descriptor, long diskOffset, FileLocator fileLocator, FileAccess access)
 {
     _descriptor = descriptor;
     _diskOffset = diskOffset;
     _fileLocator = fileLocator;
     _access = access;
 }
Beispiel #2
0
        public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path, long capacity, Geometry geometry, Dictionary<string, string> parameters)
        {
            DiskParameters vmdkParams = new DiskParameters();
            vmdkParams.Capacity = capacity;
            vmdkParams.Geometry = geometry;

            switch (variant)
            {
                case "fixed":
                    vmdkParams.CreateType = DiskCreateType.MonolithicFlat;
                    break;
                case "dynamic":
                    vmdkParams.CreateType = DiskCreateType.MonolithicSparse;
                    break;
                case "vmfsfixed":
                    vmdkParams.CreateType = DiskCreateType.Vmfs;
                    break;
                case "vmfsdynamic":
                    vmdkParams.CreateType = DiskCreateType.VmfsSparse;
                    break;
                default:
                    throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unknown VMDK disk variant '{0}'", variant), "variant");
            }

            return Disk.Initialize(locator, path, vmdkParams);
        }
        public void TestNotFoundWithException()
        {
            FileLocator locator = new FileLocator();
            locator.Add("testdir/A");
            locator.Add("testdir/B");
            locator.Add("testdir/B/C");

            locator.Find("5");
        }
        public void TestNotFoundWithoutException()
        {
            FileLocator locator = new FileLocator();
            locator.Add("testdir/A");
            locator.Add("testdir/B");
            locator.Add("testdir/B/C");

            string file = locator.Find("5", false);
            file.Should().Be.Null();
        }
Beispiel #5
0
 public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path, long capacity, Geometry geometry, Dictionary<string, string> parameters)
 {
     switch (variant)
     {
         case "fixed":
             return Disk.InitializeFixed(locator, path, capacity, geometry);
         case "dynamic":
             return Disk.InitializeDynamic(locator, path, capacity, geometry, DynamicHeader.DefaultBlockSize);
         default:
             throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unknown VHD disk variant '{0}'", variant), "variant");
     }
 }
Beispiel #6
0
 public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path, VirtualDiskParameters diskParameters)
 {
     switch (variant)
     {
         case "fixed":
             return Disk.InitializeFixed(locator.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None), Ownership.Dispose, diskParameters.Capacity);
         case "dynamic":
             return Disk.InitializeDynamic(locator.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None), Ownership.Dispose, diskParameters.Capacity);
         default:
             throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unknown VDI disk variant '{0}'", variant), "variant");
     }
 }
 public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path, VirtualDiskParameters diskParameters)
 {
     switch (variant)
     {
         case "fixed":
             return Disk.InitializeFixed(locator, path, diskParameters.Capacity, diskParameters.Geometry);
         case "dynamic":
             throw new NotImplementedException();
         default:
             throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Unknown VHD disk variant '{0}'", variant), "variant");
     }
 }
        public void TestSimpleSearches()
        {
            FileLocator locator = new FileLocator();
            locator.Add("testdir/A");
            locator.Add("testdir/B");
            locator.Add("testdir/B/C");

            var results = new[] { 1, 2, 3, 4 }.Select(x => locator.Find(x.ToString())).ToArray();

            StringAssert.StartsWith("testdir/A", results[0]);
            StringAssert.StartsWith("testdir/A", results[1]);
            StringAssert.StartsWith("testdir/B", results[2]);
            StringAssert.StartsWith("testdir/B/C", results[3]);
        }
        public void GetBytesOfReducedImage_LargePng24bImageReduced()
        {
            // lady24b.png:        PNG image data, 24bit depth, 3632w x 3872h

            var path          = FileLocator.GetFileDistributedWithApplication(_pathToTestImages, "lady24b.png");
            var originalBytes = File.ReadAllBytes(path);
            var reducedBytes  = BookCompressor.GetBytesOfReducedImage(path);

            // Is it reduced, even tho' we switched from 24bit depth to 32bit depth?
            Assert.Greater(originalBytes.Length, reducedBytes.Length, "lady24b.png is reduced from 3632x3872");
            using (var tempFile = TempFile.WithExtension(Path.GetExtension(path)))
            {
                RobustFile.WriteAllBytes(tempFile.Path, reducedBytes);
                using (var newImage = PalasoImage.FromFileRobustly(tempFile.Path))
                    Assert.AreEqual(PixelFormat.Format32bppArgb, newImage.Image.PixelFormat, "should have switched to 32bit depth");
            }
        }
Beispiel #10
0
        public void TestMakeCorrectAlbumPaths()
        {
            // ARRANGE
            var album = new Album
            {
                Id        = 73,
                Performer = new Performer
                {
                    Name = "Foo"
                }
            };
            // ACT
            var pathlist = FileLocator.MakeAlbumImagePathlist(album);

            // ASSERT
            Assert.That(pathlist.All(p => p.EndsWith(@"Foo\Picture\73.jpg")));
        }
Beispiel #11
0
        public static bool CreateSetupMedia(
            string UUPPath,
            string LanguageCode,
            string OutputMediaPath,
            string OutputWindowsREPath,
            Common.CompressionType CompressionType,
            ProgressCallback progressCallback = null)
        {
            bool   result  = true;
            string BaseESD = null;

            (result, BaseESD) = FileLocator.LocateFilesForSetupMediaCreation(UUPPath, LanguageCode, progressCallback);
            if (!result)
            {
                goto exit;
            }

            WimCompressionType compression = WimCompressionType.None;

            switch (CompressionType)
            {
            case Common.CompressionType.LZMS:
                compression = WimCompressionType.Lzms;
                break;

            case Common.CompressionType.LZX:
                compression = WimCompressionType.Lzx;
                break;

            case Common.CompressionType.XPRESS:
                compression = WimCompressionType.Xpress;
                break;
            }

            //
            // Build installer
            //
            result = WindowsInstallerBuilder.BuildSetupMedia(BaseESD, OutputWindowsREPath, OutputMediaPath, compression, RunsAsAdministrator, LanguageCode, progressCallback);
            if (!result)
            {
                goto exit;
            }

exit:
            return(result);
        }
        private void ValidateEntryPointPath(string serviceManifestFileName, FileLocator fileLocator, string program, bool isExternalExecutable = false)
        {
            string entryPointPath = this.GetEntryPointPath(program, serviceManifestFileName);

            if (string.IsNullOrEmpty(entryPointPath))
            {
                ImageBuilderUtility.TraceAndThrowValidationErrorWithFileName(
                    TraceType,
                    serviceManifestFileName,
                    StringResources.ImageBuilderError_NullOrEmptyError,
                    "EntryPoint");
            }
            else if (entryPointPath.IndexOfAny(System.IO.Path.GetInvalidPathChars()) != -1)
            {
                ImageBuilderUtility.TraceAndThrowValidationErrorWithFileName(
                    TraceType,
                    serviceManifestFileName,
                    StringResources.ImageBuilderError_InvalidValue,
                    "EntryPoint",
                    entryPointPath);
            }
            else if (System.IO.Path.IsPathRooted(entryPointPath))
            {
                ImageBuilderUtility.TraceAndThrowValidationErrorWithFileName(
                    TraceType,
                    serviceManifestFileName,
                    StringResources.ImageBuilderError_RootedEntryPointNotSupported,
                    entryPointPath);
            }

            if (isExternalExecutable)
            {
                ImageBuilder.TraceSource.WriteInfo(
                    TraceType,
                    "EntryPointPath {0} is external executable",
                    entryPointPath);
            }
            else if (!fileLocator.FileExists(entryPointPath))
            {
                ImageBuilderUtility.TraceAndThrowValidationErrorWithFileName(
                    TraceType,
                    serviceManifestFileName,
                    StringResources.ImageBuilderError_EntryPointNotFound,
                    entryPointPath);
            }
        }
Beispiel #13
0
        public void Setup()
        {
            _folder = new TemporaryFolder("BookCollectionTests");
            //			_fileLocator = new BloomFileLocator(new CollectionSettings(), new XMatterPackFinder(new string[]{}), new string[] { FileLocator.GetDirectoryDistributedWithApplication("root"), FileLocator.GetDirectoryDistributedWithApplication("factoryCollections") });
            _fileLocator = new FileLocator(new string[] { FileLocator.GetDirectoryDistributedWithApplication("BloomBrowserUI"), FileLocator.GetDirectoryDistributedWithApplication("browserui/bookCSS"), FileLocator.GetDirectoryDistributedWithApplication("factoryCollections") });

//			_vernacularLibraryCollection = new BookCollection(_folder.Path, BookCollection.CollectionType.TheOneEditableCollection, BookFactory,
//				BookStorageFactory, null, null, new CreateFromSourceBookCommand(), new EditBookCommand());

            _vernacularLibraryCollection = new Moq.Mock <BookCollection>();
            _bookInfoList = new List <Bloom.Book.BookInfo>();
            _vernacularLibraryCollection.Setup(x => x.GetBookInfos()).Returns(_bookInfoList);
            _storeCollectionList = new Mock <SourceCollectionsList>();
            _storeCollectionList.Setup(x => x.GetSourceCollections()).Returns(() => GetStoreCollections());
            _librarySettings = new Mock <CollectionSettings>();
            _librarySettings.Setup(x => x.CollectionName).Returns(() => "Foo");
        }
Beispiel #14
0
        public void Setup()
        {
            Logger.Init();
            _folder = new TemporaryFolder("ImageServerTests");
            LocalizationManager.UseLanguageCodeFolders = true;
            var localizationDirectory = FileLocator.GetDirectoryDistributedWithApplication("localization");

            LocalizationManager.Create("fr", "Bloom", "Bloom", "1.0.0", localizationDirectory, "SIL/Bloom", null, "", new string[] { });


            ErrorReport.IsOkToInteractWithUser = false;
            _collectionPath = Path.Combine(_folder.Path, "TestCollection");
            var cs = new CollectionSettings(Path.Combine(_folder.Path, "TestCollection.bloomCollection"));

            _fileLocator = new BloomFileLocator(cs, new XMatterPackFinder(new string[] { BloomFileLocator.GetInstalledXMatterDirectory() }), ProjectContext.GetFactoryFileLocations(),
                                                ProjectContext.GetFoundFileLocations(), ProjectContext.GetAfterXMatterFileLocations());
        }
        public void TestBookSpecifiesXMatter(string xmatterBook, string expected, bool useDeviceVersionIfAvailable = false)
        {
            var fileLocator = new FileLocator(new[] { _factoryXMatter, _testXmatter });

            // Test that the XMatterHelper finds a required xmatter setting.
            var dom1 = new HtmlDom("<html>" +
                                   "<head>" +
                                   "<meta charset='UTF-8'></meta>" +
                                   "<meta name='BloomFormatVersion' content='2.0'></meta>" +
                                   "<meta name='pageTemplateSource' content='Basic Book'></meta>" +
                                   xmatterBook +
                                   "</head>" +
                                   "<body>" +
                                   "<div id='bloomDataDiv'>" +
                                   "<div data-book='contentLanguage1' lang='*'>en</div>" +
                                   "<div data-book='contentLanguage1Rtl' lang='*'>False</div>" +
                                   "<div data-book='languagesOfBook' lang='*'>English</div>" +
                                   "</div>" +
                                   "</body>" +
                                   "</html>");
            XMatterHelper helper1;

            if (xmatterBook.Contains("DoesNotExist"))
            {
                using (new NonFatalProblem.ExpectedByUnitTest())
                {
                    helper1 = new XMatterHelper(dom1, "Factory", fileLocator, useDeviceVersionIfAvailable);
                }
            }
            else
            {
                helper1 = new XMatterHelper(dom1, "Factory", fileLocator, useDeviceVersionIfAvailable);
            }
            if (xmatterBook.Contains("DoesNotExist") || string.IsNullOrEmpty(xmatterBook))
            {
                // An xmatter specification that cannot be found should be removed from the DOM.
                // An empty xmatter specification is also removed.
                Assert.That(dom1.GetMetaValue("xmatter", null), Is.Null);
            }
            else
            {
                // Verify that we may have what we want for the xmatter specification, valid or not.
                Assert.That(dom1.GetMetaValue("xmatter", null), Is.Not.Null);
            }
            Assert.That(helper1.GetStyleSheetFileName(), Is.EqualTo(expected));
        }
        public LocalizationManager CreateLocalizationManager()
        {
            var installedStringFileFolder      = Path.GetDirectoryName(FileLocator.GetFileDistributedWithApplication("SayMore.es.tmx"));
            var relativePathForWritingTmxFiles = Path.Combine(Program.kCompanyAbbrev, Application.ProductName);

            LocalizationManager.DeleteOldTmxFiles(kSayMoreLocalizationId,
                                                  Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), relativePathForWritingTmxFiles),
                                                  installedStringFileFolder);

            var localizationManager = LocalizationManager.Create(Settings.Default.UserInterfaceLanguage, kSayMoreLocalizationId,
                                                                 "SayMore", Application.ProductVersion, installedStringFileFolder, relativePathForWritingTmxFiles,
                                                                 Resources.SayMore, "*****@*****.**", "SayMore", "SIL.Archiving", "SIL.Windows.Forms.FileSystem");

            Settings.Default.UserInterfaceLanguage = LocalizationManager.UILanguageId;

            return(localizationManager);
        }
        public void CreateBookOnDiskFromTemplate_FromBasicBook_BookLineageSetToIdOfSourceBook()
        {
            var source = FileLocator.GetDirectoryDistributedWithApplication("factoryCollections", "Templates", "Basic Book");

            string bookFolderPath = _starter.CreateBookOnDiskFromTemplate(source, _projectFolder.Path);

            var jsonFile = Path.Combine(bookFolderPath, BookInfo.MetaDataFileName);

            Assert.That(File.Exists(jsonFile), "Creating a book should create a metadata json file meta.json");
            var metadata = new BookInfo(bookFolderPath, false);

            var kIdOfBasicBook = "056B6F11-4A6C-4942-B2BC-8861E62B03B3";

            Assert.That(metadata.BookLineage, Is.EqualTo(kIdOfBasicBook));
            //we should get our own id, not reuse our parent's
            Assert.That(metadata.Id, Is.Not.EqualTo(kIdOfBasicBook), "New book should get its own ID, not reuse parent's");
        }
Beispiel #18
0
        public void FileLoc_GetSonarRunnerProperties()
        {
            // 0. Set up
            string runnerRootDir = TestUtils.CreateTestSpecificFolder(this.TestContext);
            string binDir        = TestUtils.EnsureTestSpecificFolder(this.TestContext, "bin");
            string configDir     = TestUtils.EnsureTestSpecificFolder(this.TestContext, "conf");

            string runnerFile = Path.Combine(binDir, FileLocator.SonarRunnerFileName);

            File.WriteAllText(runnerFile, "dummy runner file");

            string configFile = Path.Combine(configDir, "sonar-runner.properties");

            File.WriteAllText(configFile, "dummy runner properties file");

            using (TestUtilities.EnvironmentVariableScope scope = new TestUtilities.EnvironmentVariableScope())
            {
                // 1. Runner not found on path -> nothing
                scope.SetPath("c:\\");
                string actual = FileLocator.FindDefaultSonarRunnerProperties();
                Assert.IsNull(actual, "Not expecting the runner properties file to be found");


                // 2. Runner found on path but no properties file -> not found
                scope.SetPath("c:\\;" + binDir);
                File.Delete(configFile);

                using (new AssertIgnoreScope())
                {
                    actual = FileLocator.FindDefaultSonarRunnerProperties();
                }
                Assert.IsNull(actual, "Not expecting the runner properties file to be found");


                // 3. Runner found on path and config file exists in expected relative location -> found

                // Create the properties file in the expected location
                configFile = Path.Combine(configDir, "sonar-runner.properties");
                File.WriteAllText(configFile, "dummy runner properties file");

                actual = FileLocator.FindDefaultSonarRunnerProperties();
                Assert.IsNotNull(actual, "Expecting the runner properties file to be found");
                Assert.AreEqual(configFile, actual, "Unexpected file name returned");
            }
        }
Beispiel #19
0
        public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path,
                                               VirtualDiskParameters diskParameters)
        {
            switch (variant)
            {
            case "fixed":
                return(Disk.InitializeFixed(locator, path, diskParameters.Capacity, diskParameters.Geometry));

            case "dynamic":
                return(Disk.InitializeDynamic(locator, path, diskParameters.Capacity,
                                              FileParameters.DefaultDynamicBlockSize));

            default:
                throw new ArgumentException(
                          string.Format(CultureInfo.InvariantCulture, "Unknown VHD disk variant '{0}'", variant),
                          nameof(variant));
            }
        }
Beispiel #20
0
        /// <summary>
        /// Play song currently active in the radio
        /// </summary>
        public async Task PlayCurrentSong()
        {
            if (_player.SongPlaybackState != PlaybackState.Stop)
            {
                _player.Stop();
            }

            var songpath = FileLocator.FindSongPath(_radio.CurrentSong);

            try
            {
                _player.Play(songpath);
            }
            catch (Exception)
            {
                await _radio.MoveToNextSongAsync();
            }
        }
Beispiel #21
0
        /// <summary>
        /// Creates a new virtual disk that is a linked clone of an existing disk.
        /// </summary>
        /// <param name="fileSystem">The file system to create the VMDK on</param>
        /// <param name="path">The path to the new disk</param>
        /// <param name="type">The type of the new disk</param>
        /// <param name="parent">The disk to clone</param>
        /// <returns>The new virtual disk</returns>
        public static DiskImageFile InitializeDifferencing(DiscFileSystem fileSystem, string path, DiskCreateType type, string parent)
        {
            if (type != DiskCreateType.MonolithicSparse && type != DiskCreateType.TwoGbMaxExtentSparse && type != DiskCreateType.VmfsSparse)
            {
                throw new ArgumentException("Differencing disks must be sparse", "type");
            }

            string      basePath      = Path.GetDirectoryName(path);
            FileLocator locator       = new DiscFileLocator(fileSystem, basePath);
            FileLocator parentLocator = locator.GetRelativeLocator(Path.GetDirectoryName(parent));

            using (DiskImageFile parentFile = new DiskImageFile(parentLocator, Path.GetFileName(parent), FileAccess.Read))
            {
                DescriptorFile baseDescriptor = CreateDifferencingDiskDescriptor(type, parentFile, parent);

                return(DoInitialize(locator, Path.GetFileName(path), parentFile.Capacity, type, baseDescriptor));
            }
        }
Beispiel #22
0
        public TestBook(string testName, string content)
        {
            _folder    = new TemporaryFolder(testName);
            BookFolder = _folder.FolderPath;
            BookPath   = Path.Combine(_folder.FolderPath, testName + ".htm");
            File.WriteAllText(BookPath, content);
            var settings    = CreateDefaultCollectionsSettings();
            var codeBaseDir = BloomFileLocator.GetCodeBaseFolder();
            // This is minimal...if the content doesn't specify xmatter Bloom defaults to Traditional
            // and needs the file locator to know this folder so it can find it.
            // May later need to include more folders or allow the individual tests to do so.
            var locator = new FileLocator(new string[] { codeBaseDir + "/../browser/templates/xMatter" });
            var storage = new BookStorage(BookFolder, locator, new BookRenamedEvent(), settings);
            // very minimal...enhance if we need to test something that can really find source collections.
            var templatefinder = new SourceCollectionsList();

            Book = new Bloom.Book.Book(new BookInfo(BookFolder, true), storage, templatefinder, settings, new PageSelection(), new PageListChangedEvent(), new BookRefreshEvent());
        }
        public override IDownloadingFile Download(INetDiskFile from, FileLocator to)
        {
            var downloader = FileTransferService
                             .GetDownloaderBuilder()
                             .UseSixCloudConfigure()
                             .Configure(localPath => localPath.GetUniqueLocalPath(path => File.Exists(path) || File.Exists($"{path}{Constants.DownloadInfoFileExtension}")))
                             .From(new RemotePathProvider(this, from.Path))
                             .To(Path.Combine(to, from.Path.FileName))
                             .Build();

            var result = DownloadingFile.Create(this, from, downloader);

            SaveDownloadingFile(result);

            Logger.Info($"Download: from {from.Path.FileName} to {downloader.Context.LocalPath}. ");

            return(result);
        }
Beispiel #24
0
        /// <summary>Get the path and file name of the RAMP executable file</summary>
        public static string GetRampExeFileLocation()
        {
            string       exeFile;
            const string rampFileExtension = ".ramp";

            if (ArchivingDlgViewModel.IsMono)
            {
                exeFile = FileLocator.LocateInProgramFiles("RAMP", true);
            }
            else
            {
                exeFile = FileLocator.GetFromRegistryProgramThatOpensFileType(rampFileExtension) ??
                          FileLocator.LocateInProgramFiles("ramp.exe", true, "ramp");
            }

            // make sure the file exists
            return(!File.Exists(exeFile) ? null : new FileInfo(exeFile).FullName);
        }
        /// <summary>
        /// This can be used to find the best localized file when there is only one file with the given name,
        /// and the file is part of the files distributed with Bloom (i.e., not something in a downloaded template).
        /// </summary>
        public static string GetBestLocalizableFileDistributedWithApplication(bool existenceOfEnglishVersionIsOptional, params string[] partsOfEnglishFilePath)
        {
            // at this time, FileLocator does not have a way for the app to actually tell it where to find things distributed
            // with the application...
            var englishPath = FileLocator.GetFileDistributedWithApplication(true, partsOfEnglishFilePath);

            // ... so if it doesn't find it, we have to keep looking
            if (string.IsNullOrWhiteSpace(englishPath))
            {
                //this one will throw if we still can't find it and existenceOfEnglishVersionIsOptional is false
                englishPath = BloomFileLocator.GetBrowserFile(existenceOfEnglishVersionIsOptional, partsOfEnglishFilePath);
            }

            if (!RobustFile.Exists(englishPath))
            {
                return(englishPath);                // just return whatever the original GetFileDistributedWithApplication gave. "", null, whatever it is.
            }
            return(BloomFileLocator.GetBestLocalizedFile(englishPath));
        }
        private static void UpdateExtensions()
        {
            var extensions = new Dictionary <string, string>();

#if !MONO
            extensions.Add("eol", "");             //for converting line endings on windows machines
#endif
            extensions.Add("hgext.graphlog", "");  //for more easily readable diagnostic logs
            extensions.Add("convert", "");         //for catastrophic repair in case of repo corruption
            string fixUtfFolder = FileLocator.GetDirectoryDistributedWithApplication(false, "MercurialExtensions", "fixutf8");
            if (!string.IsNullOrEmpty(fixUtfFolder))
            {
                extensions.Add("fixutf8", Path.Combine(fixUtfFolder, "fixutf8.py"));
            }

            var doc = HgRepository.GetMercurialConfigInMercurialFolder();
            SetExtensions(doc, extensions);
            doc.SaveAndThrowIfCannot();
        }
Beispiel #27
0
        public DataleveranseXmlGreier()
        {
            var schemaPath   = FileLocator.FindDirectoryInTree(Config.Settings.SchemaSubdirectory);
            var xsdPath      = Path.Combine(schemaPath, "NiNCoreDataleveranse.xsd");
            var xsdGridPath  = Path.Combine(schemaPath, "NiNCoreGridleveranse.xsd");
            var xsdCachePath = Path.Combine(schemaPath, "cache");

            var gmlXmlResolver = CreateGmlXmlResolver(xsdCachePath);

            var schemas = new XmlSchemaSet {
                XmlResolver = gmlXmlResolver
            };

            var xsdMarkup = File.ReadAllText(xsdPath);

            var xsdDocument   = XDocument.Parse(xsdMarkup);
            var xsdAttributes = GetAttributes(xsdDocument.Root);
            var xsdNamespace  = xsdAttributes.ContainsKey("xmlns:nin")
                ? xsdAttributes["xmlns:nin"].Replace("\"", "")
                : "";

            var stringReader = new StringReader(xsdMarkup);
            var xmlReader    = XmlReader.Create(stringReader);

            schemas.Add(xsdNamespace, xmlReader);

            dataleveranseValiderer = new DataleveranseValiderer(schemas);

            schemas = new XmlSchemaSet {
                XmlResolver = gmlXmlResolver
            };

            xsdMarkup     = File.ReadAllText(xsdGridPath);
            xsdDocument   = XDocument.Parse(xsdMarkup);
            xsdAttributes = GetAttributes(xsdDocument.Root);
            xsdNamespace  = xsdAttributes.ContainsKey("xmlns:nin") ? xsdAttributes["xmlns:nin"].Replace("\"", "") : "";

            stringReader = new StringReader(xsdMarkup);
            xmlReader    = XmlReader.Create(stringReader);
            schemas.Add(xsdNamespace, xmlReader);

            gridValidator = new DataleveranseValiderer(schemas);
        }
        /// <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);
        }
Beispiel #29
0
        private async Task SavePerformerAsync()
        {
            var performer = Mapper.Map <Performer>(Performer);

            performer.CountryId = SelectedCountryId;

            var result = await _performerService.UpdatePerformerAsync(_performer.Id, performer);

            if (result.Type != ResultType.Ok)
            {
                MessageBox.Show(result.Error);
                _performer.Name = _initialName;
                return;
            }

            _performer.Country   = Mapper.Map <Country>(result.Data.Country);
            _performer.ImagePath = FileLocator.GetPerformerImagePath(performer);
            RaisePropertyChanged("Performer");
        }
        /// <summary>
        /// Creates the sonar runner file structure required for the
        /// product "FileLocator" code to work and create a sonar-runner properties
        /// file containing the specified host url setting
        /// </summary>
        /// <returns>Returns the path of the runner bin directory</returns>
        private string CreateRunnerFilesInScope(EnvironmentVariableScope scope)
        {
            string runnerConfDir = TestUtils.EnsureTestSpecificFolder(this.TestContext, "conf");
            string runnerBinDir  = TestUtils.EnsureTestSpecificFolder(this.TestContext, "bin");

            // Create a sonar-runner.properties file
            string runnerExe = Path.Combine(runnerBinDir, "sonar-runner.bat");

            File.WriteAllText(runnerExe, "dummy content - only the existence of the file matters");
            string configFile = Path.Combine(runnerConfDir, ActualRunnerPropertiesFileName);

            File.WriteAllText(configFile, "# dummy properties file content");

            scope.SetPath(runnerBinDir);

            Assert.IsFalse(string.IsNullOrWhiteSpace(FileLocator.FindDefaultSonarRunnerExecutable()), "Test setup error: failed to locate the created runner executable file");

            return(configFile);
        }
Beispiel #31
0
        /// ------------------------------------------------------------------------------------
        internal static void Load()
        {
            if (s_dbAccessInfo == null)
            {
                // Find the file that contains information about connecting to an FW database.
                s_accessInfoFile = FileLocator.GetFileDistributedWithApplication(App.ConfigFolderName, "FwDBAccessInfo.xml");
                s_dbAccessInfo   = XmlSerializationHelper.DeserializeFromFile <FwDBAccessInfo>(s_accessInfoFile);
            }

            if (s_dbAccessInfo == null && ShowMsgOnFileLoadFailure)
            {
                ErrorReport.NotifyUserOfProblem(LocalizationManager.GetString(
                                                    "Miscellaneous.Messages.DataSourceReading.LoadingDBAccessInfoErorMsg",
                                                    "The file that contains information to access FieldWork databases " +
                                                    "older than version 7.x '{0}' is either missing or corrupt. Until " +
                                                    "this problem is corrected, FieldWorks data sources cannot be " +
                                                    "accessed or added as data sources."), s_accessInfoFile);
            }
        }
        public void Setup()
        {
            _librarySettings = new Moq.Mock <CollectionSettings>();
            _librarySettings.SetupGet(x => x.IsSourceCollection).Returns(false);
            _librarySettings.SetupGet(x => x.Language1Iso639Code).Returns("xyz");
            _librarySettings.SetupGet(x => x.Language2Iso639Code).Returns("fr");
            _librarySettings.SetupGet(x => x.Language3Iso639Code).Returns("es");
            _librarySettings.SetupGet(x => x.XMatterPackName).Returns("Factory");
            ErrorReport.IsOkToInteractWithUser = false;
            _projectFolder = new TemporaryFolder("BookStarterTests_ProjectCollection");
            var collectionSettings = new CollectionSettings(Path.Combine(_projectFolder.Path, "test.bloomCollection"));

            var xmatterFinder = new XMatterPackFinder(new [] { FileLocator.GetDirectoryDistributedWithApplication("xMatter") });

            _fileLocator = new BloomFileLocator(collectionSettings, xmatterFinder, ProjectContext.GetFactoryFileLocations(), ProjectContext.GetFoundFileLocations());


            _starter = new BookStarter(_fileLocator, dir => new BookStorage(dir, _fileLocator, new BookRenamedEvent(), collectionSettings), _librarySettings.Object);
            _shellCollectionFolder = new TemporaryFolder("BookStarterTests_ShellCollection");
        }
Beispiel #33
0
        internal DiskImageFile(FileLocator locator, string path, FileAccess access)
        {
            FileShare share = access == FileAccess.Read ? FileShare.Read : FileShare.None;

            _fileStream = locator.Open(path, FileMode.Open, access, share);
            _ownsStream = Ownership.Dispose;

            try
            {
                _fileLocator = locator.GetRelativeLocator(locator.GetDirectoryFromPath(path));
                _fileName    = locator.GetFileFromPath(path);

                Initialize();
            }
            catch
            {
                _fileStream.Dispose();
                throw;
            }
        }
Beispiel #34
0
        public static void ShowHelpTopic(string topicLink)
        {
            string helpFilePath = FileLocator.GetFileDistributedWithApplication(true, "WeSay_Helps.chm");

            if (String.IsNullOrEmpty(helpFilePath))
            {
                string commonDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                helpFilePath = Path.Combine(commonDataFolder, Path.Combine("wesay", "WeSay_Helps.chm"));
            }
            if (File.Exists(helpFilePath))
            {
                //var uri = new Uri(helpFilePath);
                Help.ShowHelp(new Label(), helpFilePath, topicLink);
            }
            else
            {
                Process.Start("http://wesay.palaso.org/help/");
            }
            UsageReporter.SendNavigationNotice("Help: " + topicLink);
        }
        /// <summary>
        /// Initializes a new instance of the DiskImageFile class.
        /// </summary>
        /// <param name="fileLocator">An object to open the file and any extents.</param>
        /// <param name="file">The file name.</param>
        /// <param name="access">The type of access desired.</param>
        internal DiskImageFile(FileLocator fileLocator, string file, FileAccess access)
        {
            _access = access;

            FileAccess fileAccess = FileAccess.Read;
            FileShare  fileShare  = FileShare.Read;

            if (_access != FileAccess.Read)
            {
                fileAccess = FileAccess.ReadWrite;
                fileShare  = FileShare.None;
            }

            Stream fileStream = null;

            try
            {
                fileStream = fileLocator.Open(file, FileMode.Open, fileAccess, fileShare);
                LoadDescriptor(fileStream);

                // For monolithic disks, keep hold of the stream - we won't try to use the file name
                // from the embedded descriptor because the file may have been renamed, making the
                // descriptor out of date.
                if (_descriptor.CreateType == DiskCreateType.StreamOptimized ||
                    _descriptor.CreateType == DiskCreateType.MonolithicSparse)
                {
                    _monolithicStream     = fileStream;
                    _ownsMonolithicStream = Ownership.Dispose;
                    fileStream            = null;
                }
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Dispose();
                }
            }

            _fileLocator = fileLocator.GetRelativeLocator(fileLocator.GetDirectoryFromPath(file));
        }
Beispiel #36
0
        internal static DiskImageFile InitializeDynamic(FileLocator locator, string path, long capacity, long blockSize)
        {
            DiskImageFile result = null;
            Stream        stream = locator.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);

            try
            {
                InitializeDynamicInternal(stream, capacity, blockSize);
                result = new DiskImageFile(locator, path, stream, Ownership.Dispose);
                stream = null;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }

            return(result);
        }
        public void Setup()
        {
            _collectionSettings = new CollectionSettings(new NewCollectionSettings()
            {
                PathToSettingsFile  = CollectionSettings.GetPathForNewSettings(new TemporaryFolder("BookDataTests").Path, "test"),
                Language1Iso639Code = "xyz",
                Language2Iso639Code = "en",
                Language3Iso639Code = "fr"
            });
            ErrorReport.IsOkToInteractWithUser = false;

            var localizationDirectory = FileLocator.GetDirectoryDistributedWithApplication("localization");

            _localizationManager = LocalizationManager.Create("fr", "Bloom", "Bloom", "1.0.0", localizationDirectory, "SIL/Bloom",
                                                              null, "", new string[] {});
            _palasoLocalizationManager = LocalizationManager.Create("fr", "Palaso", "Palaso", "1.0.0", localizationDirectory, "SIL/Bloom",
                                                                    null, "", new string[] { });

            _brandingFolder            = new TemporaryFolder("unitTestBrandingFolder");
            _pathToBrandingSettingJson = _brandingFolder.Combine("settings.json");
        }
Beispiel #38
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Get the path and file name of the Arbil executable file
        /// </summary>
        /// <returns>The full name of the Arbil executable file</returns>
        /// ------------------------------------------------------------------------------------
        public static string GetExeFileLocation()
        {
            string exeFile;

            if (ArchivingDlgViewModel.IsMono)
            {
                exeFile = FileLocator.LocateInProgramFiles("RAMP", true);
            }
            else
            {
                exeFile = FileLocator.LocateInProgramFiles("arbil-stable.exe", true, "arbil");
            }

            // make sure the file exists
            if (!File.Exists(exeFile))
            {
                throw new FileNotFoundException("The Arbil executable file was not found.");
            }

            return(new FileInfo(exeFile).FullName);
        }
Beispiel #39
0
        public override VirtualDisk OpenDisk(FileLocator locator, string path, string extraInfo, Dictionary<string, string> parameters, FileAccess access)
        {
            VirtualMachine machine = new VirtualMachine(locator.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read), Ownership.Dispose);

            int diskIndex;
            if (!int.TryParse(extraInfo, out diskIndex))
            {
                diskIndex = 0;
            }

            int i = 0;
            foreach (var disk in machine.Disks)
            {
                if (i == diskIndex)
                {
                    return disk;
                }

                ++i;
            }

            return null;
        }
Beispiel #40
0
 public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path, VirtualDiskParameters diskParameters)
 {
     return Disk.Initialize(locator.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None), Ownership.Dispose, diskParameters.Capacity, diskParameters.Geometry);
 }
Beispiel #41
0
 public override VirtualDisk OpenDisk(FileLocator locator, string path, FileAccess access)
 {
     FileShare share = access == FileAccess.Read ? FileShare.Read : FileShare.None;
     return new Disk(locator.Open(path, FileMode.Open, access, share), Ownership.Dispose);
 }
Beispiel #42
0
        private static DiskImageFile DoInitialize(FileLocator fileLocator, string file, long capacity, DiskCreateType type, DescriptorFile baseDescriptor)
        {
            if (type == DiskCreateType.MonolithicSparse)
            {
                // MonolithicSparse is a special case, the descriptor is embedded in the file itself...
                using (Stream fs = fileLocator.Open(file, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
                {
                    long descriptorStart;
                    CreateExtent(fs, capacity, ExtentType.Sparse, 10 * Sizes.OneKiB, out descriptorStart);

                    ExtentDescriptor extent = new ExtentDescriptor(ExtentAccess.ReadWrite, capacity / Sizes.Sector, ExtentType.Sparse, file, 0);
                    fs.Position = descriptorStart * Sizes.Sector;
                    baseDescriptor.Extents.Add(extent);
                    baseDescriptor.Write(fs);
                }
            }
            else
            {
                ExtentType extentType = CreateTypeToExtentType(type);
                long totalSize = 0;
                List<ExtentDescriptor> extents = new List<ExtentDescriptor>();
                if (type == DiskCreateType.MonolithicFlat || type == DiskCreateType.VmfsSparse || type == DiskCreateType.Vmfs)
                {
                    string adornment = "flat";
                    if(type == DiskCreateType.VmfsSparse)
                    {
                        adornment = string.IsNullOrEmpty(baseDescriptor.ParentFileNameHint) ? "sparse" : "delta";
                    }

                    string fileName = AdornFileName(file, adornment);

                    using(Stream fs = fileLocator.Open(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
                    {
                        CreateExtent(fs, capacity, extentType);
                        extents.Add(new ExtentDescriptor(ExtentAccess.ReadWrite, capacity / Sizes.Sector, extentType, fileName, 0));
                        totalSize = capacity;
                    }
                }
                else if (type == DiskCreateType.TwoGbMaxExtentFlat || type == DiskCreateType.TwoGbMaxExtentSparse)
                {
                    int i = 1;
                    while (totalSize < capacity)
                    {
                        string adornment;
                        if (type == DiskCreateType.TwoGbMaxExtentSparse)
                        {
                            adornment = string.Format(CultureInfo.InvariantCulture, "s{0:x3}", i);
                        }
                        else
                        {
                            adornment = string.Format(CultureInfo.InvariantCulture, "{0:x6}", i);
                        }

                        string fileName = AdornFileName(file, adornment);

                        using (Stream fs = fileLocator.Open(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
                        {
                            long extentSize = Math.Min(2 * Sizes.OneGiB - Sizes.OneMiB, capacity - totalSize);
                            CreateExtent(fs, extentSize, extentType);
                            extents.Add(new ExtentDescriptor(ExtentAccess.ReadWrite, extentSize / Sizes.Sector, extentType, fileName, 0));
                            totalSize += extentSize;
                        }

                        ++i;
                    }
                }
                else
                {
                    throw new NotSupportedException("Creating disks of this type is not supported");
                }

                using (Stream fs = fileLocator.Open(file, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
                {
                    baseDescriptor.Extents.AddRange(extents);
                    baseDescriptor.Write(fs);
                }
            }

            return new DiskImageFile(fileLocator, file, FileAccess.ReadWrite);
        }
Beispiel #43
0
        /// <summary>
        /// Creates a new instance from a file on disk.
        /// </summary>
        /// <param name="path">The path to the disk</param>
        /// <param name="access">The desired access to the disk</param>
        public DiskImageFile(string path, FileAccess access)
        {
            _access = access;

            FileAccess fileAccess = FileAccess.Read;
            FileShare fileShare = FileShare.Read;
            if (_access != FileAccess.Read)
            {
                fileAccess = FileAccess.ReadWrite;
                fileShare = FileShare.None;
            }

            FileStream fileStream = null;
            try
            {
                fileStream = new FileStream(path, FileMode.Open, fileAccess, fileShare);
                LoadDescriptor(fileStream);

                // For monolithic disks, keep hold of the stream - we won't try to use the file name
                // from the embedded descriptor because the file may have been renamed, making the 
                // descriptor out of date.
                if (_descriptor.CreateType == DiskCreateType.StreamOptimized || _descriptor.CreateType == DiskCreateType.MonolithicSparse)
                {
                    _monolithicStream = fileStream;
                    _ownsMonolithicStream = Ownership.Dispose;
                    fileStream = null;
                }
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Dispose();
                }
            }

            _fileLocator = new LocalFileLocator(Path.GetDirectoryName(path));
        }
Beispiel #44
0
 public override VirtualDiskLayer OpenDiskLayer(FileLocator locator, string path, FileAccess access)
 {
     FileMode mode = (access == FileAccess.Read) ? FileMode.Open : FileMode.OpenOrCreate;
     FileShare share = (access == FileAccess.Read) ? FileShare.Read : FileShare.None;
     return new DiskImageFile(locator.Open(path, mode, access, share), Ownership.Dispose);
 }
Beispiel #45
0
 public override VirtualDisk OpenDisk(FileLocator locator, string path, FileAccess access)
 {
     return OpenDisk(locator, path, string.Empty, new Dictionary<string, string>(), access);
 }
Beispiel #46
0
 public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path, VirtualDiskParameters diskParameters)
 {
     throw new NotSupportedException();
 }
Beispiel #47
0
 /// <summary>
 /// Initializes a new instance of the Disk class.  Differencing disks are supported.
 /// </summary>
 /// <param name="file">The file containing the disk</param>
 /// <param name="ownsFile">Indicates if the new instance should control the lifetime of the file.</param>
 /// <param name="parentLocator">Object used to locate the parent disk</param>
 /// <param name="parentPath">Path to the parent disk (if required)</param>
 private Disk(DiskImageFile file, Ownership ownsFile, FileLocator parentLocator, string parentPath)
 {
     _files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>();
     _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, ownsFile));
     if (file.NeedsParent)
     {
         _files.Add(
             new DiscUtils.Tuple<DiskImageFile, Ownership>(
                 new DiskImageFile(parentLocator, parentPath, FileAccess.Read),
                 Ownership.Dispose));
         ResolveFileChain();
     }
 }
Beispiel #48
0
        /// <summary>
        /// Gets the locations of the parent file.
        /// </summary>
        /// <param name="fileLocator">The file locator to use.</param>
        /// <returns>Array of candidate file locations.</returns>
        private string[] GetParentLocations(FileLocator fileLocator)
        {
            if (!NeedsParent)
            {
                throw new InvalidOperationException("Only differencing disks contain parent locations");
            }

            if (fileLocator == null)
            {
                // Use working directory by default
                fileLocator = new LocalFileLocator(string.Empty);
            }

            List<string> absPaths = new List<string>(8);
            List<string> relPaths = new List<string>(8);
            foreach (var pl in _dynamicHeader.ParentLocators)
            {
                if (pl.PlatformCode == ParentLocator.PlatformCodeWindowsAbsoluteUnicode
                    || pl.PlatformCode == ParentLocator.PlatformCodeWindowsRelativeUnicode)
                {
                    _fileStream.Position = pl.PlatformDataOffset;
                    byte[] buffer = Utilities.ReadFully(_fileStream, pl.PlatformDataLength);
                    string locationVal = Encoding.Unicode.GetString(buffer);

                    if (pl.PlatformCode == ParentLocator.PlatformCodeWindowsAbsoluteUnicode)
                    {
                        absPaths.Add(locationVal);
                    }
                    else
                    {
                        relPaths.Add(fileLocator.ResolveRelativePath(locationVal));
                    }
                }
            }

            // Order the paths to put absolute paths first
            List<string> paths = new List<string>(absPaths.Count + relPaths.Count + 1);
            paths.AddRange(absPaths);
            paths.AddRange(relPaths);

            // As a back-up, try to infer from the parent name...
            if (paths.Count == 0)
            {
                paths.Add(fileLocator.ResolveRelativePath(_dynamicHeader.ParentUnicodeName));
            }

            return paths.ToArray();
        }
Beispiel #49
0
 internal Disk(FileLocator layerLocator, string path, FileAccess access)
 {
     _path = path;
     _files = new List<ThinkAway.Tuple<VirtualDiskLayer, Ownership>>();
     _files.Add(new ThinkAway.Tuple<VirtualDiskLayer, Ownership>(new DiskImageFile(layerLocator, path, access), Ownership.Dispose));
     ResolveFileChain();
 }
Beispiel #50
0
 public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path, long capacity, Geometry geometry, Dictionary<string, string> parameters)
 {
     return Disk.Initialize(locator.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None), Ownership.Dispose, capacity, geometry);
 }
Beispiel #51
0
 public override VirtualDisk OpenDisk(FileLocator locator, string path, FileAccess access)
 {
     OpticalFormat format = path.EndsWith(".bin", StringComparison.OrdinalIgnoreCase) ? OpticalFormat.Mode2 : OpticalFormat.Mode1;
     FileShare share = access == FileAccess.Read ? FileShare.Read : FileShare.None;
     return new Disc(locator.Open(path, FileMode.Open, access, share), Ownership.Dispose, format);
 }
Beispiel #52
0
 public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path, VirtualDiskParameters diskParameters)
 {
     DiskParameters vmdkParams = new DiskParameters(diskParameters);
     vmdkParams.CreateType = VariantToCreateType(variant);
     return Disk.Initialize(locator, path, vmdkParams);
 }
Beispiel #53
0
 public override VirtualDiskLayer OpenDiskLayer(FileLocator locator, string path, FileAccess access)
 {
     return null;
 }
Beispiel #54
0
 internal static Disk InitializeDynamic(FileLocator fileLocator, string path, long capacity, Geometry geometry, long blockSize)
 {
     return new Disk(DiskImageFile.InitializeDynamic(fileLocator, path, capacity, geometry, blockSize), Ownership.Dispose);
 }
Beispiel #55
0
 /// <summary>
 /// Initializes a new instance of the Disk class.  Differencing disks are supported.
 /// </summary>
 /// <param name="locator">The locator to access relative files</param>
 /// <param name="path">The path to the disk image</param>
 /// <param name="access">The access requested to the disk</param>
 internal Disk(FileLocator locator, string path, FileAccess access)
 {
     DiskImageFile file = new DiskImageFile(locator, path, access);
     _files = new List<DiscUtils.Tuple<DiskImageFile, Ownership>>();
     _files.Add(new DiscUtils.Tuple<DiskImageFile, Ownership>(file, Ownership.Dispose));
     ResolveFileChain();
 }
Beispiel #56
0
 internal static Disk Initialize(FileLocator fileLocator, string path, DiskParameters parameters)
 {
     return new Disk(DiskImageFile.Initialize(fileLocator, path, parameters), Ownership.Dispose);
 }
Beispiel #57
0
 internal static Disk InitializeFixed(FileLocator fileLocator, string path, long capacity, Geometry geometry)
 {
     return new Disk(DiskImageFile.InitializeFixed(fileLocator, path, capacity, geometry), Ownership.Dispose);
 }
Beispiel #58
0
        /// <summary>
        /// Creates a new virtual disk at the specified path.
        /// </summary>
        /// <param name="fileLocator">The object used to locate / create the component files.</param>
        /// <param name="path">The name of the VMDK to create.</param>
        /// <param name="parameters">The desired parameters for the new disk.</param>
        /// <returns>The newly created disk image</returns>
        internal static DiskImageFile Initialize(FileLocator fileLocator, string path, DiskParameters parameters)
        {
            if (parameters.Capacity <= 0)
            {
                throw new ArgumentException("Capacity must be greater than zero", "parameters");
            }

            Geometry geometry = parameters.Geometry ?? DefaultGeometry(parameters.Capacity);

            Geometry biosGeometry;
            if (parameters.BiosGeometry != null)
            {
                biosGeometry = parameters.BiosGeometry;
            }
            else
            {
                biosGeometry = Geometry.MakeBiosSafe(geometry, parameters.Capacity);
            }


            DiskAdapterType adapterType = (parameters.AdapterType == DiskAdapterType.None) ? DiskAdapterType.LsiLogicScsi : parameters.AdapterType;
            DiskCreateType createType = (parameters.CreateType == DiskCreateType.None) ? DiskCreateType.MonolithicSparse : parameters.CreateType;

            DescriptorFile baseDescriptor = CreateSimpleDiskDescriptor(geometry, biosGeometry, createType, adapterType);

            return DoInitialize(fileLocator, path, parameters.Capacity, createType, baseDescriptor);
        }
Beispiel #59
0
 public override VirtualDiskLayer OpenDiskLayer(FileLocator locator, string path, FileAccess access)
 {
     return new DiskImageFile(locator, path, access);
 }
Beispiel #60
0
 public override VirtualDisk OpenDisk(FileLocator locator, string path, FileAccess access)
 {
     return new Disk(locator, path, access);
 }