Пример #1
0
        private string GetAmazonLambdaToolVersion()
        {
            // check if dotnet executable can be found
            var dotNetExe = ProcessLauncher.DotNetExe;

            if (string.IsNullOrEmpty(dotNetExe))
            {
                return(null);
            }

            // check if Amazon Lambda Tools extension is installed
            var result = ProcessLauncher.ExecuteWithOutputCapture(
                dotNetExe,
                new[] { "lambda", "tool", "help" },
                workingFolder: null
                );

            if (result == null)
            {
                return(null);
            }

            // parse version from Amazon Lambda Tools
            var match = Regex.Match(result, @"\((?<Version>.*)\)");

            if (!match.Success)
            {
                return(null);
            }
            return(match.Groups["Version"].Value);
        }
Пример #2
0
        public void Start(string Domain, string UserName, string Password, bool CreateWindow)
        {
            // Create the worker shell...
#if true
            CommandPrompt.StartInfo.UseShellExecute = false;        // Required to enable RedirectStandard...
            CommandPrompt.StartInfo.CreateNoWindow  = !CreateWindow;
            CommandPrompt.StartInfo.FileName        = "cmd.exe";
            CommandPrompt.StartInfo.Arguments       = "";
            //CommandPrompt.StartInfo.RedirectStandardError = true;
            //CommandPrompt.StartInfo.RedirectStandardInput = true;
            //CommandPrompt.StartInfo.RedirectStandardOutput = true;
            CommandPrompt.StartInfo.RedirectStandardInput  = false;
            CommandPrompt.StartInfo.RedirectStandardOutput = false;
            CommandPrompt.StartInfo.RedirectStandardError  = false;

            CommandPrompt.StartInfo.Domain              = Domain;
            CommandPrompt.StartInfo.UserName            = UserName;
            CommandPrompt.StartInfo.PasswordInClearText = Password;

            CommandPrompt.StartInfo.LoadUserProfile = true;         // Instructs the launcher to load the user's profile into HKEY_CURRENT_USER.
#else
            CommandPrompt = new TrimProcessLauncher();
#endif

            CommandPrompt.Start();
            //StandardOutput = new PipeReader(CommandPrompt.StandardOutput, "StdOut");
            //StandardError = new PipeReader(CommandPrompt.StandardError, "StdErr");
        }
Пример #3
0
        private int Run(string[] args)
        {
            _output = new ConsoleOutput();

            try
            {
                BuildOptions options = ParseBuildOptions(args);
                if (options == null || options.Solution == null)
                {
                    return(1);
                }

                GlobalSettings globalSettings = GlobalSettings.Load(_output);
                globalSettings.Save();
                var settings = new Settings(globalSettings, options, _output);

                var stopwatch = new Stopwatch();
                stopwatch.Start();

                int exitCode = 0;
                if (options.CleanCache)
                {
                    CacheCleaner.Run(settings);
                }
                else
                {
                    var          solutionReaderWriter = new SolutionReaderWriter(settings);
                    SolutionInfo solutionInfo         = solutionReaderWriter.ReadWrite(options.Solution.FullName);
                    settings.SolutionSettings = SolutionSettings.Load(settings, solutionInfo);
                    var projectReaderWriter = new ProjectReaderWriter(settings);
                    projectReaderWriter.ReadWrite(solutionInfo);
                    settings.SolutionSettings.UpdateAndSave(settings, solutionInfo);

                    if (!options.GenerateOnly)
                    {
                        var processLauncher = new ProcessLauncher(settings);
                        Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs cancelArgs)
                        {
                            _output.WriteLine("Stopping build...");
                            processLauncher.Stop();
                            cancelArgs.Cancel = true;
                        };

                        exitCode = processLauncher.Run(solutionInfo);
                    }
                }

                stopwatch.Stop();
                TimeSpan ts            = stopwatch.Elapsed;
                string   buildTimeText = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
                _output.WriteLine("Build time: " + buildTimeText);

                return(exitCode);
            }
            catch (Exception e)
            {
                _output.WriteLine("ERROR: " + e.Message);
                return(-1);
            }
        }
