Exemplo n.º 1
0
 protected virtual bool CheckPrerequisites()
 {
     if (!IOExtensions.ExistsOnPath("pandoc.exe"))
     {
         _coreShell.ShowErrorMessage(Resources.Error_PandocMissing);
         _pss.Start("http://pandoc.org/installing.html");
         return(false);
     }
     return(true);
 }
Exemplo n.º 2
0
        protected virtual async Task <bool> CheckPrerequisitesAsync()
        {
            if (!await CheckExecutableExistsOnPathAsync("pandoc"))
            {
                var session = _workflowProvider.GetOrCreate().RSession;
                var message = session.IsRemote ? Resources.Error_PandocMissingRemote : Resources.Error_PandocMissingLocal;
                await Services.ShowErrorMessageAsync(message);

                _pss.Start("https://pandoc.org/installing.html");
                return(false);
            }
            return(true);
        }
Exemplo n.º 3
0
        private async Task <string> ExecuteCommandAsync(string arguments, string outputPrefix, int timeoutms, bool failOnTimeout = true, CancellationToken ct = default)
        {
            var printOutput = outputPrefix != null;

            await TaskUtilities.SwitchToBackgroundThread();

            var docker = GetLocalDocker();
            var psi    = new ProcessStartInfo {
                CreateNoWindow         = true,
                FileName               = docker.DockerCommandPath,
                Arguments              = arguments,
                RedirectStandardError  = true,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false
            };

            var process = _ps.Start(psi);
            var result  = new StringBuilder();

            try {
                while (!process.StandardOutput.EndOfStream)
                {
                    var line = await process.StandardOutput.ReadLineAsync();

                    if (printOutput)
                    {
                        Output.WriteLine(Invariant($"{outputPrefix}> {line}"));
                    }
                    result.AppendLine(line);
                }

                await process.WaitForExitAsync(timeoutms, ct);
            } catch (IOException) {
                if (printOutput)
                {
                    Output.WriteError(Resources.LocalDockerErrorFormat.FormatInvariant(outputPrefix, Resources.LocalDockerOutputStreamException));
                }
                throw new ContainerException(Resources.LocalDockerOutputStreamException);
            } catch (OperationCanceledException) when(!failOnTimeout && !ct.IsCancellationRequested)
            {
            }

            var error = await process.StandardError.ReadToEndAsync();

            if (!string.IsNullOrEmpty(error) && !IsSecurityWarning(error))
            {
                Output.WriteError(Resources.LocalDockerErrorFormat.FormatInvariant(outputPrefix, error));
                if (IsServiceNotReady(error))
                {
                    throw new ContainerServiceNotReadyException(error);
                }
                else
                {
                    throw new ContainerException(error);
                }
            }

            return(result.ToString());
        }
Exemplo n.º 4
0
        private async Task <string> ExecuteCommandAsync(string arguments, int timeoutms, bool failOnTimeout = true, CancellationToken ct = default(CancellationToken))
        {
            await TaskUtilities.SwitchToBackgroundThread();

            var docker           = GetLocalDocker();
            ProcessStartInfo psi = new ProcessStartInfo {
                FileName               = docker.DockerCommandPath,
                Arguments              = arguments,
                RedirectStandardError  = true,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                UseShellExecute        = false
            };

            var process = _ps.Start(psi);

            try {
                await process.WaitForExitAsync(timeoutms, ct);
            } catch (OperationCanceledException) when(!failOnTimeout && !ct.IsCancellationRequested)
            {
            }

            var output = await process.StandardOutput.ReadToEndAsync();

            var error = await process.StandardError.ReadToEndAsync();

            if (!string.IsNullOrEmpty(error))
            {
                _outputLogWriter?.Write(MessageCategory.Error, error);
                throw new ContainerException(error);
            }

            _outputLogWriter?.Write(MessageCategory.General, output);
            return(output);
        }
        public IProcess StartHost(string interpreterPath, string interpreterArchitecture, string commandLine)
        {
            var exeLocator = new BrokerExecutableLocator(_fs);

            var hostBinPath = exeLocator.GetHostExecutablePath(interpreterArchitecture);

            if (hostBinPath == null)
            {
                throw new Win32Exception($"Microsoft.R.Host is missing. Interpreter: {interpreterPath}. Architecture: {interpreterArchitecture}");
            }

            var psi = new ProcessStartInfo {
                FileName               = hostBinPath,
                Arguments              = commandLine,
                RedirectStandardError  = true,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                WorkingDirectory       = Environment.GetEnvironmentVariable("PWD")
            };

            psi.Environment.Add("R_HOME", interpreterPath);
            psi.Environment.Add("LD_LIBRARY_PATH", Path.Combine(interpreterPath, "lib"));

            var process = _ps.Start(psi);

            process.WaitForExit(250);
            if (process.HasExited && process.ExitCode != 0)
            {
                throw new Win32Exception(process.ExitCode);
            }
            return(process);
        }
