示例#1
0
文件: BlobsTest.cs 项目: jflam/RTVS
        public async Task CreateGetDestroyBlobs()
        {
            byte[] data1   = new byte[] { 0, 1, 2, 3, 4, 5 };
            byte[] data2   = new byte[] { 10, 11, 12, 13, 14, 15 };
            byte[] data3   = new byte[] { 20, 21, 22, 23, 24, 25 };
            var    dataSet = new byte[][] { data1, data2, data3 };

            using (DataTransferSession dts = new DataTransferSession(_session, null)) {
                var blob1 = await dts.SendBytesAsync(data1);

                var blob2 = await dts.SendBytesAsync(data2);

                var blob3 = await dts.SendBytesAsync(data3);

                blob1.Id.Should().BeGreaterThan(0);
                blob2.Id.Should().BeGreaterThan(0);
                blob3.Id.Should().BeGreaterThan(0);

                blob1.Id.Should().NotBe(blob2.Id);
                blob2.Id.Should().NotBe(blob3.Id);
                blob3.Id.Should().NotBe(blob1.Id);

                var blobIds = new IRBlobInfo[] { blob1, blob2, blob3 };

                for (int i = 0; i < blobIds.Length; ++i)
                {
                    var blob = await dts.FetchBytesAsync(blobIds[i], false);

                    blob.Should().Equal(dataSet[i]);
                }
            }
        }
示例#2
0
        public async Task <string> EditFileAsync(string content, string fileName, CancellationToken cancellationToken = default(CancellationToken))
        {
            TaskUtilities.AssertIsOnBackgroundThread();
            var editor = _coreShell.GetService <IFileEditor>();

            if (!string.IsNullOrEmpty(content))
            {
                return(await editor.EditFileAsync(content, null, cancellationToken));
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                if (_session.IsRemote)
                {
                    using (var dts = new DataTransferSession(_session, _fileSystem)) {
                        // TODO: handle progress for large files
                        try {
                            await dts.FetchFileToLocalTempAsync(fileName.ToRPath(), null, cancellationToken);

                            fileName = _fileSystem.GetDownloadsPath(Path.GetFileName(fileName));
                            return(await editor.EditFileAsync(null, fileName, cancellationToken));
                        } catch (OperationCanceledException) { }
                    }
                }
                return(await editor.EditFileAsync(null, fileName, cancellationToken));
            }
            return(string.Empty);
        }
示例#3
0
        private async Task RMarkdownRenderAsync(IRSession session, IFileSystem fs, string inputFilePath, string outputFilePath, string format, int codePage, IApplicationShell appShell)
        {
            using (var fts = new DataTransferSession(session, fs)) {
                string       currentStatusText = string.Empty;
                uint         cookie            = 0;
                IVsStatusbar statusBar         = null;
                appShell.DispatchOnUIThread(() => {
                    statusBar = appShell.GlobalServices.GetService <IVsStatusbar>(typeof(SVsStatusbar));
                    statusBar.GetText(out currentStatusText);
                    statusBar.Progress(ref cookie, 1, "", 0, 0);
                });

                try {
                    // TODO: progress and cancellation handling
                    appShell.DispatchOnUIThread(() => { statusBar?.Progress(ref cookie, 1, Resources.Info_MarkdownSendingInputFile.FormatInvariant(Path.GetFileName(inputFilePath)), 0, 3); });
                    var rmd = await fts.SendFileAsync(inputFilePath, true, null, CancellationToken.None);

                    appShell.DispatchOnUIThread(() => { statusBar?.Progress(ref cookie, 1, Resources.Info_MarkdownPublishingFile.FormatInvariant(Path.GetFileName(inputFilePath)), 1, 3); });
                    var publishResult = await session.EvaluateAsync <ulong>($"rtvs:::rmarkdown_publish(blob_id = {rmd.Id}, output_format = {format.ToRStringLiteral()}, encoding = 'cp{codePage}')", REvaluationKind.Normal);

                    appShell.DispatchOnUIThread(() => { statusBar?.Progress(ref cookie, 1, Resources.Info_MarkdownGetOutputFile.FormatInvariant(Path.GetFileName(outputFilePath)), 2, 3); });
                    await fts.FetchFileAsync(new RBlobInfo(publishResult), outputFilePath, true, null, CancellationToken.None);

                    appShell.DispatchOnUIThread(() => { statusBar?.Progress(ref cookie, 1, Resources.Info_MarkdownPublishComplete.FormatInvariant(Path.GetFileName(outputFilePath)), 3, 3); });
                } finally {
                    appShell.DispatchOnUIThread(() => {
                        statusBar?.Progress(ref cookie, 0, "", 0, 0);
                        statusBar?.SetText(currentStatusText);
                    });
                }
            }
        }