Пример #4
0
        private async Task <IEnumerable <string> > GetDbContextTypesAsync(string outputPath, Project project)
        {
            var processLauncher = new ProcessLauncher(project);

            var processResult = await processLauncher.GetOutputAsync(outputPath, GenerationType.DbContextList, null);

            if (string.IsNullOrEmpty(processResult))
            {
                throw new InvalidOperationException(CompareLocale.UnableToCollectDbContextInformation);
            }

            if (processResult.Contains("Error:"))
            {
                throw new InvalidOperationException(processResult);
            }

            var modelResults = processLauncher.BuildModelResult(processResult);
            var result       = new List <string>();

            foreach (var modelResult in modelResults)
            {
                result.Add(modelResult.Item1);
            }

            return(result);
        }
Пример #5
0
        public IList <TestCase> CreateTestCases()
        {
            var           launcher = new ProcessLauncher(_testEnvironment, _testEnvironment.Options.GetPathExtension(_executable));
            int           processReturnCode;
            List <string> consoleOutput = launcher.GetOutputOfCommand("", _executable, GoogleTestConstants.ListTestsOption.Trim(), false, false, out processReturnCode);

            if (processReturnCode != 0)
            {
                string messsage =
                    $"Could not list test cases of executable '{_executable}': executing process failed with return code {processReturnCode}";
                messsage += $"\nCommand executed: '{_executable} {GoogleTestConstants.ListTestsOption.Trim()}', working directory: '{Path.GetDirectoryName(_executable)}'";
                if (consoleOutput.Count(s => !string.IsNullOrEmpty(s)) > 0)
                {
                    messsage += $"\nOutput of command:\n{string.Join("\n", consoleOutput)}";
                }
                else
                {
                    messsage += "\nCommand produced no output";
                }

                _testEnvironment.LogWarning(messsage);

                return(new List <TestCase>());
            }

            IList <TestCaseDescriptor> testCaseDescriptors = new ListTestsParser(_testEnvironment).ParseListTestsOutput(consoleOutput);

            if (_testEnvironment.Options.ParseSymbolInformation)
            {
                List <TestCaseLocation> testCaseLocations = GetTestCaseLocations(testCaseDescriptors, _testEnvironment.Options.GetPathExtension(_executable));
                return(testCaseDescriptors.Select(descriptor => CreateTestCase(descriptor, testCaseLocations)).ToList());
            }

            return(testCaseDescriptors.Select(CreateTestCase).ToList());
        }
Пример #6
0
        public void Build(BuildOptions options)
        {
            if (IsBuilding)
            {
                return;
            }

            _globalSettings = GlobalSettings.Load(_output);
            var settings = new Settings(_globalSettings, options, _output);

            if (options.CleanCache)
            {
                CacheCleaner.Run(settings);
                return;
            }

            lock (_lock)
            {
                _processLauncher     = new ProcessLauncher(settings);
                _lastBuildWasStopped = false;
                _isBeingStopped      = false;
                _buildThread         = new Thread(() => BuildThread(settings))
                {
                    IsBackground = true
                };
                _buildThread.Start();
            }
        }
Пример #7
0
        private void StopThread()
        {
            ProcessLauncher processLauncher = null;
            Thread          buildThread     = null;

            lock (_lock)
            {
                processLauncher = _processLauncher;
                buildThread     = _buildThread;
            }
            if (processLauncher != null && buildThread != null)
            {
                try
                {
                    processLauncher.Stop();
                    buildThread.Join();
                    _output.WriteLine("Build stopped.");
                }
                catch (Exception ex)
                {
                    _output.WriteLine("An error occurred trying to stop the build:");
                    _output.WriteLine(ex.Message);
                }
                lock (_lock)
                {
                    _lastBuildWasStopped = true;
                    _isBeingStopped      = false;
                }
            }
        }
Пример #8
0
        private async Task <IEnumerable <string> > GetDbContextTypesAsync(string outputPath, Project project)
        {
            var processLauncher = new ProcessLauncher(project);

            var processResult = await processLauncher.GetOutputAsync(outputPath, GenerationType.DbContextList, null);

            if (string.IsNullOrEmpty(processResult))
            {
                throw new ArgumentException("Unable to collect DbContext information", nameof(processResult));
            }

            if (processResult.StartsWith("Error:"))
            {
                throw new ArgumentException(processResult, nameof(processResult));
            }

            var modelResults = processLauncher.BuildModelResult(processResult);
            var result       = new List <string>();

            foreach (var modelResult in modelResults)
            {
                result.Add(modelResult.Item1);
            }

            return(result);
        }