Exemplo n.º 6
0
        private IEnumerable <string> ExecuteAndGetOutput(string command, string arguments)
        {
            IProcess proc            = null;
            var      standardOutData = new List <string>();

            try {
                var psi = new ProcessStartInfo()
                {
                    Arguments              = arguments,
                    FileName               = command,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true
                };

                proc = _ps.Start(psi);

                while (!proc.StandardOutput.EndOfStream)
                {
                    standardOutData.Add(proc.StandardOutput.ReadLine());
                }
            } catch (Exception ex) {
                _logger.LogError(Resources.Error_FailedToRun.FormatInvariant($"{command} {arguments}", ex.Message));
            } finally {
                if (proc != null && !proc.HasExited)
                {
                    try {
                        proc?.Kill();
                    } catch (Exception ex) when(!ex.IsCriticalException())
                    {
                    }
                }
            }
            return(standardOutData);
        }
Exemplo n.º 7
0
        private static Process CreateRunAsUserProcess(IProcessServices ps, bool quietMode)
        {
            ProcessStartInfo psi = new ProcessStartInfo();

            psi.FileName               = PathConstants.RunAsUserBinPath;
            psi.Arguments              = quietMode ? "-q" : "";
            psi.RedirectStandardError  = true;
            psi.RedirectStandardInput  = true;
            psi.RedirectStandardOutput = true;

            return(ps.Start(psi));
        }
Exemplo n.º 8
0
        private static IProcess CreateRunAsUserProcess(IProcessServices ps, bool quietMode)
        {
            var psi = new ProcessStartInfo {
                FileName               = PathConstants.RunAsUserBinPath,
                Arguments              = quietMode ? "-q" : "",
                RedirectStandardError  = true,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true
            };

            return(ps.Start(psi));
        }
Exemplo n.º 9
0
 public bool TryHandleCommand(IImmutableSet <IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut)
 {
     if (commandId == RPackageCommandId.icmdOpenContainingFolder)
     {
         var path = nodes.GetSelectedFolderPath(_unconfiguredProject);
         if (!string.IsNullOrEmpty(path))
         {
             path = path.TrimTrailingSlash();
             _ps.Start(Path.GetDirectoryName(path));
         }
         return(true);
     }
     return(false);
 }
Exemplo n.º 10
0
        protected override void Handle()
        {
            var generalData = new StringWriter(CultureInfo.InvariantCulture);

            DiagnosticLogs.WriteGeneralData(generalData, detailed: false);

            var body = string.Format(CultureInfo.InvariantCulture, Resources.ReportIssueBody, generalData.ToString());

            var psi = new ProcessStartInfo {
                UseShellExecute = true,
                FileName        = string.Format(CultureInfo.InvariantCulture, _url, Uri.EscapeDataString(body))
            };

            _pss.Start(psi);
        }
Exemplo n.º 11
0
            public static PythonRpc Create(IProcessServices procServices, string exe, params string[] args)
            {
                var startInfo = new ProcessStartInfo(exe, args.AsQuotedArguments())
                {
                    UseShellExecute        = false,
                    ErrorDialog            = false,
                    CreateNoWindow         = true,
                    RedirectStandardInput  = true,
                    RedirectStandardOutput = true,
                };

                var process = procServices.Start(startInfo);

                return(new PythonRpc(procServices, process));
            }