示例#4
0
 private async Task CopyFileAsync(string path, HttpListenerContext context, CancellationToken ct)
 {
     using (DataTransferSession dts = new DataTransferSession(_session, FileSystem)) {
         await dts.CopyToFileStreamAsync(path, context.Response.OutputStream, true, null, ct);
     }
     context.Response.OutputStream.Close();
 }
示例#5
0
        public async Task CompressedBlob()
        {
            var createResult = await _session.EvaluateAsync("rtvs:::create_blob(raw(1000000))", REvaluationKind.Normal);

            createResult.Result.Should().NotBeNull();

            var createCompressedResult = await _session.EvaluateAsync("rtvs:::create_compressed_blob(raw(1000000))", REvaluationKind.Normal);

            createCompressedResult.Result.Should().NotBeNull();

            var blobId  = ((JValue)createResult.Result).Value <ulong>();
            var blobId2 = ((JValue)createCompressedResult.Result).Value <ulong>();

            using (DataTransferSession dts = new DataTransferSession(_session, new WindowsFileSystem())) {
                var expectedData = await dts.FetchBytesAsync(new RBlobInfo(blobId), true, null, CancellationToken.None);

                var compressedData = await dts.FetchBytesAsync(new RBlobInfo(blobId2), true, null, CancellationToken.None);

                compressedData.Length.Should().BeLessThan(expectedData.Length);

                var actualData = await dts.FetchAndDecompressBytesAsync(new RBlobInfo(blobId2), true, null, CancellationToken.None);

                actualData.Should().Equal(expectedData);
            }
        }
示例#6
0
        public async Task <string> FetchFileAsync(string remoteFileName, ulong remoteBlobId, string localPath, CancellationToken cancellationToken)
        {
            await _coreShell.SwitchToMainThreadAsync(cancellationToken);

            if (!string.IsNullOrEmpty(localPath))
            {
                if (_fileSystem.DirectoryExists(localPath))
                {
                    localPath = Path.Combine(localPath, remoteFileName);
                }
            }
            else
            {
                localPath = _fileSystem.GetDownloadsPath(remoteFileName);
            }

            try {
                var message = Resources.Progress_FetchingFile.FormatInvariant(remoteFileName);
                _coreShell.ProgressDialog.Show(async(progress, ct) => {
                    using (DataTransferSession dts = new DataTransferSession(_session, _fileSystem)) {
                        await dts.FetchAndDecompressFileAsync(remoteBlobId, localPath, progress, message, cancellationToken);
                    }
                }, message);
            } catch (Exception ex) {
                _coreShell.ShowErrorMessage(Resources.Error_UnableToTransferFile.FormatInvariant(localPath, ex.Message));
                return(string.Empty);
            }
            return(localPath);
        }
示例#7
0
        private async Task SendProjectAsync(EnvDTE.Project project, string remotePath, string filterString, CancellationToken cancellationToken)
        {
            Console.WriteLine(Resources.Info_PreparingProjectForTransfer);

            var projectDir  = Path.GetDirectoryName(project.FullName);
            var projectName = Path.GetFileNameWithoutExtension(project.FullName);

            string[] filterSplitter = { ";" };
            Matcher  matcher        = new Matcher(StringComparison.InvariantCultureIgnoreCase);

            matcher.AddIncludePatterns(filterString.Split(filterSplitter, StringSplitOptions.RemoveEmptyEntries));

            Console.WriteLine(Resources.Info_RemoteDestination.FormatInvariant(remotePath));
            Console.WriteLine(Resources.Info_FileTransferFilter.FormatInvariant(filterString));
            Console.WriteLine(Resources.Info_CompressingFiles);

            var compressedFilePath = FileSystem.CompressDirectory(projectDir, matcher, new Progress <string>((p) => {
                Console.WriteLine(Resources.Info_LocalFilePath.FormatInvariant(p));
                string dest = p.MakeRelativePath(projectDir).ProjectRelativePathToRemoteProjectPath(remotePath, projectName);
                Console.WriteLine(Resources.Info_RemoteFilePath.FormatInvariant(dest));
            }), CancellationToken.None);

            using (var fts = new DataTransferSession(Session, FileSystem)) {
                Console.WriteLine(Resources.Info_TransferringFiles);
                var remoteFile = await fts.SendFileAsync(compressedFilePath, true, null, cancellationToken);

                await Session.EvaluateAsync <string>($"rtvs:::save_to_project_folder({remoteFile.Id}, {projectName.ToRStringLiteral()}, '{remotePath.ToRPath()}')", REvaluationKind.Normal, cancellationToken);
            }

            Console.WriteLine(Resources.Info_TransferringFilesDone);
        }