Пример #9
0
        public override bool Execute(OpenInput input)
        {
            input.CreateMissingSpecFolder();

            var reset = new ManualResetEvent(false);

            using (var runner = new WebApplicationRunner(input))
            {
                runner.Start();
                Console.WriteLine("Launching the browser to " + runner.BaseAddress);

                ProcessLauncher.GotoUrl(runner.BaseAddress);

#if NET46
                AppDomain.CurrentDomain.DomainUnload += (sender, args) =>
                {
                    runner.SafeDispose();
                };
#else
                System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += context => runner.Dispose();
#endif

                Console.CancelKeyPress += (s, e) =>
                {
                    Console.WriteLine("Shutdown detected, tearing down the testing harness...");
                    runner.SafeDispose();
                    reset.Set();
                };

                tellUsersWhatToDo(runner.BaseAddress);
                reset.WaitOne();
            }

            return(true);
        }
Пример #10
0
        public bool Execute(string file, string param, string dir)
        {
            IntPtr sessionTokenHandle = IntPtr.Zero;

            try
            {
                sessionTokenHandle = SessionFinder.GetLocalInteractiveSession();
                if (sessionTokenHandle != IntPtr.Zero)
                {
                    ProcessLauncher.StartProcessAsUser(file, param, dir, sessionTokenHandle);
                }
            }
            catch (System.ComponentModel.Win32Exception ex)
            {
                if (ex.NativeErrorCode == 1008)      //ERROR_NO_TOKEN: No user is logged-on
                {
                    return(false);
                }
                throw ex;
            }
            catch (Exception ex)
            {
                //What are we gonna do?
                throw ex;
            }
            finally
            {
                if (sessionTokenHandle != IntPtr.Zero)
                {
                    NativeMethods.CloseHandle(sessionTokenHandle);
                }
            }
            return(true);
        }
Пример #11
0
        public void TestConsoleCaller()
        {
            var process = new Process();

            process.StartInfo.CreateNoWindow         = false;
            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput  = true;
            process.StartInfo.RedirectStandardError  = true;
            process.StartInfo.WorkingDirectory       = @"d:\IpmiTool-1.8.11.i4-win";
            process.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");

            //process.StartInfo.FileName = Path.Combine(@"d:\IpmiTool-1.8.11.i4-win", "ipmitool.exe");
            //process.StartInfo.Arguments = " -I lanplus -H 10.23.60.3 -U root -P superuser -b 6 -t 44 raw 6 1";

            using (ProcessLauncher launcher = new ProcessLauncher(this, process))
            {
                launcher.consoleOutlineEvent += this.onConsoleOutputDataReceived;
                launcher.consoleErrorEvent   += this.onConsoleErrortDataReceived;
                try
                {
                    launcher.Start();
                    //launcher.SendInput(string.Format(" -I lanplus -H 10.23.60.3 -U root -P superuser -b 6 -t 44 raw 6 1{0}", Convert.ToChar(0x0d)));
                    //launcher.SendInput(string.Format("d:{0}", Convert.ToChar(0x0d)));
                    //launcher.SendInput(string.Format(@"cd d:\IpmiTool-1.8.11.i4-win{0}", Convert.ToChar(0x0d)));
                    //launcher.SendInput(string.Format("dir{0}", Convert.ToChar(0x0d)));
                }
                finally
                {
                    //launcher.SendInput("exit()");
                }
            }
        }
Пример #12
0
        public void TestConsoleCallerPython()
        {
            var process = new Process();

            process.StartInfo.UseShellExecute        = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput  = true;
            process.StartInfo.RedirectStandardError  = true;
            process.StartInfo.WorkingDirectory       = @"C:\";
            process.StartInfo.FileName  = Path.Combine(Environment.SystemDirectory, "cmd.exe");
            process.StartInfo.Arguments = @"/c ""C:\python27\python.exe -i""";
            using (ProcessLauncher launcher = new ProcessLauncher(this, process))
            {
                launcher.consoleOutlineEvent += this.onConsoleOutputDataReceived;
                launcher.consoleErrorEvent   += this.onConsoleErrortDataReceived;
                try
                {
                    launcher.Start();
                    launcher.SendInput("import sys;\n");
                    launcher.SendInput("print \"Test.\";\n");
                }
                finally
                {
                    launcher.SendInput("exit()");
                }
            }
        }