Exemplo n.º 12
0
        private IProcess StartBroker(ProcessStartInfo psi)
        {
            var process = _processServices.Start(psi);

            process.WaitForExit(250);
            if (process.HasExited && process.ExitCode < 0)
            {
                var message = _processServices.MessageFromExitCode(process.ExitCode);
                if (!string.IsNullOrEmpty(message))
                {
                    throw new RHostDisconnectedException(Resources.Error_UnableToStartBrokerException.FormatInvariant(_name, message), new Win32Exception(message));
                }
                throw new RHostDisconnectedException(Resources.Error_UnableToStartBrokerException.FormatInvariant(_name, process.ExitCode), new Win32Exception(process.ExitCode));
            }
            return(process);
        }
Exemplo n.º 13
0
        public static async Task OpenDataCsvApp(IREvaluationResultInfo result, IApplicationShell appShell, IFileSystem fileSystem, IProcessServices processServices)
        {
            await appShell.SwitchToMainThreadAsync();

            if (Interlocked.Exchange(ref _busy, 1) > 0)
            {
                return;
            }

            var workflow = appShell.ExportProvider.GetExportedValue <IRInteractiveWorkflowProvider>().GetOrCreate();
            var session  = workflow.RSession;

            var folder = GetTempCsvFilesFolder();

            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            var pss          = appShell.ExportProvider.GetExportedValue <IProjectSystemServices>();
            var variableName = result.Name ?? _variableNameReplacement;
            var csvFileName  = MakeCsvFileName(appShell, pss, variableName);

            var file = pss.GetUniqueFileName(folder, csvFileName, "csv", appendUnderscore: true);

            string currentStatusText;
            var    statusBar = appShell.GetGlobalService <IVsStatusbar>(typeof(SVsStatusbar));

            statusBar.GetText(out currentStatusText);

            try {
                statusBar.SetText(Resources.Status_WritingCSV);
                appShell.ProgressDialog.Show(async(p, ct) => await CreateCsvAndStartProcess(result, session, file, fileSystem, p), Resources.Status_WritingCSV, 100, 500);
                if (fileSystem.FileExists(file))
                {
                    processServices.Start(file);
                }
            } catch (Win32Exception ex) {
                appShell.ShowErrorMessage(string.Format(CultureInfo.InvariantCulture, Resources.Error_CannotOpenCsv, ex.Message));
            } catch (IOException ex) {
                appShell.ShowErrorMessage(string.Format(CultureInfo.InvariantCulture, Resources.Error_CannotOpenCsv, ex.Message));
            } finally {
                statusBar.SetText(currentStatusText);
            }

            Interlocked.Exchange(ref _busy, 0);
        }
Exemplo n.º 14
0
        private static Process CreateRLaunchProcess(IProcessServices ps, bool authenticateOnly)
        {
            // usage:
            // Microsoft.R.Host.RunAsUser [-q]
            //    -q: Quiet
            const string rLaunchPath = "/usr/lib/rtvs/Microsoft.R.Host.RunAsUser";

            ProcessStartInfo psi = new ProcessStartInfo();

            psi.FileName               = rLaunchPath;
            psi.Arguments              = authenticateOnly ? "" : "-q";
            psi.RedirectStandardError  = true;
            psi.RedirectStandardInput  = true;
            psi.RedirectStandardOutput = true;

            return(ps.Start(psi));
        }
Exemplo n.º 15
0
 public void OpenBrowser(WebBrowserRole role, string url, bool onIdle = false)
 {
     if (role == WebBrowserRole.External || IsExternal(role))
     {
         _ps.Start(url);
     }
     else
     {
         if (onIdle)
         {
             NavigateOnIdle(role, url);
         }
         else
         {
             OpenVsBrowser(role, url);
         }
     }
 }
Exemplo n.º 16
0
        public static IProcess RunAsCurrentUser(IProcessServices ps, string hostBinPath, string arguments, string rHomePath, string loadLibPath)
        {
            var psi = new ProcessStartInfo {
                FileName               = hostBinPath,
                Arguments              = arguments,
                RedirectStandardError  = true,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                WorkingDirectory       = Environment.GetEnvironmentVariable("PWD")
            };

            // All other should be same as the broker environment. Only these are set based on interpreters.
            // R_HOME is explicitly set on the R-Host.
            psi.Environment.Add("R_HOME", rHomePath);
            psi.Environment.Add("LD_LIBRARY_PATH", loadLibPath);

            return(ps.Start(psi));
        }