示例#8
0
        public async Task CreateGetDestroyBlobs() {
            byte[] data1 = new byte[] { 0, 1, 2, 3, 4, 5 };
            byte[] data2 = new byte[] { 10, 11, 12, 13, 14, 15 };
            byte[] data3 = new byte[] { 20, 21, 22, 23, 24, 25 };
            var dataSet = new byte[][] { data1, data2, data3 };

            using (DataTransferSession dts = new DataTransferSession(_session, null)) {
                var blob1 = await dts.SendBytesAsync(data1, true, null, CancellationToken.None);
                var blob2 = await dts.SendBytesAsync(data2, true, null, CancellationToken.None);
                var blob3 = await dts.SendBytesAsync(data3, true, null, CancellationToken.None);

                blob1.Id.Should().BeGreaterThan(0);
                blob2.Id.Should().BeGreaterThan(0);
                blob3.Id.Should().BeGreaterThan(0);

                blob1.Id.Should().NotBe(blob2.Id);
                blob2.Id.Should().NotBe(blob3.Id);
                blob3.Id.Should().NotBe(blob1.Id);

                var blobIds = new IRBlobInfo[] { blob1, blob2, blob3 };

                for (int i = 0; i < blobIds.Length; ++i) {
                    var blob = await dts.FetchBytesAsync(blobIds[i], false, null, CancellationToken.None);
                    blob.Should().Equal(dataSet[i]);
                }
            }
        }
示例#9
0
 public async Task CreateBlob_DisconnectedFromTheStart() {
     using (var session = new RSession(0, _brokerClient, new AsyncReaderWriterLock().CreateExclusiveReaderLock(), () => { })) {
         var data = new byte[] { 1, 2, 3, 4, 5 };
         using (DataTransferSession dts = new DataTransferSession(session, null)) {
             Func<Task> f = () => dts.SendBytesAsync(data, false, null, CancellationToken.None);
             await f.ShouldThrowAsync<RHostDisconnectedException>();
         }
     }
 }
示例#10
0
 public async Task CreateBlob_DisconnectedFromTheStart()
 {
     using (var session = new RSession(0, _brokerClient, () => { })) {
         var data = new byte[] { 1, 2, 3, 4, 5 };
         using (DataTransferSession dts = new DataTransferSession(session, null)) {
             Func <Task> f = () => dts.SendBytesAsync(data, false);
             await f.ShouldThrowAsync <RHostDisconnectedException>();
         }
     }
 }
示例#11
0
        private async Task RMarkdownRenderAsync(IRSession session, IFileSystem fs, string inputFilePath, string outputFilePath, string format, int codePage)
        {
            using (var fts = new DataTransferSession(session, fs)) {
                var rmd = await fts.SendFileAsync(inputFilePath);

                var publishResult = await session.EvaluateAsync <ulong>($"rtvs:::rmarkdown_publish(blob_id = {rmd.Id}, output_format = {format.ToRStringLiteral()}, encoding = 'cp{codePage}')", REvaluationKind.Normal);

                await fts.FetchFileAsync(new RBlobInfo(publishResult), outputFilePath);
            }
        }
示例#12
0
 public async Task CreateBlob_DisconnectedFromTheStart()
 {
     using (var session = new RSession(0, _testMethod.FileSystemSafeName, _fileSystem, _brokerClient, new AsyncReaderWriterLock().CreateExclusiveReaderLock(), () => { })) {
         var data = new byte[] { 1, 2, 3, 4, 5 };
         using (DataTransferSession dts = new DataTransferSession(session, null)) {
             Func <Task> f = () => dts.SendBytesAsync(data, false, null, CancellationToken.None);
             await f.ShouldThrowAsync <RHostDisconnectedException>();
         }
     }
 }