Пример #13
0
        //
        // Run out of memory test, eventually terminates the SIP due
        // to fail fast.
        //
        internal void RunTestAsProcess(Parameters !config, string test)
        {
            Process p = null;

            //
            // Create a subprocess run of "memstress -testparameter"
            //
            string[] args = new string[3];
            args[0] = "memstress";
            args[1] = test;
            args[2] = "-noprocess";

            Console.WriteLine("Creating subprocess memstress {0} -noprocess", test);

            try {
                p = ProcessLauncher.CreateSubProcess(config, args);
            }
            catch (Exception e) {
                Console.WriteLine("Exception from CreateSubProcess: " + e.Message);
                return;
            }

            if (p == null)
            {
                Console.WriteLine("Error creating process");
                return;
            }

            Console.WriteLine("Process returned with ExitCode={0}", p.ExitCode);
        }
Пример #14
0
        public static async Task <bool> GetIsMakerImageAsync()
        {
            var cmdOutput      = string.Empty;
            var standardOutput = new InMemoryRandomAccessStream();
            var options        = new ProcessLauncherOptions
            {
                StandardOutput = standardOutput
            };
            var output = await ProcessLauncher.RunToCompletionAsync(CommandLineProcesserExe, RegKeyQueryCmdArg, options);

            if (output != null && output.ExitCode == 0)
            {
                using (var outStreamRedirect = standardOutput.GetInputStreamAt(0))
                {
                    using (var dataReader = new DataReader(outStreamRedirect))
                    {
                        uint bytesLoaded = 0;
                        while ((bytesLoaded = await dataReader.LoadAsync(CmdLineBufSize)) > 0)
                        {
                            cmdOutput += dataReader.ReadString(bytesLoaded);
                        }
                    }
                }
                Match match = Regex.Match(cmdOutput, ExpectedResultPattern, RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    return(true);
                }
                else
                {
                    ServiceUtil.LogService.Write("Could not get IsMakerImage. Output: " + cmdOutput);
                }
            }
            return(false);
        }
        public async Task PerformAsync()
        {
            ProcessInfo = new ProcessStartInfo(ProcessFileName, ProcessArgs)
            {
                WorkingDirectory = ProcessStartPath
            };
            ProcessInfo.UseShellExecute = true;
            try
            {
                bool IsAdmin = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
                if (LaunchAsAdmin && IsAdmin)
                {
                    Process.Start(ProcessInfo);
                }
                else
                {
                    if (IsAdmin)
                    {
                        ProcessLauncher.ExecuteProcessUnElevated(ProcessInfo.FileName, ProcessInfo.Arguments, ProcessInfo.WorkingDirectory);
                    }
                    else
                    {
                        Process.Start(ProcessInfo);
                    }
                }
            }catch (Exception ex)
            {
                MessageBox.Show($"Could not Launch Process on Macro {Name}. Error: {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            await Task.Delay(0);
        }
Пример #16
0
        public IList <TestCase> CreateTestCases(Action <TestCase> reportTestCase = null)
        {
            List <string> standardOutput = new List <string>();

            if (_settings.UseNewTestExecutionFramework)
            {
                return(NewCreateTestcases(reportTestCase, standardOutput));
            }

            try
            {
                var    launcher = new ProcessLauncher(_logger, _settings.GetPathExtension(_executable), null);
                int    processExitCode;
                string workingDir = new FileInfo(_executable).DirectoryName;
                standardOutput = launcher.GetOutputOfCommand(workingDir, null, _executable, GoogleTestConstants.ListTestsOption,
                                                             false, false, out processExitCode);

                if (!CheckProcessExitCode(processExitCode, standardOutput))
                {
                    return(new List <TestCase>());
                }
            }
            catch (Exception e)
            {
                SequentialTestRunner.LogExecutionError(_logger, _executable, Path.GetFullPath(""),
                                                       GoogleTestConstants.ListTestsOption, e);
                return(new List <TestCase>());
            }

            IList <TestCaseDescriptor> testCaseDescriptors = new ListTestsParser(_settings.TestNameSeparator).ParseListTestsOutput(standardOutput);
            var testCaseLocations = GetTestCaseLocations(testCaseDescriptors, _settings.GetPathExtension(_executable));

            IList <TestCase> testCases = new List <TestCase>();
            IDictionary <string, ISet <TestCase> > suite2TestCases = new Dictionary <string, ISet <TestCase> >();

            foreach (var descriptor in testCaseDescriptors)
            {
                var testCase = _settings.ParseSymbolInformation
                    ? CreateTestCase(descriptor, testCaseLocations)
                    : CreateTestCase(descriptor);
                ISet <TestCase> testCasesInSuite;
                if (!suite2TestCases.TryGetValue(descriptor.Suite, out testCasesInSuite))
                {
                    suite2TestCases.Add(descriptor.Suite, testCasesInSuite = new HashSet <TestCase>());
                }
                testCasesInSuite.Add(testCase);
                testCases.Add(testCase);
            }

            foreach (var suiteTestCasesPair in suite2TestCases)
            {
                foreach (var testCase in suiteTestCasesPair.Value)
                {
                    testCase.Properties.Add(new TestCaseMetaDataProperty(suiteTestCasesPair.Value.Count, testCases.Count));
                }
            }

            return(testCases);
        }
Пример #17
0
        private void TortoiseProc(string command, Dictionary <string, string> arguments = null, bool waitForExit = false)
        {
            arguments = arguments ?? new Dictionary <string, string>();
            var argumentsString  = $"/command:{command} {string.Join(" ", arguments.Select(kv => $"/{kv.Key}:{kv.Value}"))}";
            var processStartInfo = new ProcessStartInfo("TortoiseProc.exe", argumentsString);

            ProcessLauncher.Launch(processStartInfo, waitForExit);
        }
Пример #18
0
 public ApplicationController(ApplicationRepository applicationRepository, ProcessLauncher processLauncher,
                              FileSystem fileSystem, SystemVariable systemVariable, TemplateProcessor templateProcessor)
 {
     _applicationRepository = applicationRepository ?? throw new ArgumentNullException(nameof(applicationRepository));
     _systemVariable        = systemVariable ?? throw new ArgumentNullException(nameof(systemVariable));
     _processLauncher       = processLauncher ?? throw new ArgumentNullException(nameof(processLauncher));
     _templateProcessor     = templateProcessor ?? throw new ArgumentNullException(nameof(templateProcessor));
 }
Пример #19
0
        private void launchPage()
        {
            var url = Url.Contains("?")
                ? Url + $"&StorytellerPort={Server.Port}"
                : $"{Url}?StorytellerPort={Server.Port}";

            _process = ProcessLauncher.GotoUrl(url);
        }
Пример #20
0
        public static async Task SetAudioRenderVolume(int volume, bool retryOnException)
        {
            var result = await ProcessLauncher.RunToCompletionAsync(@"SetAudioRenderVolume.exe", volume.ToString(CultureInfo.InvariantCulture));

            if (result.ExitCode != 200)
            {
                await Logger.Write("Could not set audio render volume.");
            }
        }
Пример #21
0
        public IList <TestCase> CreateTestCases()
        {
            var           launcher      = new ProcessLauncher(TestEnvironment, TestEnvironment.Options.PathExtension);
            List <string> consoleOutput = launcher.GetOutputOfCommand("", Executable, GoogleTestConstants.ListTestsOption.Trim(), false, false);
            IList <TestCaseDescriptor> testCaseDescriptors = new ListTestsParser(TestEnvironment).ParseListTestsOutput(consoleOutput);
            List <TestCaseLocation>    testCaseLocations   = GetTestCaseLocations(testCaseDescriptors, TestEnvironment.Options.PathExtension);

            return(testCaseDescriptors.Select(descriptor => CreateTestCase(descriptor, testCaseLocations)).ToList());
        }
Пример #22
0
        public static async Task <ProcessLauncherOutput> RunCommandAsync(string fileName, string args)
        {
            var output = new ProcessLauncherOutput();

            try
            {
                using (var standardOutput = new InMemoryRandomAccessStream())
                    using (var standardError = new InMemoryRandomAccessStream())
                    {
                        var options = new ProcessLauncherOptions
                        {
                            StandardOutput = standardOutput,
                            StandardError  = standardError
                        };

                        var result = await ProcessLauncher.RunToCompletionAsync(
                            fileName,
                            args,
                            options);

                        output.Result = result;

                        using (IInputStream inputStream = standardOutput.GetInputStreamAt(0))
                        {
                            ulong size = standardOutput.Size;

                            using (var dataReader = new DataReader(inputStream))
                            {
                                uint bytesLoaded = await dataReader.LoadAsync((uint)size);

                                output.Output = dataReader.ReadString(bytesLoaded);
                            }
                        }

                        using (IInputStream inputStream = standardError.GetInputStreamAt(0))
                        {
                            ulong size = standardError.Size;

                            using (var dataReader = new DataReader(inputStream))
                            {
                                uint bytesLoaded = await dataReader.LoadAsync((uint)size);

                                output.Error = dataReader.ReadString(bytesLoaded);
                            }
                        }
                    }

                return(output);
            }
            catch (Exception ex)
            {
                ServiceUtil.LogService.WriteException(ex);
            }

            return(null);
        }
Пример #23
0
    /// <inheritdoc/>
    public override void Extract(IBuilder builder, Stream stream, string?subDir = null)
    {
        if (!UnixUtils.IsMacOSX)
        {
            throw new NotSupportedException(Resources.ExtractionOnlyOnMacOS);
        }

        EnsureFile(stream, archivePath =>
        {
            var launcher      = new ProcessLauncher("hdiutil");
            using var tempDir = new TemporaryDirectory("0install-archive");

            try
            {
                launcher.Run("attach", "-quiet", "-readonly", "-mountpoint", tempDir, "-nobrowse", archivePath);
                try
                {
                    if (subDir == null)
                    {
                        Handler.RunTask(new ReadDirectory(tempDir, builder)
                        {
                            Tag = Tag
                        });
                        try
                        {
                            builder.Remove(".Trashes");
                        }
                        catch (IOException)
                        {}
                    }
                    else
                    {
                        string extractDir = Path.Combine(tempDir, subDir);
                        if (Directory.Exists(extractDir))
                        {
                            Handler.RunTask(new ReadDirectory(extractDir, builder)
                            {
                                Tag = Tag
                            });
                        }
                    }
                }
                finally
                {
                    launcher.Run("detach", "-quiet", tempDir);
                }
            }
            #region Error handling
            catch (ExitCodeException ex)
            {
                // Wrap exception since only certain exception types are allowed
                throw new IOException(ex.Message, ex);
            }
            #endregion
        });
    }
Пример #24
0
        public static async Task SetAudioCaptureVolume(double volume, bool retryOnException)
        {
            //96.14% db equals 90% volume with Logitech G933 Headset
            var result = await ProcessLauncher.RunToCompletionAsync(@"SetAudioCaptureVolume.exe", volume.ToString(CultureInfo.InvariantCulture));

            if (result.ExitCode != 200)
            {
                await Logger.Write("Could not set audio capture volume.");
            }
        }
 public EfCoreMigrationsDialog(EFCorePowerTools.EFCorePowerToolsPackage package, string outputPath, Project project)
 {
     Telemetry.TrackPageView(nameof(EfCoreModelDialog));
     InitializeComponent();
     Background       = VsThemes.GetWindowBackground();
     _package         = package;
     _outputPath      = outputPath;
     _project         = project;
     _processLauncher = new ProcessLauncher(project.IsNetCore(), project.IsNetCore21());
 }
Пример #26
0
        private async Task RunProcess()
        {
            var options        = new ProcessLauncherOptions();
            var standardOutput = new InMemoryRandomAccessStream();
            var standardError  = new InMemoryRandomAccessStream();

            options.StandardOutput = standardOutput;
            options.StandardError  = standardError;

            await CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                try
                {
                    var result = await ProcessLauncher.RunToCompletionAsync(cmd.Text, args.Text == null ? string.Empty : args.Text, options);

                    ProcessExitCode.Text += "Process Exit Code: " + result.ExitCode;

                    using (var outStreamRedirect = standardOutput.GetInputStreamAt(0))
                    {
                        var size = standardOutput.Size;
                        using (var dataReader = new DataReader(outStreamRedirect))
                        {
                            var bytesLoaded     = await dataReader.LoadAsync((uint)size);
                            var stringRead      = dataReader.ReadString(bytesLoaded);
                            StdOutputText.Text += stringRead;
                        }
                    }

                    using (var errStreamRedirect = standardError.GetInputStreamAt(0))
                    {
                        using (var dataReader = new DataReader(errStreamRedirect))
                        {
                            var size           = standardError.Size;
                            var bytesLoaded    = await dataReader.LoadAsync((uint)size);
                            var stringRead     = dataReader.ReadString(bytesLoaded);
                            StdErrorText.Text += stringRead;
                        }
                    }
                }
                catch (UnauthorizedAccessException uex)
                {
                    StdErrorText.Text += "Exception Thrown: " + uex.Message + "\n";
                    StdErrorText.Text += "\nMake sure you're allowed to run the specified exe; either\n" +
                                         "\t1) Add the exe to the AppX package, or\n" +
                                         "\t2) Add the absolute path of the exe to the allow list:\n" +
                                         "\t\tHKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\EmbeddedMode\\ProcessLauncherAllowedExecutableFilesList.\n\n" +
                                         "Also, make sure the <iot:Capability Name=\"systemManagement\" /> has been added to the AppX manifest capabilities.\n";
                }
                catch (Exception ex)
                {
                    StdErrorText.Text += "Exception Thrown:" + ex.Message + "\n";
                    StdErrorText.Text += ex.StackTrace + "\n";
                }
            });
        }