Exemplo n.º 17
0
        private static async Task CreateCsvAndStartProcess(IREvaluationResultInfo result, IRSession session, string fileName, IFileSystem fileSystem, IProcessServices processServices)
        {
            await TaskUtilities.SwitchToBackgroundThread();

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

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

                fileSystem.FileWriteAllBytes(fileName, csvData);
            }

            if (fileSystem.FileExists(fileName))
            {
                processServices.Start(fileName);
            }
        }
Exemplo n.º 18
0
        private static Process CreateRLaunchProcess(IProcessServices ps, bool authenticateOnly)
        {
            // usage:
            // Microsoft.R.Host.RunAsUser [-q]
            //    -q: Quiet
            const string rLaunchBinary = "Microsoft.R.Host.RunAsUser";

            string brokerDir   = Path.GetDirectoryName(typeof(Program).GetTypeInfo().Assembly.Location);
            string rLaunchPath = Path.Combine(brokerDir, rLaunchBinary);

            ProcessStartInfo psi = new ProcessStartInfo();

            psi.FileName               = rLaunchPath;
            psi.Arguments              = authenticateOnly ? "" : "-q";
            psi.RedirectStandardError  = true;
            psi.RedirectStandardInput  = true;
            psi.RedirectStandardOutput = true;

            return(ps.Start(psi));
        }
Exemplo n.º 19
0
        public bool TryHandleCommand(IImmutableSet <IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut)
        {
            if (commandId == _commandId)
            {
                var path = nodes.GetSingleNodePath();
                if (!string.IsNullOrEmpty(path))
                {
                    if (File.Exists(path))
                    {
                        path = Path.GetDirectoryName(path);
                    }

                    path = path.TrimTrailingSlash();
                    var psi = new ProcessStartInfo();
                    SetFlags(psi, path);
                    _ps.Start(psi);
                }
                return(true);
            }
            return(false);
        }
Exemplo n.º 20
0
        public static async Task OpenDataCsvApp(IREvaluationResultInfo result, IApplicationShell appShell, IFileSystem fileSystem, IProcessServices processServices) {
            await appShell.SwitchToMainThreadAsync();

            if (Interlocked.Exchange(ref _busy, 1) > 0) {
                return;
            }

            var workflow = appShell.ExportProvider.GetExportedValue<IRInteractiveWorkflowProvider>().GetOrCreate();
            var session = workflow.RSession;

            var folder = GetTempCsvFilesFolder();
            if (!Directory.Exists(folder)) {
                Directory.CreateDirectory(folder);
            }

            var pss = appShell.ExportProvider.GetExportedValue<IProjectSystemServices>();
            var variableName = result.Name ?? _variableNameReplacement;
            var csvFileName = MakeCsvFileName(appShell, pss, variableName);

            var file = pss.GetUniqueFileName(folder, csvFileName, "csv", appendUnderscore: true);

            string currentStatusText;
            var statusBar = appShell.GetGlobalService<IVsStatusbar>(typeof(SVsStatusbar));
            statusBar.GetText(out currentStatusText);

            try {
                statusBar.SetText(Resources.Status_WritingCSV);
                appShell.ProgressDialog.Show(async (p, ct) => await CreateCsvAndStartProcess(result, session, file, fileSystem, p, ct), Resources.Status_WritingCSV, 100, 500);
                if (fileSystem.FileExists(file)) {
                    processServices.Start(file);
                }
            } catch (Exception ex) when (ex is Win32Exception || ex is IOException || ex is UnauthorizedAccessException) {
                appShell.ShowErrorMessage(string.Format(CultureInfo.InvariantCulture, Resources.Error_CannotOpenCsv, ex.Message));
            } finally {
                statusBar.SetText(currentStatusText);
            }

            Interlocked.Exchange(ref _busy, 0);
        }