示例#13
0
        private async Task ExportToImageAsync(IRSession session, string format, string filePath, int widthInPixels, int heightInPixels, int resolution)
        {
            string script = String.Format(@"
device_id <- rtvs:::graphics.ide.getactivedeviceid()
rtvs:::export_to_image(device_id, rtvs:::graphics.ide.getactiveplotid(device_id), {0}, {1}, {2}, {3})
", format, widthInPixels, heightInPixels, resolution);
            var    blobid = await session.EvaluateAsync <ulong>(script, REvaluationKind.Normal);

            using (DataTransferSession dts = new DataTransferSession(session, new FileSystem())) {
                await dts.FetchFileAsync(new RBlobInfo(blobid), filePath, true, null, CancellationToken.None);
            }
        }
示例#14
0
            public async Task CreateBlob_DisconnectedDuringCreate() {
                var data = new byte[25 * 1024 * 1024]; // try to send a massive blob

                ManualResetEvent testStarted = new ManualResetEvent(false);
                using (DataTransferSession dts = new DataTransferSession(_session, null)) {
                    Func<Task> f = () => dts.SendBytesAsync(data, false, null, CancellationToken.None);
                    var assertion = f.ShouldThrowAsync<RHostDisconnectedException>();
                    await Task.Delay(100);
                    await _session.StopHostAsync();
                    await assertion;
                }
            }
示例#15
0
 private async Task ExportAsync(string outputFilePath, Task <ulong> exportTask)
 {
     try {
         var result = await exportTask;
         using (DataTransferSession dts = new DataTransferSession(InteractiveWorkflow.RSession, _fileSystem)) {
             await dts.FetchFileAsync(new RBlobInfo(result), outputFilePath);
         }
     } catch (IOException ex) {
         throw new RPlotManagerException(ex.Message, ex);
     } catch (RException ex) {
         throw new RPlotManagerException(string.Format(CultureInfo.InvariantCulture, Resources.Plots_EvalError, ex.Message), ex);
     }
 }
示例#16
0
            public async Task CreateBlob_DisconnectedDuringCreate()
            {
                var data = new byte[25 * 1024 * 1024]; // try to send a massive blob

                using (DataTransferSession dts = new DataTransferSession(_session, null)) {
                    Func <Task> f         = () => dts.SendBytesAsync(data, false, null, CancellationToken.None);
                    var         assertion = f.ShouldThrowAsync <RHostDisconnectedException>();
                    await Task.Delay(100);

                    await _session.StopHostAsync();

                    await assertion;
                }
            }
示例#17
0
        private async Task <IEnumerable <string> > ExportToPdfAsync(string[] inputs, string filePath, int width, int height)
        {
            var app = new RHostClientTestApp {
                PlotHandler = OnPlot, PlotDeviceCreateHandler = OnDeviceCreate, PlotDeviceDestroyHandler = OnDeviceDestroy
            };

            using (var sessionProvider = new RSessionProvider(TestCoreServices.CreateReal())) {
                await sessionProvider.TrySwitchBrokerAsync(nameof(IdeGraphicsDeviceTest));

                var session = sessionProvider.GetOrCreate(Guid.NewGuid());
                await session.StartHostAsync(new RHostStartupInfo {
                    Name = _testMethod.Name
                }, app, 50000);

                foreach (var input in inputs)
                {
                    using (var interaction = await session.BeginInteractionAsync()) {
                        await interaction.RespondAsync(input.EnsureLineBreak());
                    }
                }

                string script = String.Format(@"
device_id <- rtvs:::graphics.ide.getactivedeviceid()
rtvs:::export_to_pdf(device_id, rtvs:::graphics.ide.getactiveplotid(device_id), {0}, {1})
", width, height);
                var    blobid = await session.EvaluateAsync <ulong>(script, REvaluationKind.Normal);

                using (DataTransferSession dts = new DataTransferSession(session, new FileSystem())) {
                    await dts.FetchFileAsync(new RBlobInfo(blobid), filePath);
                }

                await session.StopHostAsync();
            }
            // Ensure that all plot files created by the graphics device have been deleted
            foreach (var plot in OriginalPlotMessages)
            {
                File.Exists(plot.FilePath).Should().BeFalse();
            }

            return(PlotFilePaths.AsReadOnly());
        }
示例#18
0
        private async Task RMarkdownRenderAsync(IRSession session, string inputFilePath, string outputFilePath, string format, int codePage, IServiceContainer services)
        {
            using (var fts = new DataTransferSession(session, services.FileSystem())) {
                var statusBar = services.GetService <IStatusBar>();
                using (var progress = await statusBar.ShowProgressAsync(3)) {
                    // TODO: cancellation handling
                    progress.Report(new StatusBarProgressData(Resources.Info_MarkdownSendingInputFile.FormatInvariant(Path.GetFileName(inputFilePath)), 0));

                    var rmd = await fts.SendFileAsync(inputFilePath, true, null, CancellationToken.None);

                    progress.Report(new StatusBarProgressData(Resources.Info_MarkdownPublishingFile.FormatInvariant(Path.GetFileName(inputFilePath)), 1));

                    var publishResult = await session.EvaluateAsync <ulong>($"rtvs:::rmarkdown_publish(blob_id = {rmd.Id}, output_format = {format.ToRStringLiteral()}, encoding = 'cp{codePage}')", REvaluationKind.Normal);

                    progress.Report(new StatusBarProgressData(Resources.Info_MarkdownGetOutputFile.FormatInvariant(Path.GetFileName(outputFilePath)), 2));
                    await fts.FetchFileAsync(new RBlobInfo(publishResult), outputFilePath, true, null, CancellationToken.None);

                    progress.Report(new StatusBarProgressData(Resources.Info_MarkdownPublishComplete.FormatInvariant(Path.GetFileName(outputFilePath)), 3));
                }
            }
        }
示例#19
0
            public async Task GetBlob_CanceledDuringGet()
            {
                var cts  = new CancellationTokenSource();
                var data = new byte[1024 * 1024];

                IRBlobInfo blob = null;

                using (DataTransferSession dts = new DataTransferSession(_session, null)) {
                    blob = await dts.SendBytesAsync(data, false, null, CancellationToken.None);
                }

                Func <Task> f = async() => {
                    while (true)
                    {
                        await _session.BlobReadAllAsync(blob.Id, ct : cts.Token);
                    }
                };
                var assertion = f.ShouldThrowAsync <OperationCanceledException>();

                cts.CancelAfter(1);
                await assertion;
            }
示例#20
0
        public async Task ViewFile(string fileName, string tabName, bool deleteFile, CancellationToken cancellationToken = default(CancellationToken))
        {
            var viewer = _coreShell.GetService <IObjectViewer>();
            var task   = Task.CompletedTask;

            if (_session.IsRemote)
            {
                using (var dts = new DataTransferSession(_session, _fileSystem)) {
                    // TODO: handle progress for large files
                    try {
                        await dts.FetchFileToLocalTempAsync(fileName.ToRPath(), null, cancellationToken);

                        fileName = _fileSystem.GetDownloadsPath(Path.GetFileName(fileName));
                        await viewer?.ViewFile(fileName, tabName, deleteFile, cancellationToken);
                    } catch (REvaluationException) { } catch (RHostDisconnectedException) { }
                }
            }
            else
            {
                await viewer?.ViewFile(fileName, tabName, deleteFile, cancellationToken);
            }
        }
示例#21
0
        private static async Task CreateCsvAndStartProcess(IREvaluationResultInfo result, IRSession session, string fileName, IFileSystem fileSystem, IProgress <ProgressDialogData> progress)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            var sep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
            var dec = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

            using (var e = await session.BeginEvaluationAsync()) {
                var csvDataBlobId = await e.EvaluateAsync <ulong>($"rtvs:::export_to_csv({result.Expression}, sep={sep.ToRStringLiteral()}, dec={dec.ToRStringLiteral()})", REvaluationKind.Normal);

                using (DataTransferSession dts = new DataTransferSession(session, fileSystem)) {
                    var total = await session.GetBlobSizeAsync(csvDataBlobId, CancellationToken.None);

                    progress.Report(new ProgressDialogData(0, statusBarText: Resources.Status_WritingCSV, waitMessage: Resources.Status_WritingCSV));
                    await dts.FetchFileAsync(new RBlobInfo(csvDataBlobId), fileName, true, new Progress <long>(b => {
                        var step = (int)(b * 100 / total);
                        progress.Report(new ProgressDialogData(step, statusBarText: Resources.Status_WritingCSV, waitMessage: Resources.Status_WritingCSV));
                    }));

                    progress.Report(new ProgressDialogData(100, statusBarText: Resources.Status_WritingCSV, waitMessage: Resources.Status_WritingCSV));
                }
            }
        }
示例#22
0
            public async Task GetBlob_DisconnectedDuringGet()
            {
                var data = new byte[1024 * 1024];

                IRBlobInfo blob = null;

                using (DataTransferSession dts = new DataTransferSession(_session, null)) {
                    blob = await dts.SendBytesAsync(data, false, null, CancellationToken.None);
                }

                using (RBlobStream blobStream = await RBlobStream.OpenAsync(blob, _session)) {
                    Func <Task> f = async() => {
                        using (MemoryStream ms = new MemoryStream()) {
                            await blobStream.CopyToAsync(ms, 1024);
                        }
                    };
                    await Task.Delay(100);

                    await _session.StopHostAsync();

                    await f.ShouldThrowAsync <RHostDisconnectedException>();
                }
            }
示例#23
0
        public async Task <CommandResult> InvokeAsync()
        {
            string filePath = GetFilePath();

            if (filePath == null)
            {
                return(CommandResult.NotSupported);
            }

            var textView     = GetActiveTextView();
            var activeWindow = _interactiveWorkflow.ActiveWindow;

            if (textView == null || activeWindow == null)
            {
                return(CommandResult.NotSupported);
            }

            _interactiveWorkflow.Shell.SaveFileIfDirty(filePath);
            activeWindow.Container.Show(focus: false, immediate: false);

            var session = _interactiveWorkflow.RSession;

            if (session.IsRemote)
            {
                using (DataTransferSession dts = new DataTransferSession(_interactiveWorkflow.RSession, new FileSystem())) {
                    // TODO: add progress indication and cancellation
                    string remotePath = await dts.CopyFileToRemoteTempAsync(filePath, true, null, CancellationToken.None);

                    await _interactiveWorkflow.Operations.SourceFileAsync(remotePath, _echo, textView.TextBuffer.GetEncoding());
                }
            }
            else
            {
                await _interactiveWorkflow.Operations.SourceFileAsync(filePath, _echo, textView.TextBuffer.GetEncoding());
            }
            return(CommandResult.Executed);
        }
示例#24
0
        private static async Task CreateCsvAndStartProcess(
            IREvaluationResultInfo result,
            IRSession session,
            ICoreShell coreShell,
            string fileName,
            IFileSystem fileSystem,
            IProgress <ProgressDialogData> progress,
            CancellationToken cancellationToken)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            var sep = CultureInfo.CurrentCulture.TextInfo.ListSeparator;
            var dec = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;

            try {
                var csvDataBlobId = await session.EvaluateAsync <ulong>($"rtvs:::export_to_csv({result.Expression}, sep={sep.ToRStringLiteral()}, dec={dec.ToRStringLiteral()})", REvaluationKind.Normal, cancellationToken);

                using (DataTransferSession dts = new DataTransferSession(session, fileSystem)) {
                    await dts.FetchAndDecompressFileAsync(csvDataBlobId, fileName, progress, Resources.Status_WritingCSV, cancellationToken);
                }
            } catch (RException) {
                await coreShell.ShowErrorMessageAsync(Resources.Error_CannotExportToCsv, cancellationToken);
            }
        }