Пример #27
0
    static IEnumerable <ToolStripItem> BuildTrackingMenuItems(Tracker tracker)
    {
        if (!tracker.TrackingAny)
        {
            yield break;
        }

        yield return(new MenuButton("Clear", tracker.Clear, Images.Clear));

        var deletes = tracker.Deletes
                      .OrderBy(x => x.File)
                      .ToList();

        if (deletes.Any())
        {
            yield return(new ToolStripSeparator());

            yield return(new MenuButton("Pending Deletes:", tracker.AcceptAllDeletes, Images.Delete));

            foreach (var delete in deletes)
            {
                var menu = new SplitButton($"{delete.Name}", () => tracker.Accept(delete));
                menu.AddRange(
                    new MenuButton("Accept change", () => tracker.Accept(delete)),
                    new MenuButton("Open directory", () => ExplorerLauncher.ShowFileInExplorer(delete.File)));
                yield return(menu);
            }
        }

        var moves = tracker.Moves
                    .OrderBy(x => x.Temp)
                    .ToList();

        if (moves.Any())
        {
            yield return(new ToolStripSeparator());

            yield return(new MenuButton("Pending Moves:", tracker.AcceptAllMoves, Images.Accept));

            foreach (var move in moves)
            {
                var menu = new SplitButton($"{move.Name} ({move.Extension})", () => tracker.Accept(move));
                menu.AddRange(
                    new MenuButton("Accept change", () => tracker.Accept(move)),
                    new MenuButton("Launch diff tool", () => ProcessLauncher.Launch(move)),
                    new MenuButton("Open directory", () => ExplorerLauncher.ShowFileInExplorer(move.Temp)));
                yield return(menu);
            }
        }

        yield return(new ToolStripSeparator());

        yield return(new MenuButton("Accept all", tracker.AcceptAll, Images.AcceptAll));
    }
