コード例 #1
0
        public static async Task <GetResponse <TRet> > ExtractInfoFromProject <TRet>(string projPath, CancellationToken cancel, Func <Assembly, GetResponse <TRet> > getter)
        {
            if (cancel.IsCancellationRequested)
            {
                return(GetResponse <TRet> .Fail("Cancelled"));
            }

            // We copy to a temp folder, as despite all the hoops jumped through to unload the assembly,
            // it still seems to lock the dll files.  For whatever reason, though, deleting the folder
            // containing all those files seems to work out? This is definitely a hack.  Unload should
            // ideally just work out of the box.
            using var tempFolder = new TempFolder(Path.Combine(Paths.LoadingFolder, Path.GetRandomFileName()));
            if (cancel.IsCancellationRequested)
            {
                return(GetResponse <TRet> .Fail("Cancelled"));
            }
            CopyDirectory(Path.GetDirectoryName(projPath) !, tempFolder.Dir.Path, cancel);
            projPath = Path.Combine(tempFolder.Dir.Path, Path.GetFileName(projPath));
            var exec = await DotNetCommands.GetExecutablePath(projPath, cancel);

            if (exec.Failed)
            {
                return(exec.BubbleFailure <TRet>());
            }
            return(AssemblyLoading.ExecuteAndForceUnload(exec.Value, getter));
        }
コード例 #2
0
        public async Task EncryptedFileConfig()
        {
            // Restart the service specifying the configuration via
            // an encrypted physical configuration file.

            var password = "******";
            var vault    = new NeonVault(passwordName => password);

            using (var tempFolder = new TempFolder())
            {
                var decryptedPath = Path.Combine(tempFolder.Path, "decrypted");
                var encryptedPath = Path.Combine(tempFolder.Path, "encrypted");

                File.WriteAllText(decryptedPath, "From: ENCRYPTED FILE");
                vault.Encrypt(decryptedPath, encryptedPath, "foo");
                Assert.True(NeonVault.IsEncrypted(encryptedPath));

                var service = CreateService();

                service.SetConfigFilePath("/etc/complex/response", encryptedPath, passwordName => password);

                fixture.Restart(() => service);
                Assert.True(fixture.IsRunning);

                var client = fixture.GetHttpClient();

                Assert.Equal("From: ENCRYPTED FILE", await client.GetStringAsync("/"));
            }
        }
コード例 #3
0
ファイル: MO2Tests.cs プロジェクト: tr4wzified/wabbajack
        public async Task CheckValidInstallPath_ProperOverwrite()
        {
            await using var tempDir = await TempFolder.Create();

            await using var tmp = tempDir.Dir.Combine(Consts.ModOrganizer2Exe).Create();
            Assert.True(MO2Installer.CheckValidInstallPath(tempDir.Dir, downloadFolder: null).Succeeded);
        }
コード例 #4
0
        public static async Task OblivionESM_GroupMask_Export(TestingSettings settings, Target target)
        {
            var mod = OblivionMod.CreateFromBinary(
                new ModPath(
                    Mutagen.Bethesda.Oblivion.Constants.Oblivion,
                    Path.Combine(settings.DataFolderLocations.Oblivion, target.Path)));

            using var tmp = TempFolder.FactoryByAddedPath("Mutagen_Oblivion_Binary_GroupMask_Export");
            var oblivionOutputPath = Path.Combine(tmp.Dir.Path, TestingConstants.OBLIVION_ESM);

            mod.WriteToBinary(
                oblivionOutputPath,
                importMask: new GroupMask()
            {
                Npcs = true
            });
            var fileLocs = RecordLocator.GetFileLocations(oblivionOutputPath, GameRelease.Oblivion);

            using var reader = new BinaryReadStream(oblivionOutputPath);
            foreach (var rec in fileLocs.ListedRecords.Keys)
            {
                reader.Position = rec;
                var t = HeaderTranslation.ReadNextRecordType(reader);
                if (!t.Equals(Oblivion.Internals.RecordTypes.NPC_))
                {
                    throw new ArgumentException("Exported a non-NPC record.");
                }
            }
        }