示例#25
0
        public async Task CompressedZeroSizedBlob() {
            var createResult = await _session.EvaluateAsync("rtvs:::create_blob(raw())", REvaluationKind.Normal);
            createResult.Result.Should().NotBeNull();

            var createCompressedResult = await _session.EvaluateAsync("rtvs:::create_compressed_blob(raw())", REvaluationKind.Normal);
            createCompressedResult.Result.Should().NotBeNull();

            var blobId = ((JValue)createResult.Result).Value<ulong>();
            var blobId2 = ((JValue)createCompressedResult.Result).Value<ulong>();

            using (DataTransferSession dts = new DataTransferSession(_session, new FileSystem())) {
                var expectedData = await dts.FetchBytesAsync(new RBlobInfo(blobId), true, null, CancellationToken.None);
                var actualData = await dts.FetchAndDecompressBytesAsync(new RBlobInfo(blobId2), true, null, CancellationToken.None);
                actualData.Should().Equal(expectedData);
            }
        }
示例#26
0
        private async Task SendToRemoteWorkerAsync(IEnumerable <string> files, string projectDir, string projectName, string remotePath, IProgress <ProgressDialogData> progress, CancellationToken ct)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            var      workflow = _interactiveWorkflowProvider.GetOrCreate();
            IConsole console  = new InteractiveWindowConsole(workflow);

            try {
                var session = workflow.RSession;
                int count   = 0;
                int total   = files.Count();

                progress.Report(new ProgressDialogData(0, Resources.Info_CompressingFiles));

                if (ct.IsCancellationRequested)
                {
                    return;
                }

                List <string> paths = new List <string>();
                // Compression phase : 1 of 3 phases.
                string compressedFilePath = string.Empty;
                compressedFilePath = _fs.CompressFiles(files, projectDir, new Progress <string>((p) => {
                    Interlocked.Increment(ref count);
                    int step = (count * 100 / total) / 3; // divide by 3, this is for compression phase.
                    progress.Report(new ProgressDialogData(step, Resources.Info_CompressingFile.FormatInvariant(Path.GetFileName(p), _fs.FileSize(p))));
                    string dest = p.MakeRelativePath(projectDir).ProjectRelativePathToRemoteProjectPath(remotePath, projectName);
                    paths.Add($"{Resources.Info_LocalFilePath.FormatInvariant(p)}{Environment.NewLine}{Resources.Info_RemoteFilePath.FormatInvariant(dest)}");
                }), ct);

                if (ct.IsCancellationRequested)
                {
                    return;
                }

                using (var fts = new DataTransferSession(session, _fs)) {
                    long size = _fs.FileSize(compressedFilePath);

                    // Transfer phase: 2 of 3 phases
                    var remoteFile = await fts.SendFileAsync(compressedFilePath, true, new Progress <long>((b) => {
                        int step = 33;                                         // start with 33% to indicate compression phase is done.
                        step += (int)((((double)b / (double)size) * 100) / 3); // divide by 3, this is for transfer phase.
                        progress.Report(new ProgressDialogData(step, Resources.Info_TransferringFilesWithSize.FormatInvariant(b, size)));
                    }), ct);

                    if (ct.IsCancellationRequested)
                    {
                        return;
                    }

                    // Extract phase: 3 of 3 phases
                    // start with 66% completion to indicate compression and transfer phases are done.
                    progress.Report(new ProgressDialogData(66, Resources.Info_ExtractingFilesInRHost));
                    await session.EvaluateAsync <string>($"rtvs:::save_to_project_folder({remoteFile.Id}, {projectName.ToRStringLiteral()}, '{remotePath.ToRPath()}')", REvaluationKind.Normal, ct);

                    progress.Report(new ProgressDialogData(100, Resources.Info_TransferringFilesDone));

                    paths.ForEach((s) => console.WriteLine(s));
                }
            } catch (TaskCanceledException) {
                console.WriteErrorLine(Resources.Info_FileTransferCanceled);
            } catch (RHostDisconnectedException rhdex) {
                console.WriteErrorLine(Resources.Error_CannotTransferNoRSession.FormatInvariant(rhdex.Message));
            } catch (Exception ex) when(ex is UnauthorizedAccessException || ex is IOException)
            {
                _ui.ShowErrorMessage(Resources.Error_CannotTransferFile.FormatInvariant(ex.Message));
            }
        }