Пример #28
0
        public JamEntryViewModel(JamEntry model)
            : base(model)
        {
            Team = new JamTeamViewModel(model.Team);

            ThumbnailPathProperty      = ImageSourceProperty.CreateReadonly(this, nameof(Thumbnail), vm => vm.Model.ThumbnailPath);
            ThumbnailSmallPathProperty = ImageSourceProperty.CreateReadonly(this, nameof(ThumbnailSmall), vm => vm.Model.ThumbnailSmallPath);

            Launcher          = new ProcessLauncher();
            LaunchGameCommand = new SimpleCommand(LaunchGame);
        }
Пример #29
0
        public override void HandleMessage(OpenInEditor message, IApplication app)
        {
            if (!app.Persistence.Hierarchy.Specifications.Has(message.id))
            {
                return;
            }

            var spec = app.Persistence.Hierarchy.Specifications[message.id];
            var file = spec.Filename;

            ProcessLauncher.OpenFile(file);
        }
        private static void InstallNpmPackage(string packageName)
        {
            Trace.WriteLine($"Attempting to install {packageName} through NPM");

            var processLauncher = new ProcessLauncher();
            var npmPath         = NpmHelper.GetNpmPath();

            processLauncher.Start(
                npmPath,
                $"install -g {packageName}");

            Trace.WriteLine($"{packageName} installed successfully through NPM");
        }