コード例 #5
0
        private static async Task <Dictionary <RelativePath, T> > GatheringExtractWithOMOD <T>(Stream archive, Predicate <RelativePath> shouldExtract, Func <RelativePath, IExtractedFile, ValueTask <T> > mapfn)
        {
            var tmpFile = new TempFile();
            await tmpFile.Path.WriteAllAsync(archive);

            var dest = await TempFolder.Create();

            Utils.Log($"Extracting {(string)tmpFile.Path}");

            Framework.Settings.TempPath     = (string)dest.Dir;
            Framework.Settings.CodeProgress = new OMODProgress();

            var omod = new OMOD((string)tmpFile.Path);

            omod.GetDataFiles();
            omod.GetPlugins();

            var results = new Dictionary <RelativePath, T>();

            foreach (var file in dest.Dir.EnumerateFiles())
            {
                var path = file.RelativeTo(dest.Dir);
                if (!shouldExtract(path))
                {
                    continue;
                }

                var result = await mapfn(path, new ExtractedNativeFile(file, path));

                results.Add(path, result);
            }

            return(results);
        }
コード例 #6
0
ファイル: BasePluginTests.cs プロジェクト: mpoyhonen/polygen
        public void Test_project_configuration_file_parsing()
        {
            using (var tempFolder = new TempFolder())
            {
                const string designModelPath = "ProjectConfiguration.xml";

                tempFolder.CreateWriteTextFile(designModelPath,
                                               @"
<ProjectConfiguration xmlns='uri:polygen/1.0/project-configuration'>
    <Solution path='solution'>
        <Project name='DesignProject' path='DesignProject' type='Design' />
        <Project name='WebProject' path='WebProject' type='Web' />
    </Solution>
</ProjectConfiguration>
");

                var runner = TestRunner.Create(new Core.AutofacModule(), new AutofacModule());

                runner.Initialize();
                runner.RegisterSchemas();
                runner.ParseProjectConfiguration(tempFolder.GetPath(designModelPath));

                var projectConfiguration = runner.Context.DesignModels.GetByType(Core.CoreConstants.DesignModelType_ProjectConfiguration).FirstOrDefault() as IProjectConfiguration;

                projectConfiguration.Should().NotBeNull();
                projectConfiguration.Projects.Projects.Count().Should().Be(2);

                var projects = projectConfiguration.Projects.Projects.Select(x => (name: x.Name, path: x.SourceFolder, type: x.Type));

                projects.Should().BeEquivalentTo(new[] {
コード例 #7
0
ファイル: FilePickerTests.cs プロジェクト: rhysmdnz/wabbajack
        private static async Task <TempFolder> CreateSetFolder(FilePickerVM vm)
        {
            var temp = await TempFolder.Create();

            vm.TargetPath = temp.Dir;
            return(temp);
        }
コード例 #8
0
        public void CustomRoot()
        {
            string customRoot = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("d"));
            string testFolderPath;
            string testFilePath;

            TempFolder.Root = customRoot;

            try
            {
                using (var folder = new TempFolder())
                {
                    testFolderPath = folder.Path;

                    Assert.Equal(customRoot, Path.GetFullPath(Path.Combine(folder.Path, "..")));

                    testFilePath = Path.Combine(folder.Path, "test.txt");

                    File.WriteAllText(testFilePath, "Hello World!");
                    Assert.True(File.Exists(testFilePath));
                }

                Assert.False(Directory.Exists(testFolderPath));
                Assert.False(File.Exists(testFilePath));
            }
            finally
            {
                TempFolder.Root = null;
                Directory.Delete(customRoot);
            }
        }
コード例 #9
0
ファイル: TasksTests.cs プロジェクト: tr4wzified/wabbajack
        public async Task CanRemapGameFolder()
        {
            await using var tempFolder = await TempFolder.Create();

            var gameff = tempFolder.Dir.Combine(Consts.GameFolderFilesDir);

            gameff.CreateDirectory();

            await gameff.Combine("some_file.txt").WriteAllTextAsync("some_file");

            await gameff.Combine("steam_api64.dll").WriteAllTextAsync("steam_api");


            var meta = Game.SkyrimSpecialEdition.MetaData();
            await tempFolder.Dir.Combine(Consts.ModOrganizer2Ini)
            .WriteAllLinesAsync(
                "[General]",
                $"gameName={meta.MO2Name}",
                $"gamePath={meta.GameLocation()}",
                $"pathDouble={meta.GameLocation().ToString().Replace(@"\", @"\\")}",
                $"pathForward={meta.GameLocation().ToString().Replace(@"\", @"/")}");

            Assert.True(await MigrateGameFolder.Execute(tempFolder.Dir));

            Assert.Equal("some_file", await gameff.Combine("some_file.txt").ReadAllTextAsync());
            Assert.Equal("steam_api", await gameff.Combine("steam_api64.dll").ReadAllTextAsync());
            Assert.Equal(Hash.FromBase64("k5EWx/9Woqg="), await gameff.Combine(@"Data\Skyrim - Interface.bsa").FileHashAsync());

            var ini = tempFolder.Dir.Combine(Consts.ModOrganizer2Ini).LoadIniFile();

            Assert.Equal(gameff, (AbsolutePath)(string)ini.General.gamePath);
            Assert.Equal(gameff, (AbsolutePath)(string)ini.General.pathDouble);
            Assert.Equal(gameff, (AbsolutePath)(string)ini.General.pathForward);
        }
コード例 #10
0
        public async Task EncryptedEnvironmentFileConfig()
        {
            // Restart the service specifying by loading an encrypted file with
            // the environment variable assignment.

            var password = "******";
            var vault    = new NeonVault(passwordName => password);

            using (var tempFolder = new TempFolder())
            {
                var decryptedPath = Path.Combine(tempFolder.Path, "decrypted");
                var encryptedPath = Path.Combine(tempFolder.Path, "encrypted");

                File.WriteAllText(decryptedPath,
                                  @"# This is a comment.

WEB_RESULT=HELLO WORLD! (encrypted)
");

                var service = CreateService();

                service.LoadEnvironmentVariableFile(decryptedPath);
                vault.Encrypt(decryptedPath, encryptedPath, "foo");
                Assert.True(NeonVault.IsEncrypted(encryptedPath));

                fixture.Restart(() => service);
                Assert.True(fixture.IsRunning);

                var client = fixture.GetHttpClient();

                Assert.Equal("HELLO WORLD! (encrypted)", await client.GetStringAsync("/"));
            }
        }
コード例 #11
0
        public async Task LinesUuidTemplate()
        {
            // Verify that we can import a file with one JSON object per line,
            // generating a templated UUID key for each.

            using (var folder = new TempFolder())
            {
                var jsonFile = Path.Combine(folder.Path, "lines.json");

                File.WriteAllText(jsonFile,
                                  @"{ ""name"": ""jack"", ""age"": 10 }
{ ""name"": ""jill"", ""age"": 11 }
{ ""name"": ""spot"", ""age"": 2 }
");
                var playbook =
                    $@"
- name: test
  hosts: localhost
  tasks:
    - name: import
      neon_couchbase_import:
        servers:
          - {couchbase.Settings.Servers.First().Host}
        bucket: {bucket.Name}
        username: {couchbase.Username}
        password: {couchbase.Password}
        source: {Path.GetFileName(jsonFile)}
        format: json-lines
        key: ""ID-#UUID#""
";
                var results    = AnsiblePlayer.PlayInFolderNoGather(folder.Path, playbook);
                var taskResult = results.GetTaskResult("import");

                Assert.True(taskResult.Success);
                Assert.True(taskResult.Changed);

                // Verify

                var query = new QueryRequest($"select meta({bucket.Name}).id, {bucket.Name}.* from {bucket.Name}")
                            .ScanConsistency(ScanConsistency.RequestPlus);

                var items = await bucket.QuerySafeAsync <dynamic>(query);

                // Verify that we have all of documents.

                Assert.Equal(3, items.Count);
                Assert.Single(items.Where(doc => doc.name == "jack"));
                Assert.Single(items.Where(doc => doc.name == "jill"));
                Assert.Single(items.Where(doc => doc.name == "spot"));

                // Verify that all of the IDs look like UUIDs.  We're
                // going to assume that all entity UUIDs have the same
                // length for this test.

                var keyLength = "ID-".Length + EntityHelper.CreateUuid().Length;

                Assert.Equal(3, items.Count(doc => ((string)doc.id).Length == keyLength && ((string)doc.id).StartsWith("ID-")));
            }
        }
コード例 #12
0
        public async Task LinesInteger1000()
        {
            // Verify that we can import a file with one JSON object per line,
            // generating an integer key starting at 1000 for each.

            using (var folder = new TempFolder())
            {
                var jsonFile = Path.Combine(folder.Path, "lines.json");

                File.WriteAllText(jsonFile,
                                  @"{ ""name"": ""jack"", ""age"": 10 }
{ ""name"": ""jill"", ""age"": 11 }
{ ""name"": ""spot"", ""age"": 2 }
");
                var playbook =
                    $@"
- name: test
  hosts: localhost
  tasks:
    - name: import
      neon_couchbase_import:
        servers:
          - {couchbase.Settings.Servers.First().Host}
        bucket: {bucket.Name}
        username: {couchbase.Username}
        password: {couchbase.Password}
        source: {Path.GetFileName(jsonFile)}
        format: json-lines
        key: ""#MONO_INCR#""
        first_key: 1000
";
                var results    = AnsiblePlayer.PlayInFolderNoGather(folder.Path, playbook);
                var taskResult = results.GetTaskResult("import");

                Assert.True(taskResult.Success);
                Assert.True(taskResult.Changed);

                // Verify

                var query = new QueryRequest($"select meta({bucket.Name}).id, {bucket.Name}.* from {bucket.Name}")
                            .ScanConsistency(ScanConsistency.RequestPlus);

                var items = await bucket.QuerySafeAsync <dynamic>(query);

                // Verify that we have all of documents.

                Assert.Equal(3, items.Count);
                Assert.Single(items.Where(doc => doc.name == "jack"));
                Assert.Single(items.Where(doc => doc.name == "jill"));
                Assert.Single(items.Where(doc => doc.name == "spot"));

                // Verify that that the documents were assigned the
                // expected IDs.

                Assert.Equal("1000", (string)items.Single(doc => doc.name == "jack").id);
                Assert.Equal("1001", (string)items.Single(doc => doc.name == "jill").id);
                Assert.Equal("1002", (string)items.Single(doc => doc.name == "spot").id);
            }
        }
コード例 #13
0
ファイル: Storage.cs プロジェクト: Davidblkx/BrokenEngine
        public Storage(ISettings settings)
        {
            _settings = settings;

            PluginsFolder.Create();
            DataFolder.Create();
            TempFolder.Create();
        }
コード例 #14
0
 // helper that initializes the Program.DataConnection and invokes a callback
 protected static void WithProgramDbConnection(TempFolder tf, Action <IDataFetcherWithRelations> action)
 {
     using (System.Data.IDbConnection con = Utils.CreateDbConnection())
     {
         Utils.InitializeDbConnection(tf, con);
         action(Duplicati.GUI.Program.DataConnection);
     }
 }
コード例 #15
0
 public void Constructor_WorkingLiftFolderDoesntExist_Throws()
 {
     using (TempFolder cache = new TempFolder("LiftChangeDetectorTestsCache"))
     {
         LiftChangeDetector detector = new LiftChangeDetector("notgonnafindme", cache.Path);
         detector.Reset();
     }
 }
コード例 #16
0
        static ActiveLogBufferMap CreateActiveLogBufferMap(TempFolder tmp)
        {
            var config = new SeqForwarderConfig();
            var map    = new ActiveLogBufferMap(tmp.Path, config.Storage, config.Output, new InertLogShipperFactory());

            map.Load();
            return(map);
        }
コード例 #17
0
 public void AnEmptyMapCreatesNoFiles()
 {
     using (var tmp = new TempFolder("Buffer"))
         using (CreateActiveLogBufferMap(tmp))
         {
             Assert.Equal(0, Directory.GetFileSystemEntries(tmp.Path).Length);
         }
 }
コード例 #18
0
ファイル: MO2Tests.cs プロジェクト: tr4wzified/wabbajack
        public async Task CheckValidInstallPath_HasModlist()
        {
            await using var tempDir = await TempFolder.Create();

            await using var mo2    = tempDir.Dir.Combine("ModOrganizer.exe").Create();
            await using var molist = tempDir.Dir.Combine(((RelativePath) "modlist")).WithExtension(Consts.ModListExtension).Create();
            Assert.False(MO2Installer.CheckValidInstallPath(tempDir.Dir, downloadFolder: null).Succeeded);
        }
コード例 #19
0
 public void Constructor_WorkingLiftFolderDoesntExist_Throws()
 {
     using (TempFolder cache = new TempFolder("LiftChangeDetectorTestsCache"))
     {
         LiftChangeDetector detector = new LiftChangeDetector("notgonnafindme", cache.Path);
         detector.Reset();
     }
 }
コード例 #20
0
        public async Task SmallZipNoLongerCrashes()
        {
            var src = await DownloadMod(Game.Fallout4, 29596, 120918);

            await using var tmpFolder = await TempFolder.Create();

            await FileExtractor2.ExtractAll(src, tmpFolder.Dir);
        }
コード例 #21
0
 public ITempFolder CreateByAddedPath(string addedFolderPath, bool deleteAfter = true, bool throwIfUnsuccessfulDisposal = true)
 {
     return(TempFolder.FactoryByAddedPath(
                new DirectoryPath(Path.Combine(Path.GetTempPath(), addedFolderPath)),
                deleteAfter: deleteAfter,
                throwIfUnsuccessfulDisposal: throwIfUnsuccessfulDisposal,
                fileSystem: _fileSystem));
 }
コード例 #22
0
 public void CheckValidInstallPath_ProperOverwrite()
 {
     using (var tempDir = new TempFolder())
     {
         File.Create(Path.Combine(tempDir.Dir.FullName, $"ModOrganizer.exe"));
         Assert.IsTrue(MO2Installer.CheckValidInstallPath(tempDir.Dir.FullName, downloadFolder: null).Succeeded);
     }
 }
コード例 #23
0
 public void CheckValidInstallPath_Invalid()
 {
     // TODO: This doesn't fail, and I'm not sure why it should?
     using (var tempDir = new TempFolder())
     {
         // Assert.IsFalse(MO2Installer.CheckValidInstallPath($"{tempDir.Dir.FullName}/*", downloadFolder: null).Succeeded);
     }
 }
コード例 #24
0
        public static TempFolder CreateSetFolder(FilePickerVM vm)
        {
            var temp = new TempFolder();

            Directory.CreateDirectory(temp.Dir.FullName);
            vm.TargetPath = temp.Dir.FullName;
            return(temp);
        }
コード例 #25
0
 public void CheckValidInstallPath_ImproperOverwrite()
 {
     using (var tempDir = new TempFolder())
     {
         File.Create(Path.Combine(tempDir.Dir.FullName, $"someFile.txt"));
         Assert.IsFalse(MO2Installer.CheckValidInstallPath(tempDir.Dir.FullName, downloadFolder: null).Succeeded);
     }
 }
コード例 #26
0
        public void VariableInjectEncrypted()
        {
            var orgDirectory = Environment.CurrentDirectory;

            try
            {
                using (var manager = new KubeTestManager())
                {
                    using (var runner = new ProgramRunner())
                    {
                        using (var tempFolder = new TempFolder())
                        {
                            Environment.CurrentDirectory = tempFolder.Path;

                            var vault = new NeonVault(Program.LookupPassword);

                            // Create a test password and a [.password-name] file in the
                            // temp test folder.

                            var result = runner.Execute(Program.Main, $"password", "set", "test");
                            Assert.Equal(0, result.ExitCode);

                            //-------------------------------------------------
                            // Verify that we can inject variables into an
                            // ENCRYPTED file.

                            File.WriteAllText("test.cmd", "type %1 > output.txt");

                            File.WriteAllText("file.txt",
                                              @"
$<<TEST_A>>
$<<TEST_B>>
$<<TEST_C>>
$<<TEST_D>>
");
                            File.WriteAllBytes("file.txt", vault.Encrypt("file.txt", "test"));
                            Assert.True(NeonVault.IsEncrypted("file.txt"));

                            result = runner.Execute(Program.Main, $"run", "--TEST_A=A-VALUE", "--TEST_B=B-VALUE", "--TEST_C=C-VALUE", "--TEST_D=D-VALUE", "--", "test.cmd", "_..file.txt");
                            Assert.Equal(0, result.ExitCode);

                            var output = File.ReadAllText("output.txt");

                            Assert.Contains("A-VALUE", output);
                            Assert.Contains("B-VALUE", output);
                            Assert.Contains("C-VALUE", output);
                            Assert.Contains("D-VALUE", output);
                            File.Delete("output.txt");
                            File.Delete("file.txt");
                        }
                    }
                }
            }
            finally
            {
                Environment.CurrentDirectory = orgDirectory;
            }
        }
コード例 #27
0
 public ReflectionSettingsBundleVm(
     ICollection <ReflectionSettingsVM> settings,
     TempFolder tempFolder,
     ILogger logger)
 {
     _tempFolder = tempFolder;
     _logger     = logger;
     Settings    = settings;
 }
コード例 #28
0
 public ReflectionSettingsBundleVM(
     ICollection <ReflectionSettingsVM> settings,
     TempFolder tempFolder,
     Action <string> log)
 {
     _tempFolder = tempFolder;
     _log        = log;
     Settings    = settings;
 }
コード例 #29
0
 public void CheckValidInstallPath_HasModlist()
 {
     using (var tempDir = new TempFolder())
     {
         File.Create(Path.Combine(tempDir.Dir.FullName, $"ModOrganizer.exe"));
         File.Create(Path.Combine(tempDir.Dir.FullName, $"modlist{Consts.ModListExtension}"));
         Assert.IsFalse(MO2Installer.CheckValidInstallPath(tempDir.Dir.FullName, downloadFolder: null).Succeeded);
     }
 }
コード例 #30
0
 /// <summary>
 /// Download the associated work item attachment.
 /// </summary>
 private void Download()
 {
     if (null == _localFile)
     {
         _localFile = new FileInfo(TempFolder.CreateTemporaryFile());
         DownloadWebFile(_attachment.Uri, _workItem.WorkItem.Store.TeamProjectCollection.Credentials,
                         _localFile.FullName);
     }
 }
コード例 #31
0
        public async Task CheckValidInstallPath_OverwriteFilesInDownloads()
        {
            await using var tempDir = new TempFolder();
            var downloadsFolder = tempDir.Dir.Combine("downloads");

            downloadsFolder.CreateDirectory();
            await using var tmp = tempDir.Dir.Combine($"downloads/someFile.txt").Create();
            Assert.True(MO2Installer.CheckValidInstallPath(tempDir.Dir, downloadFolder: downloadsFolder).Succeeded);
        }
コード例 #32
0
		public void CanProvideChangeRecord_AfterReset_True()
		{
			using (TempFile working = new TempFile("<lift version='0.12'/>"))
			{
				using (TempFolder cache = new TempFolder("LiftChangeDetectorTestsCache"))
				{
					LiftChangeDetector detector = new LiftChangeDetector(working.Path, cache.Path);
					detector.Reset();
					Assert.IsTrue(detector.CanProvideChangeRecord);
				}
			}
		}
コード例 #33
0
		public void GetChangeReport_NoChanges_PerformanceTest()
		{
			using (TempFile working = new TempFile(_originalLift))
			{
				int howManyEntries = 10000;
				Debug.WriteLine("running test using "+howManyEntries.ToString()+" entries");
				using (XmlWriter w = XmlWriter.Create(working.Path))
				{
					w.WriteStartElement("lift");
					for (int i = 0; i < howManyEntries; i++)
					{
						w.WriteStartElement("entry");
						w.WriteAttributeString("id", i.ToString());
						w.WriteElementString("lexical-unit", "<form lang='x'><text>"
															 + Path.GetRandomFileName()
															 //just a way to get some random text
															 + "</text></form>");
						w.WriteElementString("gloss", "<form lang='y'><text>"
													  + Path.GetRandomFileName() //just a way to get some random text
													  + "</text></form>");
						w.WriteEndElement();
					}
					w.WriteEndElement();
				}
				using (TempFolder cache = new TempFolder("LiftChangeDetectorTestsCache"))
				{
					LiftChangeDetector detector = new LiftChangeDetector(working.Path, cache.Path);

					System.Diagnostics.Stopwatch timer = new Stopwatch();
					timer.Start();
					detector.Reset();
					timer.Stop();
					Debug.WriteLine("reset took "+timer.Elapsed.TotalSeconds+" seconds");

					timer.Reset();
					timer.Start();
					ILiftChangeReport report = detector.GetChangeReport(null);
					timer.Stop();
					Debug.WriteLine("getting report took " + timer.Elapsed.TotalSeconds + " seconds");

					timer.Reset();
					timer.Start();
					for (int i = 0; i < howManyEntries; i++)
					{
						report.GetChangeType(i.ToString());
					}
				   timer.Stop();
				   Debug.WriteLine("Time to inquire about each entry " + timer.Elapsed.TotalSeconds + " seconds");

				}
			}
		}
コード例 #34
0
		public void Version13_Changed12()
		{
			using (TempFile f = new TempFile("<lift version='0.13'></lift>"))
			{
				using (TempFolder x = new TempFolder("13-12LiftMigrator"))
				{
					TempFile toFile = x.GetPathForNewTempFile(false);

					Migrator.ReverseMigrateFrom13ToFLEx12(f.Path, toFile.Path);
					Assert.AreEqual("0.12", Validator.GetLiftVersion(toFile.Path));
				}
			}
		}
コード例 #35
0
		public void SemanticDomainWeSayStyleTwoSemDomsOnOneLine_BothConverted()
		{
			using (TempFile fromFile = new TempFile("<lift version='0.13' producer='tester'><entries>" +
			@"<entry id='color'><sense>
			<trait name='semantic_domain' value='5.2.6.2.2 Basket-ball' /><trait name='semantic_domain' value='4.2.6.2.1 Football, soccer(american)' />
				 </sense></entry></entries></lift>"))
			{
				using (TempFolder x = new TempFolder("13-12LiftMigrator"))
				{
					TempFile toFile = x.GetPathForNewTempFile(false);

					Migrator.ReverseMigrateFrom13ToFLEx12(fromFile.Path, toFile.Path);
					AssertXPathAtLeastOne("//entry/sense/trait[@name='semantic_domain']", toFile.Path);
					AssertXPathAtLeastOne("//entry/sense/trait[@value='5.2.6.2.2']", toFile.Path);
					AssertXPathAtLeastOne("//entry/sense/trait[@value='4.2.6.2.1']", toFile.Path);
				}
			}
		}
コード例 #36
0
		public void HasScientificName_MovedToOldStyleName()
		{
			using (TempFile fromFile = new TempFile("<lift version='0.13' producer='tester'>" +
				"<entry>" +
					"<trait name='MorphType' value='stem'></trait>"+
					"<sense>" +
						"<field type='scientific-name'><form lang='en'><text>word of science!</text></form></field>"+
					"</sense>" +
				"</entry>" +
				"</lift>"))
			{
				using (TempFolder x = new TempFolder("13-12LiftMigrator"))
				{
					TempFile toFile = x.GetPathForNewTempFile(false);

					Migrator.ReverseMigrateFrom13ToFLEx12(fromFile.Path, toFile.Path);
					AssertXPathAtLeastOne("//lift[@producer='tester']", toFile.Path);
					AssertXPathAtLeastOne("//entry/sense/field[@type='scientific_name']", toFile.Path);
				}
			}
		}
コード例 #37
0
        public void SemanticDomainWeSayStyle_ConvertedToFLExStyle()
        {
            using (TempFile fromFile = new TempFile("<lift version='0.13' producer='tester'>" +
                "<entry>" +
                    "<trait name='MorphType' value='stem'></trait>" +
                    "<sense>" +
                        "<trait name='semantic-domain-ddp4' value='2.5 something or other'></trait>" +
                        "<trait name=\"semantic-domain-ddp4\" value=\"3.0.2.3 something using quotes\"></trait>" +
                    "</sense>" +
                "</entry>" +
                "</lift>"))
            {
                using (TempFolder x = new TempFolder("13-12LiftMigrator"))
                {
                    TempFile toFile = x.GetPathForNewTempFile(false);

                    Migrator.ReverseMigrateFrom13ToFLEx12(fromFile.Path, toFile.Path);
                    AssertXPathAtLeastOne("//entry/sense/trait[@name='semantic_domain']", toFile.Path);
                    AssertXPathAtLeastOne("//entry/sense/trait[@value='2.5']", toFile.Path);
                    AssertXPathAtLeastOne("//entry/sense/trait[@value='3.0.2.3']", toFile.Path);
                }
            }
        }
コード例 #38
0
ファイル: VSProject.cs プロジェクト: qianlifeng/easyvsx
        /// <summary>
        /// 将指定字符串加入到一个新建的文件中去
        /// </summary>
        /// <param name="projectItems">某个项目下面的ProjectItems</param>
        /// <param name="code">文件内容</param>
        /// <param name="name">文件名(包含后缀)</param>
        public void CreateDocumentFromString(ProjectItems projectItems, string code, string name)
        {
            using (TempFolder tempFolder = new TempFolder())
            {
                string path = tempFolder.CreateTempFolder();

                using (FileStream fileStream = File.Create(path + "\\" + name))
                {
                    StreamWriter sw = new StreamWriter(fileStream);
                    sw.Write(code);
                    sw.Flush();
                    sw.Close();
                }

                CreateDocumentFromCopy(projectItems, path + "\\" + name);
            }
        }
コード例 #39
0
		public void GetChangeReport_AfterReset_NoChanges()
		{
			using (TempFile working = new TempFile(_originalLift))
			{
				using (TempFolder cache = new TempFolder("LiftChangeDetectorTestsCache"))
				{
					LiftChangeDetector detector = new LiftChangeDetector(working.Path, cache.Path);
					File.WriteAllText(working.Path, _modifiedLift);
					detector.Reset();


					 ILiftChangeReport report = detector.GetChangeReport(null);
					 Assert.AreEqual(LiftChangeReport.ChangeType.None, report.GetChangeType("one"));
					 Assert.AreEqual(LiftChangeReport.ChangeType.None, report.GetChangeType("two"));
					 Assert.AreEqual(0, report.IdsOfDeletedEntries.Count);
				}
			}
		}
コード例 #40
0
		public void GetChangeReport_AfterClear_Throws()
		{
			using (TempFile working = new TempFile("<lift version='0.12'/>"))
			{
				using (TempFolder cache = new TempFolder("LiftChangeDetectorTestsCache"))
				{
					LiftChangeDetector detector = new LiftChangeDetector(working.Path, cache.Path);
					detector.ClearCache();
					detector.GetChangeReport(new NullProgress());
				}
			}
		}