// POST /repository public async Task<HttpResponseMessage> Post() { if (!this.Request.Content.IsMimeMultipartContent("form-data")) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); List<FileDescriptor> ret = new List<FileDescriptor>(); using (var tmp = new TempDir()) { MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(tmp.Path); var bodypart = await this.Request.Content.ReadAsMultipartAsync(provider); foreach (var fileName in provider.FileData) { var fi = new FileInfo(fileName.LocalFileName); try { var fd = FileDescriptor.Load(fi); File.Copy( fi.FullName, Path.Combine(AppConfig.RepositoryPath, fi.Name)); ret.Add(fd); } catch (Exception ex) { // log TraceSources.RepositoryControllerSource.TraceError( "An exception of type {2} occured while processing '{0}': {1}", fileName, ex.ToString(), ex.GetType().Name); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); } } } string reason = ret.Aggregate( new StringBuilder(), (builder, descriptor) => (builder.Length == 0 ? builder : builder.Append(", ")) .AppendFormat( "{{A:{0}, V:{1}}}", descriptor.Assembly, descriptor.Version), builder => builder.ToString()); if (ret.Count > 0) ContentManager.Instance.QueueRebuild("Added assemblies: " + reason); return Request.CreateResponse(HttpStatusCode.Accepted, ret.AsEnumerable()); }
public void TestConnectionInstanceIDHandling(string appName) { var pathToMsApp = Path.Combine(Environment.CurrentDirectory, "Apps", appName); Assert.IsTrue(File.Exists(pathToMsApp)); var(msApp, errors) = CanvasDocument.LoadFromMsapp(pathToMsApp); errors.ThrowOnErrors(); // Testing if conn instance id is added to entropy Assert.IsNotNull(msApp._entropy.LocalConnectionIDReferences); using var sourcesTempDir = new TempDir(); var sourcesTempDirPath = sourcesTempDir.Dir; ErrorContainer errorsCaptured = msApp.SaveToSources(sourcesTempDirPath, pathToMsApp); errorsCaptured.ThrowOnErrors(); }
public void ImportedProperties() { using var tempDir = TempDir.Create(); var dataProvider = new DataProvider(); var dataSource = new DataSource(dataProvider, tempDir, Model.DataSourceType.Custom); var propertyId1 = "propertyid1"; var propertyDict1 = CreatePropertyDictionary(); propertyDict1["MDC_P001_6"] = propertyId1; var property1 = new Property(propertyDict1); var propertyId2 = "propertyid2"; var propertyDict2 = CreatePropertyDictionary(); propertyDict2["MDC_P001_6"] = propertyId2; var property2 = new Property(propertyDict2); var propertyId3 = "propertyid3"; var propertyDict3 = CreatePropertyDictionary(); propertyDict3["MDC_P001_6"] = propertyId3; var property3 = new Property(propertyDict3); var clsId = "clsid"; var clsDict = CreateClassDictionary(); clsDict["MDC_P001_5"] = clsId; clsDict["MDC_P090"] = propertyId1 + "," + propertyId2; var cls = new Class(clsDict); var context = new Context(dataSource, new[] { cls }.ToList(), new[] { property1, property2, property3 }.ToList()); var wrapper = context.LoadSubmodels().First() as ClassWrapper; Assert.That(wrapper, Is.Not.Null); if (wrapper == null) { return; } Assert.That(wrapper.Children.Cast <PropertyWrapper>().Select(p => p.Element), Is.EquivalentTo(new[] { property1, property2 })); }
public ActionResult Upload(HttpPostedFileBase file) { string filename = Path.GetFileName(file.FileName); LostDocFileInfo fileInfo; using (TempDir tempDir = new TempDir()) { string tempLocation = Path.Combine(tempDir.Path, filename); file.SaveAs(tempLocation); fileInfo = new LostDocFileInfo(tempLocation); string targetFile = string.Format("{0}_{1}.ldoc", fileInfo.PrimaryAssembly.Filename, fileInfo.PrimaryAssembly.AssetId.Version); if (System.IO.File.Exists(Path.Combine(AppConfig.RepositoryPath, targetFile))) { string message = string.Format("Unable to add file '{0}' as it already exists.", targetFile); App.Instance.Notifications.Add(Severity.Error, Lifetime.Page, Scope.User, this.User, "Failed to upload file", message); } else { System.IO.File.Move(tempLocation, Path.Combine(AppConfig.RepositoryPath, targetFile)); string message = string.Format("Successfully added file '{0}' (as '{1}') to repository.", filename, targetFile); App.Instance.Notifications.Add( Severity.Information, Lifetime.Page, Scope.User, this.User, "File uploaded", message); } } return(this.RedirectToAction("Index")); }
public void MathMaskTest() { Raster rOld = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2005DecDEM\2005DecDEM.tif"))); Raster rNew = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2006FebDEM\2006FebDEM.tif"))); Raster rOldErr = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2005DecDEM\ErrorSurfaces\Constant01\Constant01.tif"))); Raster rNewErr = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2006FebDEM\ErrorSurfaces\Constant02\Constant02.tif"))); // And now the budget seg case Vector vPolyMask = new Vector(new FileInfo(DirHelpers.GetTestRootPath(@"SulphurGCDMASK\Sulphur_SimpleReducedGCDMask.shp"))); // Try this with edge case shapefiles too Vector vMPMG = new Vector(new FileInfo(DirHelpers.GetTestVectorPath(@"MultiPart_MultiGeometry.shp"))); Vector vMPSG = new Vector(new FileInfo(DirHelpers.GetTestVectorPath(@"MultiPart_SingleGeometry.shp"))); Vector vSPMG = new Vector(new FileInfo(DirHelpers.GetTestVectorPath(@"SinglePart_MultiGeometry.shp"))); using (ITempDir tmp = TempDir.Create()) { // We copy the shape files first so they get the right GCID fields FileInfo fiPolyMaskCopy = new FileInfo(Path.Combine(tmp.Name, "Sulphur_SimpleReducedGCDMask.shp")); vPolyMask.Copy(fiPolyMaskCopy); Vector vPolyMaskCopy = new Vector(fiPolyMaskCopy); Raster rSub1 = RasterOperators.SubtractWithMask(rNew, rOld, vPolyMaskCopy, new FileInfo(Path.Combine(tmp.Name, "RasterSubtractVectorMask.tif")), null, false); Raster rSub2 = RasterOperators.SubtractWithMask(rNew, rOld, vPolyMaskCopy, new FileInfo(Path.Combine(tmp.Name, "RasterSubtractRasterizedMask.tif"))); FileInfo fiMPMG = new FileInfo(Path.Combine(tmp.Name, "MultiPart_MultiGeometry_Copy.shp")); vMPMG.Copy(fiMPMG); Vector vMPMGCopy = new Vector(fiMPMG); FileInfo fiMPSG = new FileInfo(Path.Combine(tmp.Name, "MultiPart_SingleGeometr_Copy.shp")); vMPSG.Copy(fiMPSG); Vector vMPSGCopy = new Vector(fiMPSG); FileInfo fiSPMG = new FileInfo(Path.Combine(tmp.Name, "SinglePart_MultiGeometry_Copy.shp")); vSPMG.Copy(fiSPMG); Vector vSPMGCopy = new Vector(fiSPMG); Raster rMPMG = RasterOperators.SubtractWithMask(rNew, rOld, vMPMGCopy, new FileInfo(Path.Combine(tmp.Name, "MultiPart_MultiGeometry.tif"))); Raster rMPSG = RasterOperators.SubtractWithMask(rNew, rOld, vMPSGCopy, new FileInfo(Path.Combine(tmp.Name, "MultiPart_SingleGeometry.tif"))); Raster rSPMG = RasterOperators.SubtractWithMask(rNew, rOld, vSPMGCopy, new FileInfo(Path.Combine(tmp.Name, "SinglePart_MultiGeometry.tif"))); Debug.WriteLine("Done"); } }
public void RenderToSeveralThreads() { using (var tmp = TempDir.Create()) { using (ScreenshotRecorder rec = new ScreenshotRecorder(tmp.Name, 500, 100, 100)) { Barrier b = new Barrier(4); Action acc = () => { b.SignalAndWait(); using (Bitmap bmp = new Bitmap(500, 100)) { rec.TimeStampBitmap(DateTime.Now, bmp); } }; Parallel.Invoke(acc, acc, acc, acc); } } }
public void GetStatsProbalisticBudgetSegTest() { Raster rTemp2005 = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"BudgetSeg\SulphurCreek\2005Dec_DEM\2005Dec_DEM.img"))); Raster rTemp2006 = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"BudgetSeg\SulphurCreek\2006Feb_DEM\2006Feb_DEM.img"))); UnitGroup ug = new UnitGroup(VolumeUnit.CubicMeter, AreaUnit.SquareMeter, LengthUnit.Meter, LengthUnit.Meter); // And now the budget seg case Vector vPolyMask = new Vector(new FileInfo(DirHelpers.GetTestRootPath(@"SulphurGCDMASK\Sulphur_ComplexGCDMask.shp"))); using (ITempDir tmp = TempDir.Create()) { FileInfo fiPolyMaskCopy = new FileInfo(Path.Combine(tmp.Name, "Sulphur_ComplexGCDMask.shp")); vPolyMask.Copy(fiPolyMaskCopy); Vector vPolyMaskCopy = new Vector(fiPolyMaskCopy); Dictionary <string, DoDStats> testBudgetSeg = RasterOperators.GetStatsProbalistic(rTemp2005, rTemp2006, rTemp2005, vPolyMaskCopy, "Category", ug); } }
public void SetNullAbsoluteTest() { using (ITempDir tmp = TempDir.Create()) { Raster rTemp2005 = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"BudgetSeg\SulphurCreek\2005Dec_DEM\2005Dec_DEM.img"))); Raster rTemp2006 = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"BudgetSeg\SulphurCreek\2006Feb_DEM\2006Feb_DEM.img"))); Raster rDoD = RasterOperators.Subtract(rTemp2006, rTemp2005, new FileInfo(Path.Combine(tmp.Name, "rDoD.tif"))); ErrorRasterProperties props02 = new ErrorRasterProperties(0.2m); ErrorRasterProperties props01 = new ErrorRasterProperties(0.1m); // 0.1 2006 // 0.2 2005 Raster r2005Error = RasterOperators.CreateErrorRaster(rTemp2005, props02, new FileInfo(Path.Combine(tmp.Name, "2005Dec_DEM_CONSTERR02.tif"))); Raster r2006Error = RasterOperators.CreateErrorRaster(rTemp2006, props01, new FileInfo(Path.Combine(tmp.Name, "2006Feb_DEM_CONSTERR01.tif"))); Raster propError = RasterOperators.RootSumSquares(r2006Error, r2005Error, new FileInfo(Path.Combine(tmp.Name, "properror.tif"))); Raster rTemplateOutput5 = RasterOperators.AbsoluteSetNull(rDoD, RasterOperators.ThresholdOps.GreaterThan, propError, new FileInfo(Path.Combine(tmp.Name, "AbsRasterGreaterThan.tif"))); } }
public void Display_MessageBox_When_OutputFile_During_Trace_Start_Cannot_Be_Deleted() { using (var tmp = TempDir.Create()) { using (var model = Create(tmp.Name)) { string etlFile = model.TraceFileName; using (var lockedOutputFile = File.Create(etlFile)) { ClearStates(); model.Commands["StartTracing"].Execute(null); Assert.AreEqual(2, LocalTraceStateChanges.Count); Assert.AreEqual(TraceStates.Starting, LocalTraceStateChanges[0]); } MessageBoxShown($"Could not delete old trace file {etlFile}"); } } }
public void ShouldUpdateTheVersionElementOnly() { var tempDir = TempDir.Create(); var projectFileContents = @"<Project Sdk=""Microsoft.NET.Sdk""> <PropertyGroup> <Version>1.0.0</Version> </PropertyGroup> </Project>"; var projectFilePath = WriteProjectFile(tempDir, projectFileContents); var project = Project.Create(projectFilePath); project.WriteVersion(new Version(2, 0, 0)); var versionedProjectContents = File.ReadAllText(projectFilePath); versionedProjectContents.ShouldBe(projectFileContents.Replace("1.0.0", "2.0.0")); }
public void ShouldIgnoreInsignificantCommits() { var workingDirectory = TempDir.Create(); using var tempRepository = TempRepository.Create(workingDirectory); TempCsProject.Create(workingDirectory); var workingFilePath = Path.Join(workingDirectory, "hello.txt"); // Create and commit a test file File.WriteAllText(workingFilePath, "First line of text"); CommitAll(tempRepository); // Run versionize var workingCopy = WorkingCopy.Discover(workingDirectory); workingCopy.Versionize(); // Add insignificant change File.AppendAllText(workingFilePath, "This is another line of text"); CommitAll(tempRepository, "chore: Added line of text"); // Get last commit var lastCommit = tempRepository.Head.Tip; // Run versionize, ignoring insignificant commits try { workingCopy.Versionize(ignoreInsignificant: true); throw new InvalidOperationException("Expected to throw in Versionize call"); } catch (CommandLineExitException ex) { ex.ExitCode.ShouldBe(0); } lastCommit.ShouldBe(tempRepository.Head.Tip); // Cleanup Cleanup.DeleteDirectory(workingDirectory); }
public void VectorRasterTest() { Raster rTemplate = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2005DecDEM\2005DecDEM.tif"))); Vector vPolyMaskSimple = new Vector(new FileInfo(DirHelpers.GetTestRootPath(@"SulphurGCDMASK\Sulphur_SimpleGCDMask.shp"))); Vector vPolyMaskComplex = new Vector(new FileInfo(DirHelpers.GetTestRootPath(@"SulphurGCDMASK\Sulphur_ComplexGCDMask.shp"))); using (ITempDir tmp = TempDir.Create()) { FileInfo fiPolyMaskSimpleCOPY = new FileInfo(Path.Combine(tmp.Name, "Sulphur_SimpleGCDMask.shp")); FileInfo fiPolyMaskComplexCOPY = new FileInfo(Path.Combine(tmp.Name, "Sulphur_ComplexGCDMask.shp")); vPolyMaskSimple.Copy(fiPolyMaskSimpleCOPY); vPolyMaskComplex.Copy(fiPolyMaskComplexCOPY); Vector vPolyMaskSimpleCOPY = new Vector(fiPolyMaskSimpleCOPY); Vector vPolyMaskComplexCOPY = new Vector(fiPolyMaskComplexCOPY); List <string> times = new List <string> { }; var watch = Stopwatch.StartNew(); // Try with a numeric field watch.Restart(); VectorRaster test1 = new VectorRaster(rTemplate, vPolyMaskComplexCOPY, "Category"); string time1 = string.Format("MyRasterizationTest1, , {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds); // Try the same shape file with a string field watch.Restart(); VectorRaster test2 = new VectorRaster(rTemplate, vPolyMaskComplexCOPY, "Desc_"); string time2 = string.Format("MyRasterizationTest1, , {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds); // Now try a simpler shapefule with a string field watch.Restart(); VectorRaster test3 = new VectorRaster(rTemplate, vPolyMaskSimpleCOPY, "Method"); string time3 = string.Format("MyRasterizationTest1, , {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds); Debug.WriteLine(""); Debug.WriteLine(time1); Debug.WriteLine(time2); Debug.WriteLine(time3); } }
public void AggregateType() { using var tempDir = TempDir.Create(); var dataProvider = new DataProvider(); var dataSource = new DataSource(dataProvider, tempDir, Model.DataSourceType.Custom); var propertyId = "0112/2///62683#ACE101"; var propertyDict = CreatePropertyDictionary(); propertyDict["MDC_P001_6"] = propertyId; propertyDict["MDC_P022"] = "SET(0,?) OF STRING"; var property = new Property(propertyDict); var context = new Context(dataSource, new List <Class>(), new[] { property }.ToList()); var wrapper = context.LoadSubmodelElements().First() as PropertyWrapper; if (wrapper == null) { return; } Assert.That(wrapper.Element.DataType, Is.InstanceOf <AggregateType>()); if (wrapper.Element.DataType is AggregateType type) { Assert.That(type.TypeValue, Is.EqualTo(Cdd.AggregateType.Type.Set)); Assert.That(type.Subtype, Is.EqualTo(new SimpleType(SimpleType.Type.String))); Assert.That(type.LowerBound, Is.EqualTo(0)); Assert.That(type.UpperBound, Is.Null); } Assert.That(wrapper.Children, Has.Count.EqualTo(1)); var child = wrapper.Children.First(); Assert.That(child, Is.InstanceOf <PropertyWrapper>()); var childWrapper = child as PropertyWrapper; if (childWrapper == null) { return; } Assert.That(childWrapper.Element.DataType, Is.EqualTo(new SimpleType(SimpleType.Type.String))); }
public void WriteTest() { Raster rTempl = new Raster(new FileInfo(DirHelpers.GetTestRasterPath("SquareValley950-980.tif"))); using (ITempDir tmp = TempDir.Create()) { Raster rOutput = new Raster(rTempl, new FileInfo(Path.Combine(tmp.Name, "ExtendedCopyRasterTestBuffer.tif"))); rTempl.UnloadDS(); rTempl = null; rOutput.Open(true); rOutput.Write(0, 0, 1, 1, new double[1] { 0.55 }); rOutput.Write(0, 1, 1, 1, new float[1] { 30.135f }); rOutput.Write(0, 2, 1, 1, new int[1] { 3 }); rOutput.UnloadDS(); rOutput = null; Raster rTest = new Raster(new FileInfo(Path.Combine(tmp.Name, "ExtendedCopyRasterTestBuffer.tif"))); double[] dBuff = new double[1]; rTest.Read(0, 0, 1, 1, dBuff); Assert.AreEqual(dBuff[0], 0.55, 0.000001); float[] fBuff = new float[1]; rTest.Read(0, 1, 1, 1, fBuff); Assert.AreEqual(fBuff[0], 30.135f); int[] iBuff = new int[1]; rTest.Read(0, 2, 1, 1, iBuff); Assert.AreEqual(iBuff[0], 3); rTest.UnloadDS(); rTest = null; } }
public async Task When_file_version_is_lower_than_current_then_doesnt_log_warning() { var console = new TestConsole(); using var tmpContainer = TempDir.Create(); var tmp = tmpContainer.TemporaryDir; var currentV = RootElement.GameSystem.Info().CurrentVersion; var higherV = currentV.WithMajor(currentV.Major - 1); var gst = NodeFactory.Gamesystem().WithBattleScribeVersion(higherV.BattleScribeString); using (var gstFileStream = File.Create(Path.Combine(tmp.FullName, "test.gst"))) { gst.Serialize(gstFileStream); } await Program.CreateParser().InvokeAsync($"publish -s \"{tmp}\" -o \"{tmp}\"", console); console.Out.ToString() .Should().NotContain(WarningMessage); }
public void TestNoLocalDatabaseRefsWhenLocalDatabaseReferencesPropertyWasEmptyJson(string appName) { var pathToMsApp = Path.Combine(Environment.CurrentDirectory, "Apps", appName); Assert.IsTrue(File.Exists(pathToMsApp)); var(msApp, errors) = CanvasDocument.LoadFromMsapp(pathToMsApp); errors.ThrowOnErrors(); using var sourcesTempDir = new TempDir(); var sourcesTempDirPath = sourcesTempDir.Dir; msApp.SaveToSources(sourcesTempDirPath); var loadedMsApp = SourceSerializer.LoadFromSource(sourcesTempDirPath, new ErrorContainer()); Assert.IsTrue(loadedMsApp._entropy.WasLocalDatabaseReferencesEmpty.Value); Assert.IsFalse(loadedMsApp._entropy.LocalDatabaseReferencesAsEmpty); Assert.IsTrue(loadedMsApp._dataSourceReferences.Count == 0); }
public void Start_Stop_Verify_MessageBox_Is_Displayed_IfOutputFile_Was_Not_Created() { using (var tmp = TempDir.Create()) { using (var model = Create(tmp.Name)) { model.Commands["StartTracing"].Execute(null); WaitUntilLocalTargetState(model, TraceStates.Running); model.Commands["StopTracing"].Execute(null); WaitUntilLocalTargetState(model, TraceStates.Stopped); ContainsMessage("hi trace start"); ContainsMessage($"trace stop performed {model.StopData.TraceFileName}"); MessageBoxShown($"Output file {model.StopData.TraceFileName} was not found"); } } }
public async Task DeleteBeforeHashing() { TestWriter testWriter = null; using var tmpDir = TempDir.Create(); using var engine = new ClientEngine(new EngineSettingsBuilder(EngineSettingsBuilder.CreateForTests()) { AutoSaveLoadFastResume = true, CacheDirectory = tmpDir.Path, }.ToSettings(), Factories.Default.WithPieceWriterCreator(maxOpenFiles => (testWriter = new TestWriter())) ); var first = new TaskCompletionSource <object> (); var second = new TaskCompletionSource <object> (); var torrent = TestRig.CreatePrivate(); var path = engine.Settings.GetFastResumePath(torrent.InfoHashes); Directory.CreateDirectory(Path.GetDirectoryName(path)); File.WriteAllBytes(path, new FastResume(torrent.InfoHashes, new BitField(torrent.PieceCount).SetAll(true), new BitField(torrent.PieceCount)).Encode()); var manager = await engine.AddAsync(torrent, "savedir"); testWriter.FilesThatExist = new System.Collections.Generic.List <ITorrentManagerFile> (manager.Files); Assert.IsTrue(manager.HashChecked); manager.Engine.DiskManager.GetHashAsyncOverride = (torrent, pieceIndex, dest) => { first.SetResult(null); second.Task.Wait(); new byte[20].CopyTo(dest.V1Hash); return(Task.FromResult(true)); }; var hashCheckTask = manager.HashCheckAsync(false); await first.Task.WithTimeout(); Assert.IsFalse(File.Exists(path)); second.SetResult(null); await hashCheckTask.WithTimeout(); Assert.IsTrue(File.Exists(path)); }
public void Start_Stop_Verify_MessageBox_Is_Displayed_IfOutputDirectory_Contains_No_EtlFiles() { using (var tmp = TempDir.Create()) { using (var model = Create(tmp.Name, bUseTraceDirStopVariable: true)) { model.Commands["StartTracing"].Execute(null); WaitUntilLocalTargetState(model, TraceStates.Running); model.Commands["StopTracing"].Execute(null); WaitUntilLocalTargetState(model, TraceStates.Stopped); ContainsMessage("hi trace start"); ContainsMessage($"trace stop performed {tmp.Name}"); MessageBoxShown($"Error: No new etl files were created in directory {tmp.Name}"); } } }
public async void Case4() { var origF = SampleFinder.Get("sample_4.6mb"); var oldHash = origF.SHA1ForFile(); var outDir = TempDir.New(); var archives = await SevenZipper1.Compress(origF, outDir, 0.5); archives.MustHaveFiles(7); var list = await SevenZipper1.Decompress(archives[0], outDir); list.Should().HaveCount(1); var newF = Path.Combine(outDir, list[0]); var newHash = newF.SHA1ForFile(); newHash.Should().Be(oldHash, "Hashes should match"); Directory.Delete(outDir, true); }
public void Init_Option_Add() { using (var temp = new TempDir()) { var git = new GitRepo(m_log, temp.Path); git.Init(new[] { new GitConfigOption("foo.bar", "blah1", add: true), new GitConfigOption("foo.bar", "blah2", add: true), }); var configFile = temp.GetPath("config"); var configContents = File.ReadAllLines(configFile); var sectionLineNumber = FindSectionHeader(configContents, "foo"); Assert.IsTrue(sectionLineNumber >= 0); Assert.IsTrue(Regex.IsMatch(configContents[sectionLineNumber + 1].Trim(), @"bar\s*=\s*blah1")); Assert.IsTrue(Regex.IsMatch(configContents[sectionLineNumber + 2].Trim(), @"bar\s*=\s*blah2")); } }
public void BuildPyramidsTest() { using (ITempDir tmp = TempDir.Create()) { // Small rasters don't need pyramids Raster rTempl = new Raster(new FileInfo(DirHelpers.GetTestRasterPath("SquareValley950-980.tif"))); Raster rTemplateOutput = RasterOperators.ExtendedCopy(rTempl, new FileInfo(Path.Combine(tmp.Name, "SMALL_PyramidTest.tif"))); rTemplateOutput.BuildPyramids("average"); Assert.IsFalse(File.Exists(Path.Combine(tmp.Name, "SMALL_PyramidTest.tif.ovr"))); // Big Rasters do need pyramids Raster rBigTempl = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"BudgetSeg\SulphurCreek\2005Dec_DEM\2005Dec_DEM.img"))); ExtentRectangle newExtReal = rBigTempl.Extent.Buffer(1000); Raster rBigTemplateOutput = RasterOperators.ExtendedCopy(rBigTempl, new FileInfo(Path.Combine(tmp.Name, "BIG_PyramidTest.tif")), newExtReal); rBigTemplateOutput.BuildPyramids("average"); Assert.IsTrue(File.Exists(Path.Combine(tmp.Name, "BIG_PyramidTest.tif.ovr"))); } }
public void SetNullTest() { using (ITempDir tmp = TempDir.Create()) { Raster rTempl = new Raster(new FileInfo(DirHelpers.GetTestRasterPath("const900.tif"))); Raster rTemp2 = new Raster(new FileInfo(DirHelpers.GetTestRasterPath("const950.tif"))); Raster rTemplateOutput1 = RasterOperators.SetNull(rTempl, RasterOperators.ThresholdOps.GreaterThan, 4, new FileInfo(Path.Combine(tmp.Name, "GreaterThan.tif"))); Raster rTemplateOutput2 = RasterOperators.SetNull(rTempl, RasterOperators.ThresholdOps.LessThan, 4, new FileInfo(Path.Combine(tmp.Name, "LessThan.tif"))); Raster rTemplateOutput3 = RasterOperators.SetNull(rTempl, RasterOperators.ThresholdOps.GreaterThanOrEqual, 4, new FileInfo(Path.Combine(tmp.Name, "GreaterThanOrEqual.tif"))); Raster rTemplateOutput4 = RasterOperators.SetNull(rTempl, RasterOperators.ThresholdOps.LessThanOrEqual, 4, new FileInfo(Path.Combine(tmp.Name, "LessThanOrEqual.tif"))); Raster rTemplateOutput5 = RasterOperators.SetNull(rTempl, RasterOperators.ThresholdOps.GreaterThan, rTemp2, new FileInfo(Path.Combine(tmp.Name, "RasterGreaterThan.tif"))); Raster rTemplateOutput6 = RasterOperators.SetNull(rTempl, RasterOperators.ThresholdOps.LessThan, rTemp2, new FileInfo(Path.Combine(tmp.Name, "RasterLessThan.tif"))); Raster rTemplateOutput7 = RasterOperators.SetNull(rTempl, RasterOperators.ThresholdOps.GreaterThanOrEqual, rTemp2, new FileInfo(Path.Combine(tmp.Name, "RasterGreaterThanOrEqual.tif"))); Raster rTemplateOutput8 = RasterOperators.SetNull(rTempl, RasterOperators.ThresholdOps.LessThanOrEqual, rTemp2, new FileInfo(Path.Combine(tmp.Name, "RasterLessThanOrEqual.tif"))); Raster rTemplateOutput9 = RasterOperators.SetNull(rTempl, RasterOperators.ThresholdOps.GreaterThan, 4, RasterOperators.ThresholdOps.LessThanOrEqual, 10, new FileInfo(Path.Combine(tmp.Name, "DoubleOp.tif"))); } }
public void ShouldDetectVersionInNamespacedXmlProjects() { var tempDir = TempDir.Create(); var version = SemanticVersion.Parse("1.0.0"); // Create .net project var projectFileContents = $@"<Project ToolsVersion=""12.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> ... <Version>{version}</Version> ... </PropertyGroup> </Project>"; TempProject.CreateFromProjectContents(tempDir, "csproj", projectFileContents); var projects = Projects.Discover(tempDir); projects.Version.ShouldBe(version); }
public async Task SaveRestoreState_OneInMemoryTorrent(bool addStreaming) { var pieceLength = Constants.BlockSize * 4; using var tmpDir = TempDir.Create(); var torrent = TestRig.CreateMultiFileTorrent(TorrentFile.Create(pieceLength, Constants.BlockSize, Constants.BlockSize * 2, Constants.BlockSize * 3), pieceLength, out BEncoding.BEncodedDictionary metadata); var engine = new ClientEngine(EngineSettingsBuilder.CreateForTests(cacheDirectory: tmpDir.Path)); TorrentManager torrentManager; if (addStreaming) { torrentManager = await engine.AddStreamingAsync(torrent, "mySaveDirectory", new TorrentSettingsBuilder { CreateContainingDirectory = true }.ToSettings()); } else { torrentManager = await engine.AddAsync(torrent, "mySaveDirectory", new TorrentSettingsBuilder { CreateContainingDirectory = true }.ToSettings()); } await torrentManager.SetFilePriorityAsync(torrentManager.Files[0], Priority.High); await torrentManager.MoveFileAsync(torrentManager.Files[1], Path.GetFullPath("some_fake_path.txt")); var restoredEngine = await ClientEngine.RestoreStateAsync(await engine.SaveStateAsync()); Assert.AreEqual(engine.Settings, restoredEngine.Settings); Assert.AreEqual(engine.Torrents[0].Torrent.Name, restoredEngine.Torrents[0].Torrent.Name); Assert.AreEqual(engine.Torrents[0].SavePath, restoredEngine.Torrents[0].SavePath); Assert.AreEqual(engine.Torrents[0].Settings, restoredEngine.Torrents[0].Settings); Assert.AreEqual(engine.Torrents[0].InfoHash, restoredEngine.Torrents[0].InfoHash); Assert.AreEqual(engine.Torrents[0].MagnetLink.ToV1String(), restoredEngine.Torrents[0].MagnetLink.ToV1String()); Assert.AreEqual(engine.Torrents[0].Files.Count, restoredEngine.Torrents[0].Files.Count); for (int i = 0; i < engine.Torrents.Count; i++) { Assert.AreEqual(engine.Torrents[0].Files[i].FullPath, restoredEngine.Torrents[0].Files[i].FullPath); Assert.AreEqual(engine.Torrents[0].Files[i].Priority, restoredEngine.Torrents[0].Files[i].Priority); } }
public void OneValidOneInvalidSource() { using var tempDir = TempDir.Create(); var dataProvider = new DataProvider(); var iecCddPath = Path.Combine(tempDir, "iec-cdd"); Directory.CreateDirectory(iecCddPath); using var source1 = TempDir.Create(iecCddPath); CreateEmptyXls(source1, GetExportFileName("class", "12345")); CreateEmptyXls(source1, GetExportFileName("property", "12345")); using var source2 = TempDir.Create(iecCddPath); CreateEmptyXls(source2, GetExportFileName("class", "67890")); CreateEmptyXls(source2, GetExportFileName("property", "67890")); CreateEmptyXls(source2, GetExportFileName("class", "12345")); Assert.That(dataProvider.FindDefaultDataSources(tempDir), Is.EquivalentTo(new[] { new DataSource(dataProvider, source1, Model.DataSourceType.Default), })); }
public void MultiMathErrorTest() { Raster rOld = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2005DecDEM\2005DecDEM.tif"))); Raster rNew = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2006FebDEM\2006FebDEM.tif"))); Raster rOldErr = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2005DecDEM\ErrorSurfaces\Constant01\Constant01.tif"))); Raster rNewErr = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2006FebDEM\ErrorSurfaces\Constant02\Constant02.tif"))); using (ITempDir tmp = TempDir.Create()) { Raster rSub2 = RasterOperators.MinimumErr(new List <Raster> { rOld, rNew }, new List <Raster> { rOldErr, rNewErr }, new FileInfo(Path.Combine(tmp.Name, "MinErr.tif"))); Raster rSub1 = RasterOperators.MaximumErr(new List <Raster> { rOld, rNew }, new List <Raster> { rOldErr, rNewErr }, new FileInfo(Path.Combine(tmp.Name, "MaxErr.tif"))); } }
public static void ArchiveParseTest() { using (var tempDir = new TempDir()) { // write config file var configFilePath = tempDir + LfxConfigFile.FileName; File.WriteAllText(configFilePath, ConfigFileContent); // load config file var configFile = LfxConfigFile.Load(configFilePath); // print keys foreach (var configValue in configFile) { Console.WriteLine($"{configValue.Key}: {configValue.Value}"); } Assert.AreEqual(configFilePath.ToString(), configFile.Path); Assert.AreEqual(LfxPointerType.Archive, configFile.Type); Assert.AreEqual(Url, configFile.Url); Assert.AreEqual(Hint, configFile.Hint); } }
private void GenerateRsaKey(TempDir tempFolder) { // Arrange var generateRsaKeyArgs = OptionsToStringArgsHelper.GetArgs(new GenerateKeyVerbOptions() { AlgorithmToUse = EnvCryptAlgoEnum.Rsa.ToString(), KeyName = RsaKeyName, OutputDirectory = tempFolder.TempDirectory, OutputKeyToConsole = false, Verbose = false }); // Act Program.Main(generateRsaKeyArgs); // Assert _rsaPrivateKeyFile = Path.Combine(tempFolder.TempDirectory, RsaKeyName + GenerateKeyWorkflow.PrivateKeyPostfix); _rsaPublicKeyFile = Path.Combine(tempFolder.TempDirectory, RsaKeyName + GenerateKeyWorkflow.PublicKeyPostfix); File.Exists(_rsaPrivateKeyFile).Should().BeTrue(); File.Exists(_rsaPublicKeyFile).Should().BeTrue(); var privateKeyXml = File.ReadAllText(_rsaPrivateKeyFile); privateKeyXml = privateKeyXml.Replace(Environment.NewLine, string.Empty); var publicKeyXml = File.ReadAllText(_rsaPublicKeyFile); publicKeyXml = publicKeyXml.Replace(Environment.NewLine, string.Empty); // Public key just has the exponent & modulus publicKeyXml.Should().MatchRegex(".+<Exponent>.+</Exponent>"); publicKeyXml.Should().MatchRegex(".+<Modulus>.+</Modulus>"); publicKeyXml.Should().NotMatchRegex(".+<D>.+</D>"); // Private key has everything the public key has privateKeyXml.Should().MatchRegex(".+<Exponent>.+</Exponent>"); privateKeyXml.Should().MatchRegex(".+<Modulus>.+</Modulus>"); privateKeyXml.Should().MatchRegex(".+<D>.+</D>"); }
void Compile() { var files = Scripts.Select(t => { FileInfo file2; if (t.File != null) { file2 = TempDir.GetFile(t.File.Name); } else { file2 = TempDir.GetFile(Path.GetTempFileName().ToFileInfo().Name); } file2.WriteAllText(t.FinalCode ?? t.Code); return(file2); }); var asms = AppDomain.CurrentDomain.GetAssemblies().Select(t => t.Location).ToList(); asms.RemoveAll(t => t.Contains("mscorlib")); var builder = new ToolArgsBuilder { SwitchSeparatorString = ":" } .AddOption("/out", ExeFile.FullName); asms.ForEach(t => builder.AddOption("/reference", t)); files.ForEach(t => builder.AddCommand(t.FullName)); var args = builder.ToString(); var csc = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe"; var output = new StringBuilder(); var p = csc.ToProcess(args).Execute(output); if (p.ExitCode != 0) { throw new Exception("Script compilation failed for " + Scripts.Select(ScriptToErrorText).StringJoin(",") + "\n" + output.ToString()); } }
public void Id() { using var tempDir = TempDir.Create(); var dataProvider = new DataProvider(); var dataSource = new DataSource(dataProvider, tempDir, Model.DataSourceType.Custom); var clsId = "0112/2///62683#ACC505"; var clsDict = CreateClassDictionary(); clsDict["MDC_P001_5"] = clsId; var cls = new Class(clsDict); var context = new Context(dataSource, new[] { cls }.ToList(), new System.Collections.Generic.List <Property>()); var submodels = context.LoadSubmodels(); Assert.That(submodels, Has.Count.EqualTo(1)); var submodel = submodels.First(); Assert.That(submodel, Is.InstanceOf <ClassWrapper>()); var wrapper = submodel as ClassWrapper; Assert.That(wrapper, Is.Not.Null); if (wrapper == null) { return; } Assert.That(wrapper.DataSource, Is.EqualTo(dataSource)); Assert.That(wrapper.Id, Is.EqualTo(clsId)); Assert.That(wrapper.ToString(), Is.EqualTo(clsId)); Assert.That(wrapper.Name, Is.Empty); Assert.That(wrapper.Parent, Is.Null); Assert.That(wrapper.Children, Is.Empty); Assert.That(wrapper.GetDetailsUrl(), Is.EqualTo(new Uri( "https://cdd.iec.ch/cdd/iec62683/iec62683.nsf/classes/0112-2---62683%23ACC505"))); }
public ActionResult Upload(HttpPostedFileBase file) { string filename = Path.GetFileName(file.FileName); LostDocFileInfo fileInfo; using (TempDir tempDir = new TempDir(AppConfig.TempPath)) { string tempLocation = Path.Combine(tempDir.Path, filename); file.SaveAs(tempLocation); fileInfo = new LostDocFileInfo(tempLocation); string targetFile = string.Format("{0}_{1}.ldoc", fileInfo.PrimaryAssembly.Filename, fileInfo.PrimaryAssembly.AssetId.Version); if (System.IO.File.Exists(Path.Combine(AppConfig.RepositoryPath, targetFile))) { string message = string.Format("Unable to add file '{0}' as it already exists.", targetFile); this.Notifications.Add(Severity.Error, Lifetime.Page, Scope.User, this.User, "Failed to upload file", message); } else { System.IO.File.Move(tempLocation, Path.Combine(AppConfig.RepositoryPath, targetFile)); string message = string.Format("Successfully added file '{0}' (as '{1}') to repository.", filename, targetFile); this.Notifications.Add( Severity.Information, Lifetime.Page, Scope.User, this.User, "File uploaded", message); } } return this.RedirectToAction("Index"); }