Пример #31
0
 /// <summary>
 /// Tries the put.
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <param name="remoteHost">The remote host.</param>
 /// <param name="userName">Name of the user.</param>
 /// <param name="localFiles">The local files.</param>
 /// <param name="remoteFile">The remote file.</param>
 /// <param name="ex">The ex.</param>
 /// <returns></returns>
 public static bool TryPut(SecureCopySettings settings, string remoteHost, string userName, string[] localFiles, string remoteFile, out Exception ex)
 {
     if (settings == null)
         throw new ArgumentNullException("settings");
     if (string.IsNullOrEmpty(remoteHost))
         throw new ArgumentNullException("remoteHost");
     if ((localFiles == null) || (localFiles.Length == 0))
         throw new ArgumentNullException("localFiles");
     if (string.IsNullOrEmpty(remoteFile))
         throw new ArgumentNullException("remoteFile");
     //
     if (!string.IsNullOrEmpty(userName))
         remoteHost = userName + "@" + remoteHost;
     string executablePath;
     var arguments = string.Format(PutArgumentsXABC, Get(settings, out executablePath), string.Join(" ", localFiles), remoteHost, remoteFile);
     try
     {
         var launcher = new ProcessLauncher();
         launcher.Launch(settings.ProcessPutTimeoutInMilliseconds, executablePath, arguments, (w) =>
         {
             // Respond N
             w.WriteLine("n");
             w.Flush();
         });
         ex = null;
         return true;
     }
     catch (SecureCopyException e) { ex = e; return false; }
 }
