public void PopulateCatalog_WhenPluginPathContainsInvalidDirectory_IgnoresIt() { var loader = new PluginLoader(); var catalog = MockRepository.GenerateMock <IPluginCatalog>(); loader.AddPluginPath(@"C:\This\Directory\Does\Not\Exist"); loader.PopulateCatalog(catalog, NullProgressMonitor.CreateInstance()); catalog.VerifyAllExpectations(); // nothing added to catalog }
public SolutionEntityItem AddItem(IProgressMonitor monitor, string filename, bool createSolutionConfigurations) { if (monitor == null) { monitor = new NullProgressMonitor(); } SolutionEntityItem entry = Services.ProjectService.ReadSolutionItem(monitor, filename); AddItem(entry, createSolutionConfigurations); return(entry); }
public void When_user_options_are_saved_collapsed_nodes_are_correct() { var collapsedNodes = new [] { "test" }; controller.SetCollapsedNodes(collapsedNodes); controller.SaveUserOptions("", NullProgressMonitor.CreateInstance()); xmlSerializer.AssertWasCalled(xs => xs.SaveToXml(Arg <UserOptions> .Matches(uo => uo.CollapsedNodes.Contains(collapsedNodes[0])), Arg <string> .Is.Anything)); }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="System.IO.IOException"></exception> private void CreateVerifyOpenPack(IList <RevObject> objectSource) { NullProgressMonitor m = NullProgressMonitor.INSTANCE; writer = new PackWriter(config, db.NewObjectReader()); writer.PreparePack(objectSource.Iterator()); NUnit.Framework.Assert.AreEqual(objectSource.Count, writer.GetObjectCount()); writer.WritePack(m, m, os); writer.Release(); VerifyOpenPack(false); }
public void When_user_options_are_saved_treeview_category_is_correct() { const string treeViewCategory = "test"; controller.Handle(new TreeViewCategoryChanged(treeViewCategory)); controller.SaveUserOptions("", NullProgressMonitor.CreateInstance()); xmlSerializer.AssertWasCalled(xs => xs.SaveToXml(Arg <UserOptions> .Matches(uo => uo.TreeViewCategory == treeViewCategory), Arg <string> .Is.Anything)); }
public void When_user_options_are_saved_filename_matches_project() { controller.Handle(new TreeViewCategoryChanged("test")); const string projectLocation = "test.gallio"; var userOptionsFileName = projectLocation + UserOptions.Extension; controller.SaveUserOptions(projectLocation, NullProgressMonitor.CreateInstance()); xmlSerializer.AssertWasCalled(xs => xs.SaveToXml(Arg <UserOptions> .Is.Anything, Arg.Is(userOptionsFileName))); }
public void Execute_should_save_the_project_user_options() { const string projectLocation = "projectLocation"; command.ProjectLocation = projectLocation; command.Execute(NullProgressMonitor.CreateInstance()); projectUserOptionsController.AssertWasCalled(uoc => uoc.SaveUserOptions(Arg.Is(projectLocation), Arg <IProgressMonitor> .Is.Anything)); }
public void FormatWritesTheTransformedReport() { string resourcePath = Path.Combine(Path.GetDirectoryName(AssemblyUtils.GetAssemblyLocalPath(GetType().Assembly)), @"..\Reports"); IReportWriter reportWriter = Mocks.StrictMock <IReportWriter>(); IReportContainer reportContainer = Mocks.StrictMock <IReportContainer>(); IProgressMonitor progressMonitor = NullProgressMonitor.CreateInstance(); string reportPath = SpecialPathPolicy.For <XsltReportFormatter>().CreateTempFileWithUniqueName().FullName; using (Stream tempFileStream = File.OpenWrite(reportPath)) { using (Mocks.Record()) { SetupResult.For(reportWriter.ReportContainer).Return(reportContainer); reportWriter.SerializeReport(null, AttachmentContentDisposition.Link); LastCall.Constraints(Is.NotNull(), Is.Equal(AttachmentContentDisposition.Link)) .Do((SerializeReportDelegate) delegate(XmlWriter writer, AttachmentContentDisposition contentDisposition) { XmlDocument doc = new XmlDocument(); doc.InnerXml = "<report>The report.</report>"; doc.Save(writer); }); SetupResult.For(reportContainer.ReportName).Return("Foo"); Expect.Call(reportContainer.OpenWrite("Foo.ext", MimeTypes.PlainText, new UTF8Encoding(false))) .Return(tempFileStream); reportWriter.AddReportDocumentPath("Foo.ext"); Expect.Call(reportContainer.OpenWrite(@"Foo\MbUnitLogo.png", MimeTypes.Png, null)).Return(new MemoryStream()); reportWriter.SaveReportAttachments(null); LastCall.Constraints(Is.NotNull()); } using (Mocks.Playback()) { XsltReportFormatter formatter = new XsltReportFormatter("ext", MimeTypes.PlainText, new DirectoryInfo(resourcePath), "Diagnostic.xslt", new string[] { "MbUnitLogo.png" }); var reportFormatterOptions = new ReportFormatterOptions(); reportFormatterOptions.AddProperty(XsltReportFormatter.AttachmentContentDispositionOption, AttachmentContentDisposition.Link.ToString()); formatter.Format(reportWriter, reportFormatterOptions, progressMonitor); string reportContents = File.ReadAllText(reportPath); TestLog.EmbedXml("Diagnostic report contents", reportContents); Assert.Contains(reportContents, "<resourceRoot>Foo</resourceRoot>"); Assert.Contains(reportContents, "The report."); File.Delete(reportPath); } } }
public void Save_should_save_the_project() { var testProject = new TestProject(); projectTreeModel.TestProject = testProject; const string projectName = "projectName"; projectController.Save(projectName, NullProgressMonitor.CreateInstance()); testProjectManager.AssertWasCalled(tpm => tpm.SaveProject(Arg.Is(testProject), Arg <FileInfo> .Matches(fi => fi.Name == projectName))); }
public void SetUp() { logger = MockRepository.GenerateStub <ILogger>(); driver = new IronRubyTestDriver(logger); var testIsolationProvider = (ITestIsolationProvider)RuntimeAccessor.ServiceLocator.ResolveByComponentId("Gallio.LocalTestIsolationProvider"); testIsolationContext = testIsolationProvider.CreateContext(new TestIsolationOptions(), logger); testPackage = new TestPackage(); testExplorationOptions = new TestExplorationOptions(); testExecutionOptions = new TestExecutionOptions(); messageSink = MockRepository.GenerateStub <IMessageSink>(); progressMonitor = NullProgressMonitor.CreateInstance(); }
public void Load_adds_menu_item_with_correct_command() { MenuCommand menuCommand = null; menuManager.Stub(mm => mm.Add(Arg <string> .Is.Anything, Arg <Func <MenuCommand> > .Is.Anything)) .Do((Action <string, Func <MenuCommand> >)((m, f) => menuCommand = f())); annotationsPackage.Load(); Assert.That(menuCommand, Is.NotNull()); menuCommand.Command.Execute(NullProgressMonitor.CreateInstance()); windowManager.AssertWasCalled(wm => wm.Show(AnnotationsPackage.WindowId)); }
/// <exception cref="NGit.Errors.MissingObjectException"></exception> /// <exception cref="System.IO.IOException"></exception> private void CreateVerifyOpenPack(ICollection <ObjectId> interestings, ICollection <ObjectId> uninterestings, bool thin, bool ignoreMissingUninteresting) { NullProgressMonitor m = NullProgressMonitor.INSTANCE; writer = new PackWriter(config, db.NewObjectReader()); writer.SetThin(thin); writer.SetIgnoreMissingUninteresting(ignoreMissingUninteresting); writer.PreparePack(m, interestings, uninterestings); writer.WritePack(m, m, os); writer.Release(); VerifyOpenPack(thin); }
public void Save_should_announce_before_saving_the_project() { using (eventAggregator.GetMockRepository().Ordered()) { eventAggregator.Expect(ea => ea.Send(Arg.Is(projectController), Arg <SavingProject> .Is.Anything)); testProjectManager.Expect(tpm => tpm.SaveProject(Arg <TestProject> .Is.Anything, Arg <FileInfo> .Is.Anything)); } eventAggregator.Replay(); projectController.Save("projectName", NullProgressMonitor.CreateInstance()); eventAggregator.VerifyAllExpectations(); }
public void SaveProject_with_false_and_execute_exception_should_report_error() { string projectName = Paths.DefaultProject; commandFactory.Stub(cf => cf.CreateSaveProjectCommand(projectName)).Return(command); var exception = new Exception(); command.Stub(c => c.Execute(NullProgressMonitor.CreateInstance())).IgnoreArguments().Throw(exception); applicationController.SaveProject(false); commandFactory.AssertWasCalled(cf => cf.CreateSaveProjectCommand(projectName)); unhandledExceptionPolicy.AssertWasCalled(uep => uep.Report("Error saving project", exception)); }
private IEnumerable <TestData> GetGallioTestcases(TestFrameworkLogger frameworkLogger, IEnumerable <string> sources) { try { var testFrameworkManager = RuntimeAccessor.ServiceLocator.Resolve <ITestFrameworkManager>(); var loader = new ReflectionOnlyAssemblyLoader(); IList <ICodeElementInfo> assemblyInfos = sources.Select(source => LoadAssembly(source, loader)).Where(assembly => assembly != null).ToList(); var testFrameworkSelector = new TestFrameworkSelector() { Filter = testFrameworkHandle => testFrameworkHandle.Id != "MSTestAdapter.TestFramework" || testFrameworkHandle.Id != "NUnitAdapter.TestFramework", FallbackMode = TestFrameworkFallbackMode.Approximate }; ITestDriver driver = testFrameworkManager.GetTestDriver(testFrameworkSelector, frameworkLogger); var testExplorationOptions = new TestExplorationOptions(); var tests = new List <TestData>(); MessageConsumer messageConsumer = new MessageConsumer() .Handle <TestDiscoveredMessage>(message => { if (message.Test.IsTestCase) { tests.Add((message.Test)); } }) .Handle <AnnotationDiscoveredMessage>(message => message.Annotation.Log(frameworkLogger, true)); driver.Describe(loader.ReflectionPolicy, assemblyInfos, testExplorationOptions, messageConsumer, NullProgressMonitor.CreateInstance()); bool reset = ResetCollectionForExposedTests(tests); if (reset) { tests = null; } return(tests); } catch (Exception ex) { frameworkLogger.Log(LogSeverity.Error, "Gallio failed to load tests", ex); return(null); } }
internal static IProgressMonitor GetParseProgressMonitor() { IProgressMonitor mon; if (parseProgressMonitorFactory != null) { mon = parseProgressMonitorFactory.CreateProgressMonitor(); } else { mon = new NullProgressMonitor(); } return(new AggregatedProgressMonitor(mon, new InternalProgressMonitor())); }
/// <summary> /// Send this buffer to an output stream. /// <para /> /// This method may only be invoked After {@link #close()} has completed /// normally, to ensure all data is completely transferred. /// </summary> /// <param name="os">stream to send this buffer's complete content to.</param> /// <param name="pm"> /// if not null progress updates are sent here. Caller should /// initialize the task and the number of work units to /// <code><see cref="Length"/>/1024</code>. /// </param> public virtual void writeTo(Stream os, ProgressMonitor pm) { if (os == null) { throw new ArgumentNullException("os"); } if (pm == null) { pm = new NullProgressMonitor(); } foreach (Block b in _blocks) { os.Write(b.buffer, 0, b.count); pm.Update(b.count / 1024); } }
public void SaveProject_with_false_should_execute_command() { var mocks = new MockRepository(); command = mocks.StrictMock <ICommand>(); command.Stub(c => c.Execute(NullProgressMonitor.CreateInstance())).IgnoreArguments(); string projectName = Paths.DefaultProject; commandFactory.Stub(cf => cf.CreateSaveProjectCommand(projectName)).Return(command); mocks.ReplayAll(); applicationController.SaveProject(false); command.VerifyAllExpectations(); }
public override ICollection Load(string location, ProjectData projectData, IWarningHandler warningHandler) { // Skip loading if the extension is not fully initalized unless we are not // running in Visual Studio (because we are running in MSTest instead). if (!TipShellExtension.IsInitialized && ShellEnvironment.IsRunningInVisualStudio) { return(EmptyArray <TestElement> .Instance); } // Explore the tests. ITestFrameworkManager testFrameworkManager = RuntimeAccessor.ServiceLocator.Resolve <ITestFrameworkManager>(); WarningLogger logger = new WarningLogger(warningHandler); ReflectionOnlyAssemblyLoader loader = new ReflectionOnlyAssemblyLoader(); loader.AddHintDirectory(Path.GetDirectoryName(location)); IAssemblyInfo assembly = loader.ReflectionPolicy.LoadAssemblyFrom(location); var testFrameworkSelector = new TestFrameworkSelector() { Filter = testFrameworkHandle => testFrameworkHandle.Id != "MSTestAdapter.TestFramework", FallbackMode = TestFrameworkFallbackMode.Approximate }; ITestDriver driver = testFrameworkManager.GetTestDriver(testFrameworkSelector, logger); TestExplorationOptions testExplorationOptions = new TestExplorationOptions(); ArrayList tests = new ArrayList(); MessageConsumer messageConsumer = new MessageConsumer() .Handle <TestDiscoveredMessage>(message => { if (message.Test.IsTestCase) { tests.Add(GallioTestElementFactory.CreateTestElement(message.Test, location, projectData)); } }) .Handle <AnnotationDiscoveredMessage>(message => { message.Annotation.Log(logger, true); }); driver.Describe(loader.ReflectionPolicy, new ICodeElementInfo[] { assembly }, testExplorationOptions, messageConsumer, NullProgressMonitor.CreateInstance()); return(tests); }
public override void MoveFile(FilePath source, FilePath dest) { IProgressMonitor monitor = new NullProgressMonitor(); Repository srcRepo = GetRepository(source); Repository dstRepo = GetRepository(dest); if (dstRepo != null && dstRepo.CanMoveFilesFrom(srcRepo, source, dest)) { srcRepo.MoveFile(source, dest, true, monitor); } else { CopyFile(source, dest, true); srcRepo.DeleteFile(source, true, monitor, false); } }
public override void MoveDirectory(FilePath sourcePath, FilePath destPath) { IProgressMonitor monitor = new NullProgressMonitor(); Repository srcRepo = GetRepository(sourcePath); Repository dstRepo = GetRepository(destPath); if (dstRepo.CanMoveFilesFrom(srcRepo, sourcePath, destPath)) { srcRepo.MoveDirectory(sourcePath, destPath, true, monitor); } else { CopyDirectory(sourcePath, destPath); srcRepo.DeleteDirectory(sourcePath, true, monitor, false); } }
private void RegisterLoadedPlugins() { string configurationFilePath = runtimeSetup.ConfigurationFilePath; if (configurationFilePath != null) { FileInfo configurationFile = new FileInfo(configurationFilePath); if (configurationFile.Exists) { var document = new XmlDocument(); document.Load(configurationFilePath); var gallioElement = document.SelectSingleNode("/configuration/gallio") as XmlElement; if (gallioElement != null) { LoadConfigurationData(gallioElement, pluginLoader, configurationFile.Directory); } } pluginLoader.AddPluginPath(configurationFilePath); } else { XmlNode sectionData = (XmlNode)ConfigurationManager.GetSection(GallioSectionHandler.SectionName); if (sectionData != null) { var gallioElement = sectionData as XmlElement; if (gallioElement != null) { LoadConfigurationData(gallioElement, pluginLoader, new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory)); } } } foreach (string path in pluginDirectories) { pluginLoader.AddPluginPath(path); } var pluginCatalog = new PluginCatalog(); pluginLoader.PopulateCatalog(pluginCatalog, NullProgressMonitor.CreateInstance()); pluginCatalog.ApplyTo(registry); }
private bool run(string[] args) { if (args.Length != 3) { Console.WriteLine("Usage: ServerSetup <repositoryURI> <userId> <password>"); return false; } String repositoryURI = args[0]; String userId = args[1]; String password = args[2]; IProgressMonitor monitor = new NullProgressMonitor(); ITeamRepository teamRepository = logIntoTeamRepository(repositoryURI, userId, password, monitor); throw new NotImplementedException(); }
void Load() { System.Threading.ThreadPool.QueueUserWorkItem(delegate { try { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); WebResponse resp = req.GetResponse(); MemoryStream ms = new MemoryStream(); using (var s = resp.GetResponseStream()) { byte[] buf = new byte [8092]; int nr; while ((nr = s.Read(buf, 0, buf.Length)) > 0) { ms.Write(buf, 0, nr); } } MonoDevelop.Ide.DispatchService.GuiSyncDispatch(delegate { Gdk.PixbufLoader l = new Gdk.PixbufLoader(resp.ContentType); l.Write(ms.ToArray()); image = l.Pixbuf; l.Close(); }); // Replace the async operation to avoid holding references to all // objects that subscribed the Completed event. loadOperation = NullAsyncOperation.Success; } catch (Exception ex) { loadMonitor.ReportError(null, ex); loadOperation = NullAsyncOperation.Failure; } var monitor = loadMonitor; Gtk.Application.Invoke(delegate { monitor.Dispose(); }); loadMonitor = null; }); }
///<summary> /// Constructor providing a command, task manager and keys parser. ///</summary> ///<param name="command">The command to use.</param> ///<param name="taskManager">The task manager to use.</param> ///<param name="keysParser">The keys parser to use.</param> public CommandToolStripMenuItem(MenuCommand command, ITaskManager taskManager, IKeysParser keysParser) : base(command.Text, command.Image) { Enabled = command.CanExecute; command.CanExecute.PropertyChanged += (s, e) => Enabled = command.CanExecute; if (taskManager != null) { Click += (s, e) => taskManager.QueueTask(command.Command); } else { Click += (s, e) => command.Command.Execute(NullProgressMonitor.CreateInstance()); } if (!string.IsNullOrEmpty(command.Shortcut)) { ShortcutKeys = keysParser.Parse(command.Shortcut.Replace(" ", "")); } }
public void SaveProject(bool queueTask) { var command = commandFactory.CreateSaveProjectCommand(projectFileName); if (queueTask) { taskManager.QueueTask(command); } else { // we're shutting down, so eat any errors try { command.Execute(NullProgressMonitor.CreateInstance()); } catch (Exception ex) { unhandledExceptionPolicy.Report("Error saving project", ex); } } }
public static void RenameNamespace(INamespace ns, string newName) { using (var monitor = new NullProgressMonitor()) { var col = ReferenceFinder.FindReferences(ns, true, monitor); List <Change> result = new List <Change> (); foreach (var memberRef in col) { var change = new TextReplaceChange(); change.FileName = memberRef.FileName; change.Offset = memberRef.Offset; change.RemovedChars = memberRef.Length; change.InsertedText = newName; change.Description = string.Format(GettextCatalog.GetString("Replace '{0}' with '{1}'"), memberRef.GetName(), newName); result.Add(change); } if (result.Count > 0) { RefactoringService.AcceptChanges(monitor, result); } } }
void LoadBuildVSConsoleProject(string vsVersion, string toolsVersion) { string solFile = Util.GetSampleProject("ConsoleApp-VS" + vsVersion, "ConsoleApplication.sln"); var monitor = new NullProgressMonitor(); var sol = (Solution)Services.ProjectService.ReadWorkspaceItem(monitor, solFile); Assert.IsTrue(monitor.Errors.Length == 0); Assert.IsTrue(monitor.Warnings.Length == 0); var p = (DotNetProject)sol.GetAllProjects().First(); Assert.AreEqual(toolsVersion, MSBuildProjectService.GetHandler(p).ToolsVersion); var r = sol.Build(monitor, "Debug"); Assert.IsTrue(monitor.Errors.Length == 0); Assert.IsTrue(monitor.Warnings.Length == 0); Assert.IsFalse(r.Failed); Assert.IsTrue(r.ErrorCount == 0); //there may be a single warning about not being able to find Client profile var f = r.Errors.FirstOrDefault(); var clientProfileError = "Unable to find framework corresponding to the target framework moniker " + "'.NETFramework,Version=v4.0,Profile=Client'"; if (f != null) { Assert.IsTrue(f.ErrorText.Contains(clientProfileError), "Build failed with: " + f.ErrorText); } string projectFile = ((Project)sol.Items [0]).FileName; string solXml = Util.ReadAllWithWindowsEndings(solFile); string projectXml = Util.ReadAllWithWindowsEndings(projectFile); sol.Save(monitor); Assert.IsTrue(monitor.Errors.Length == 0); Assert.IsTrue(monitor.Warnings.Length == 0); Assert.AreEqual(projectXml, Util.ReadAllWithWindowsEndings(projectFile)); }
private void RunWithProgressMonitor(Action <IProgressMonitor> action) { try { lock (this) { if (isCanceled) { return; } currentProgressMonitor = NullProgressMonitor.CreateInstance(); } action(currentProgressMonitor); } finally { lock (this) currentProgressMonitor = null; } }
public void PopulateCatalog_WhenPluginPathRefersToDirectoryWithAtLeastOnePluginFile_LoadsIt() { string pluginContents = GenerateValidPluginXml(); RunWithTemporaryPluginFile((pluginDir, pluginFile) => { var loader = new PluginLoader(); var catalog = MockRepository.GenerateMock <IPluginCatalog>(); loader.AddPluginPath(pluginDir); Plugin plugin = null; DirectoryInfo baseDirectory = null; catalog.Expect(x => x.AddPlugin(null, null)).IgnoreArguments() .Do((Gallio.Common.GallioAction <Plugin, DirectoryInfo>) delegate(Plugin pluginArg, DirectoryInfo baseDirectoryArg) { plugin = pluginArg; baseDirectory = baseDirectoryArg; }); loader.PopulateCatalog(catalog, NullProgressMonitor.CreateInstance()); catalog.VerifyAllExpectations(); // added one plugin Assert.Multiple(() => { Assert.AreEqual("pluginId", plugin.PluginId); Assert.AreEqual("serviceId", plugin.Services[0].ServiceId); Assert.AreEqual("componentId", plugin.Components[0].ComponentId); Assert.AreEqual("Assembly1", plugin.Assemblies[0].FullName); Assert.AreEqual("CodeBase.dll", plugin.Assemblies[0].CodeBase); Assert.AreEqual("Assembly2", plugin.Assemblies[1].FullName); Assert.AreEqual(pluginDir, baseDirectory.ToString()); }); }, pluginContents); }
private void sendPack() { bool thin = options.Contains(OPTION_THIN_PACK); bool progress = !options.Contains(OPTION_NO_PROGRESS); bool sideband = options.Contains(OPTION_SIDE_BAND) || options.Contains(OPTION_SIDE_BAND_64K); ProgressMonitor pm = new NullProgressMonitor(); Stream packOut = stream; if (sideband) { int bufsz = SideBandOutputStream.SMALL_BUF; if (options.Contains(OPTION_SIDE_BAND_64K)) bufsz = SideBandOutputStream.MAX_BUF; bufsz -= SideBandOutputStream.HDR_SIZE; packOut = new BufferedStream(new SideBandOutputStream(SideBandOutputStream.CH_DATA, pckOut), bufsz); if (progress) pm = new SideBandProgressMonitor(pckOut); } PackWriter pw; pw = new PackWriter(db, pm, new NullProgressMonitor()); pw.DeltaBaseAsOffset = options.Contains(OPTION_OFS_DELTA); pw.Thin = thin; pw.preparePack(wantAll, commonBase); if (options.Contains(OPTION_INCLUDE_TAG)) { foreach (Ref r in refs.Values) { RevObject o; try { o = walk.parseAny(r.ObjectId); } catch (IOException) { continue; } if (o.has(WANT) || !(o is RevTag)) continue; RevTag t = (RevTag) o; if (!pw.willInclude(t) && pw.willInclude(t.getObject())) pw.addObject(t); } } pw.writePack(packOut); if (sideband) { packOut.Flush(); pckOut.End(); } else { stream.Flush(); } }
public void Execute_should_reload_test_package() { command.Execute(NullProgressMonitor.CreateInstance()); loadPackageCommand.AssertWasCalled(c => c.Execute(Arg <IProgressMonitor> .Is.Anything)); }
/// <summary> /// Send this buffer to an output stream. /// <para /> /// This method may only be invoked After {@link #close()} has completed /// normally, to ensure all data is completely transferred. /// </summary> /// <param name="os">stream to send this buffer's complete content to.</param> /// <param name="pm"> /// if not null progress updates are sent here. Caller should /// initialize the task and the number of work units to /// <code><see cref="Length"/>/1024</code>. /// </param> public virtual void writeTo(Stream os, ProgressMonitor pm) { if (os == null) throw new ArgumentNullException("os"); if (pm == null) pm = new NullProgressMonitor(); foreach (Block b in _blocks) { os.Write(b.buffer, 0, b.count); pm.Update(b.count / 1024); } }
/** * Send this buffer to an output stream. * <para /> * This method may only be invoked After {@link #close()} has completed * normally, to ensure all data is completely transferred. * * @param os * stream to send this buffer's complete content to. * @param pm * if not null progress updates are sent here. Caller should * initialize the task and the number of work units to * <code>{@link #length()}/1024</code>. * @ * an error occurred reading from a temporary file on the local * system, or writing to the output stream. */ public void writeTo(Stream os, ProgressMonitor pm) { if (pm == null) pm = new NullProgressMonitor(); if (_blocks != null) { // Everything is in core so we can stream directly to the output. // foreach (Block b in _blocks) { os.Write(b.buffer, 0, b.count); pm.Update(b.count / 1024); } } else { // Reopen the temporary file and copy the contents. // using (var @in = new FileStream(_onDiskFile.FullName, System.IO.FileMode.Open, FileAccess.Read)) { int cnt; byte[] buf = new byte[Block.SZ]; while ((cnt = @in.Read(buf, 0, buf.Length)) > 0) { os.Write(buf, 0, cnt); pm.Update(cnt / 1024); } } } }