示例#27
0
            public async Task GetBlob_DisconnectedDuringGet() {
                var data = new byte[1024 * 1024];

                IRBlobInfo blob = null;
                using (DataTransferSession dts = new DataTransferSession(_session, null)) {
                    blob = await dts.SendBytesAsync(data, false, null, CancellationToken.None);
                }

                using (RBlobStream blobStream = await RBlobStream.OpenAsync(blob, _session)) {
                    Func<Task> f = async () => {
                        using (MemoryStream ms = new MemoryStream()) {
                            await blobStream.CopyToAsync(ms, 1024);
                        }
                    };
                    await Task.Delay(100);
                    await _session.StopHostAsync();
                    await f.ShouldThrowAsync<RHostDisconnectedException>();
                }
            }
示例#28
0
        private async Task ExportToImageAsync(IRSession session, string format, string filePath, int widthInPixels,int heightInPixels, int resolution) {
            string script = String.Format(@"
device_id <- rtvs:::graphics.ide.getactivedeviceid()
rtvs:::export_to_image(device_id, rtvs:::graphics.ide.getactiveplotid(device_id), {0}, {1}, {2}, {3})
", format, widthInPixels, heightInPixels, resolution);
            var blobid = await session.EvaluateAsync<ulong>(script, REvaluationKind.Normal);

            using(DataTransferSession dts = new DataTransferSession(session, new FileSystem())) {
                await dts.FetchFileAsync(new RBlobInfo(blobid), filePath, true, null, CancellationToken.None);
            }
        }
示例#29
0
            public async Task GetBlob_CanceledDuringGet() {
                var cts = new CancellationTokenSource();
                var data = new byte[1024 * 1024];

                IRBlobInfo blob = null;
                using (DataTransferSession dts = new DataTransferSession(_session, null)) {
                    blob = await dts.SendBytesAsync(data, false, null, CancellationToken.None);
                }

                Func<Task> f = async () => {
                    while (true) {
                        await _session.BlobReadAllAsync(blob.Id, ct: cts.Token);
                    }
                };
                var assertion = f.ShouldThrowAsync<OperationCanceledException>();
                cts.CancelAfter(1);
                await assertion;
            }
示例#30
0
        private async Task<IEnumerable<string>> ExportToPdfAsync(string[] inputs, string filePath, int width, int height) {
            var app = new RHostClientTestApp { PlotHandler = OnPlot, PlotDeviceCreateHandler = OnDeviceCreate, PlotDeviceDestroyHandler = OnDeviceDestroy };
            using (var sessionProvider = new RSessionProvider(TestCoreServices.CreateReal())) {
                await sessionProvider.TrySwitchBrokerAsync(nameof(IdeGraphicsDeviceTest));
                var session = sessionProvider.GetOrCreate(Guid.NewGuid());
                await session.StartHostAsync(new RHostStartupInfo {
                    Name = _testMethod.Name
                }, app, 50000);

                foreach (var input in inputs) {
                    using (var interaction = await session.BeginInteractionAsync()) {
                        await interaction.RespondAsync(input.EnsureLineBreak());
                    }
                }

                string script = String.Format(@"
device_id <- rtvs:::graphics.ide.getactivedeviceid()
rtvs:::export_to_pdf(device_id, rtvs:::graphics.ide.getactiveplotid(device_id), {0}, {1})
", width, height);
                var blobid = await session.EvaluateAsync<ulong>(script, REvaluationKind.Normal);
                using (DataTransferSession dts = new DataTransferSession(session, new FileSystem())) {
                    await dts.FetchFileAsync(new RBlobInfo(blobid), filePath, true, null, CancellationToken.None);
                }

                await session.StopHostAsync();
            }
            // Ensure that all plot files created by the graphics device have been deleted
            foreach (var plot in OriginalPlotMessages) {
                File.Exists(plot.FilePath).Should().BeFalse();
            }

            return PlotFilePaths.AsReadOnly();
        }
示例#31
0
        private async Task <bool> SendToRemoteWorkerAsync(IEnumerable <string> files, string projectDir, string projectName, string remotePath, IVsStatusbar statusBar)
        {
            await TaskUtilities.SwitchToBackgroundThread();

            string currentStatusText;

            statusBar.GetText(out currentStatusText);

            var  workflow     = _interactiveWorkflowProvider.GetOrCreate();
            var  outputWindow = workflow.ActiveWindow.InteractiveWindow;
            uint cookie       = 0;

            try {
                var session = workflow.RSession;
                statusBar.SetText(Resources.Info_CompressingFiles);
                statusBar.Progress(ref cookie, 1, "", 0, 0);

                int    count = 0;
                uint   total = (uint)files.Count() * 2; // for compressing and sending
                string compressedFilePath = string.Empty;
                await Task.Run(() => {
                    compressedFilePath = _fs.CompressFiles(files, projectDir, new Progress <string>((p) => {
                        Interlocked.Increment(ref count);
                        statusBar.Progress(ref cookie, 1, string.Format(Resources.Info_CompressingFile, Path.GetFileName(p)), (uint)count, total);
                        string dest = p.MakeRelativePath(projectDir).ProjectRelativePathToRemoteProjectPath(remotePath, projectName);
                        _appShell.DispatchOnUIThread(() => {
                            outputWindow.WriteLine(string.Format(Resources.Info_LocalFilePath, p));
                            outputWindow.WriteLine(string.Format(Resources.Info_RemoteFilePath, dest));
                        });
                    }), CancellationToken.None);
                    statusBar.Progress(ref cookie, 0, "", 0, 0);
                });

                using (var fts = new DataTransferSession(session, _fs)) {
                    cookie = 0;
                    statusBar.SetText(Resources.Info_TransferringFiles);

                    total = (uint)_fs.FileSize(compressedFilePath);

                    var remoteFile = await fts.SendFileAsync(compressedFilePath, true, new Progress <long>((b) => {
                        statusBar.Progress(ref cookie, 1, Resources.Info_TransferringFiles, (uint)b, total);
                    }));

                    statusBar.SetText(Resources.Info_ExtractingFilesInRHost);
                    await session.EvaluateAsync <string>($"rtvs:::save_to_project_folder({remoteFile.Id}, {projectName.ToRStringLiteral()}, '{remotePath.ToRPath()}')", REvaluationKind.Normal);

                    _appShell.DispatchOnUIThread(() => {
                        outputWindow.WriteLine(Resources.Info_TransferringFilesDone);
                    });
                }
            } catch (UnauthorizedAccessException uaex) {
                _appShell.ShowErrorMessage(string.Format(CultureInfo.InvariantCulture, Resources.Error_CannotTransferFile, uaex.Message));
            } catch (IOException ioex) {
                _appShell.ShowErrorMessage(string.Format(CultureInfo.InvariantCulture, Resources.Error_CannotTransferFile, ioex.Message));
            } catch (RHostDisconnectedException rhdex) {
                _appShell.DispatchOnUIThread(() => {
                    outputWindow.WriteErrorLine(Resources.Error_CannotTransferNoRSession.FormatInvariant(rhdex.Message));
                });
            } finally {
                statusBar.Progress(ref cookie, 0, "", 0, 0);
                statusBar.SetText(currentStatusText);
            }

            return(true);
        }