Пример #32
0
 //public static bool TryList<TItem>(SecureCopySettings settings, string remoteHost, string userId, string fileSpecification, out IEnumerable<TItem> items, out Exception ex)
 //{
 //    string itemsAsText;
 //    if (TryList(settings, remoteHost, userId, fileSpecification, out itemsAsText, out ex))
 //    {
 //        items = null;
 //        return true;
 //    };
 //    items = null;
 //    return false;
 //}
 /// <summary>
 /// Tries the list.
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <param name="remoteHost">The remote host.</param>
 /// <param name="userName">Name of the user.</param>
 /// <param name="fileSpecification">The file specification.</param>
 /// <param name="items">The items.</param>
 /// <param name="ex">The ex.</param>
 /// <returns></returns>
 public static bool TryList(SecureCopySettings settings, string remoteHost, string userName, string fileSpecification, out string items, out Exception ex)
 {
     if (settings == null)
         throw new ArgumentNullException("settings");
     if (string.IsNullOrEmpty(remoteHost))
         throw new ArgumentNullException("remoteHost");
     if (string.IsNullOrEmpty(fileSpecification))
         throw new ArgumentNullException("fileSpecification");
     //
     if (!string.IsNullOrEmpty(userName))
         remoteHost = userName + "@" + remoteHost;
     string executablePath;
     var arguments = string.Format(ListArgumentsXAB, Get(settings, out executablePath), remoteHost, fileSpecification);
     try
     {
         var launcher = new ProcessLauncher();
         launcher.Launch(settings.ProcessTimeoutInMilliseconds, executablePath, arguments, (w) =>
         {
             // Respond N
             w.WriteLine("n");
             w.Flush();
         });
         items = launcher.OutputString;
         ex = null;
         return true;
     }
     catch (SecureCopyException e) { items = null; ex = e; return false; }
 }
Пример #33
0
 /// <summary>
 /// Export to Excel
 /// </summary>
 private void btnExpToExcel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
 {
     string tempFileName = Path.ChangeExtension(Path.GetTempFileName(), ".xlsx");
     gridView_Logs.ExportToXlsx(tempFileName);
     if (File.Exists(tempFileName))
     {
         ProcessLauncher plauncher = new ProcessLauncher(tempFileName)
         {
             Verb = "open",
             WaitForExit = false,
             WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized
         };
         plauncher.Execute();
     }
 }