protected override TaskProcessResult RunExternalTaskProcess(ITask task, TaskExecutionSettings settings) { // Get the one and only asset/file associated with this particular task // (the job splitter will have created a task for each video file passed in). var inputFile = task.RequiredFiles[0].Name; // As this example just gets ffmpeg to rewrite the input file, we will // use the same file extension as the input file. // The output file will be written as {TaskId}.{extension} e.g. 1.mp4 var outputFile = string.Concat(task.TaskId.ToString(), Path.GetExtension(inputFile)); // Add the name of the application exe to the drive letter/path of the mounted VHD. var externalProgramPath = ExecutablePath("ffmpeg.exe"); // We aren't going to tell ffmepg to do any transcoding or compression or anything, // but you could imagine that user defined settings could be passed in with the job // when it was submitted. The job splitter could then set these in turn against each // of the tasks it created. Then the task processor could use those settings to // set up particular arguments for ffmpeg. //NOTE: usage: ffmpeg [options] [[infile options] -i infile]... {[outfile options] outfile}... var externalProgramArguments = String.Format("-i \"{0}\" \"{1}\"", inputFile, outputFile); // Run ffmpeg var ffmpegResult = new ExternalProcess { CommandPath = externalProgramPath, Arguments = externalProgramArguments, WorkingDirectory = LocalStoragePath, }.Run(); // Return the output file that has been created. return TaskProcessResult.FromExternalProcessResult(ffmpegResult, outputFile); }
internal async Task <ExternalProcess> LaunchApplication(string options, CancellationToken cancellationToken) { ExternalProcess logcatProcess = null; if (Options.SaveLogCat != null) { await ClearLogCat(cancellationToken).ConfigureAwait(false); var output = new StreamWriter(Options.SaveLogCat); logcatProcess = await StartLogCat(output, cancellationToken); } var args = new StringBuilder(); args.Append(AdbCommandLine("shell am start -W -S")); args.Append($" -e XAMARIN_ASYNCTESTS_OPTIONS \"'{options}'\" "); var activity = Program.Options.AndroidActivity ?? "com.xamarin.webtests.android/com.xamarin.webtests.android.MainActivity"; args.Append(activity); Program.Debug("Launching apk: {0}", args); var process = await ProcessHelper.StartCommand(Adb, args.ToString(), cancellationToken).ConfigureAwait(false); if (logcatProcess != null) { process.ExitedEvent += (sender, e) => logcatProcess.Dispose(); } return(process); }
protected override Task <int> InnerRunAsync(BuildArgs args, ILogger log) { log.Info($"Starting {nameof(SolutionBuild)}"); var dotnetAction = args.Publish ? "Publish" : "Build"; foreach (var project in args.ReleaseProjects) { var actionBlock = $"{dotnetAction.ToLowerInvariant()} \"{project.FullName()}\" --configuration {args.Configuration} --verbosity quiet /p:Version={args.Version.SemVer20String}"; if (args.Publish) { actionBlock += $" --runtime {args.Runtime}"; } else { actionBlock += $" --no-incremental"; } log.Info($"{dotnetAction}ing {project.NameWoExtension.Highlight()}"); log.Info(actionBlock.Highlight()); var exitCode = ExternalProcess.Run("dotnet", actionBlock, log.Debug, log.Error); if (exitCode != 0) { throw new CliException($"{dotnetAction} failed for {project.NameWoExtension.Highlight()}. See logs for details", 400); } } return(Task.FromResult(0)); }
private ExternalProcess ExecutePrismProcess(string prismArguments) { var javaExe = FindJava(); var prismDir = FindPrism(); CheckPrismVersion(javaExe, prismDir); AddPrismLibToPath(prismDir); var classpath = string.Format(@"{0}\lib\prism.jar;{0}\classes;{0};{0}\lib\pepa.zip;{0}\lib\*", prismDir); var argument = $"-Djava.library.path=\"{prismDir}\\lib\" -classpath \"{classpath}\" prism.PrismCL {prismArguments}"; Action <string> addToOutput; if (_output == null) { addToOutput = (output) => _prismProcessOutput.Add(output); } else { addToOutput = (output) => { _output.WriteLine(output); _prismProcessOutput.Add(output); } }; var process = new ExternalProcess(javaExe, argument, addToOutput); return(process); }
/// <summary> /// Checks whether the <paramref name="formula" /> holds in all states of the <paramref name="model" />. /// </summary> /// <param name="createModel">The creator for the model that should be checked.</param> /// <param name="checkArgument">The argument passed to LtsMin that indicates which kind of check to perform.</param> private AnalysisResult <SafetySharpRuntimeModel> Check(CoupledExecutableModelCreator <SafetySharpRuntimeModel> createModel, string checkArgument) { try { using (var modelFile = new TemporaryFile("ssharp")) { File.WriteAllBytes(modelFile.FilePath, RuntimeModelSerializer.Save((ModelBase)createModel.SourceModel, createModel.StateFormulasToCheckInBaseModel)); try { CreateProcess(modelFile.FilePath, checkArgument); Run(); } catch (Win32Exception e) { throw new InvalidOperationException( "Failed to start LTSMin. Ensure that pins2lts-seq.exe can be found by either copying it next " + "to the executing assembly or by adding it to the system path. The required cygwin dependencies " + $"must also be available. The original error message was: {e.Message}", e); } var success = InterpretExitCode(_ltsMin.ExitCode); return(new AnalysisResult <SafetySharpRuntimeModel> { FormulaHolds = success }); } } finally { _ltsMin = null; } }
/// ------------------------------------------------------------------------------------ private void DoConversion(object commandLine) { var exePath = FFmpegDownloadHelper.FullPathToFFmpegForSayMoreExe; _conversionOutput = new StringBuilder(exePath); _conversionOutput.Append(commandLine); try { // ffmpeg always seems to write the output to standarderror. // I don't understand why and that's wrong, but we'll deal with it. _process = ExternalProcess.StartProcessToMonitor(exePath, commandLine as string, HandleProcessDataReceived, HandleProcessDataReceived, null); } catch (Exception e) { ErrorReport.ReportNonFatalException(e); return; } try { _process.PriorityClass = ProcessPriorityClass.BelowNormal; } catch (InvalidOperationException) { // process probably already exited } _process.WaitForExit(); if (_conversionReportingAction != null) { _conversionReportingAction(TimeSpan.FromSeconds(int.MaxValue), null); } }
/// ------------------------------------------------------------------------------------ private void StartPlayback(bool resampleToMono) { DebugOutput = Application.OpenForms.OfType <ILogger>().FirstOrDefault(); if (_loopDelayTimer != null) { _loopDelayTimer.Dispose(); _loopDelayTimer = null; } if (_mplayerProcess != null) { ShutdownMPlayerProcess(); } var videoWindowHandle = 0; int bitsPerSample = 0; // If the file is a video file and we don't have a window in which to play // the video, then set the handle to -1 to indicate to the helper that we // only want to play the audio from the video file. if (MediaInfo != null) { if (MediaInfo.IsVideo) { videoWindowHandle = (VideoWindowHandle > 0 ? VideoWindowHandle : -1); } bitsPerSample = MediaInfo.BitsPerSample; } var args = MPlayerHelper.GetPlaybackArguments(PlaybackStartPosition, PlaybackLength, Volume, Speed, resampleToMono, videoWindowHandle, bitsPerSample); _mplayerProcess = MPlayerHelper.StartProcessToMonitor(args, HandleDataReceived, HandleDataReceived); if (_outputDebuggingWindow != null) { _mplayerStartInfo.Length = 0; _mplayerStartInfo.AppendLine("*** COMMAND LINE:"); _mplayerStartInfo.Append(_mplayerProcess.StartInfo.FileName); _mplayerStartInfo.Append(" "); _mplayerStartInfo.AppendLine(_mplayerProcess.StartInfo.Arguments); _mplayerStartInfo.Append("*** MEDIA FILE: "); _mplayerStartInfo.AppendLine(MediaFile); _mplayerStartInfo.AppendLine(); _outputDebuggingWindow.AddText(_mplayerStartInfo.ToString()); } _mplayerProcess.FileOpenedByProcess = MediaFile; _stdIn = _mplayerProcess.StandardInput; _stdIn.WriteLine("loadfile \"{0}\" ", MediaFile); HasPlaybackStarted = true; if (PlaybackStarted != null) { PlaybackStarted(this, EventArgs.Empty); } }
internal async Task <string> StartGitProzess(string arguments, bool ensureSuccess, string workingFolder = "") { var process = new ExternalProcess(_logger); var output = await process.Run(workingFolder, _pathGit, arguments, ensureSuccess); return(output.Output.TrimEnd(Environment.NewLine.ToCharArray())); }
protected override TaskProcessResult RunExternalTaskProcess(ITask task, TaskExecutionSettings settings) { var parameters = task.Parameters; var outFile = String.Format("{0}_{1}.txt", "out", task.TaskId); var process = new ExternalProcess { CommandPath = ExecutablePath(@"ModelBatchTest/Model.exe"), Arguments = String.Format("{0} {1} {2}", parameters["l0"], parameters["omega"], outFile), WorkingDirectory = LocalStoragePath }; try { ExternalProcessResult processOutput = process.Run(); return(TaskProcessResult.FromExternalProcessResult(processOutput, outFile)); } catch (ExternalProcessException ex) { string outputInfo = "No program output"; if (!string.IsNullOrEmpty(ex.StandardError) || !string.IsNullOrEmpty(ex.StandardOutput)) { outputInfo = Environment.NewLine + "stderr: " + ex.StandardError + Environment.NewLine + "stdout: " + ex.StandardOutput; } Log.Error("Failed to invoke command {0} {1}: exit code was {2}. {3}", ex.CommandPath, ex.Arguments, ex.ExitCode, outputInfo); } catch (Exception ex) { Log.Error("Error in task processor: {0}", ex.ToString()); } return(new TaskProcessResult { Success = TaskProcessSuccess.RetryableFailure }); }
private async Task Update(DatabaseSetting dbSetting, DvcsScriptRepositoryBase.RevisionIdentifierBase sourceChangeset) { ICollection <BuildItem> buildItems; using (var connection = new SqlConnection(dbSetting.ConnectionString)) { await connection.OpenAsync(); using (var transaction = connection.BeginTransaction()) { var fileSystem = new FileSystem(); var db = dbSetting.Create(connection, transaction); var gitProcess = new ExternalProcess(pathToGit.FullName); var dvcsScriptRepo = new GitScriptRepository(dbSetting.ScriptsPath, dbSetting.ServerName, dbSetting.DatabaseName, gitProcess, fileSystem, sqlParser, new ConsoleLogger(SeverityLevel.Warning), false); dvcsScriptRepo.SourceChangeset = sourceChangeset; buildItems = await db.GetChangedBuildItemsAsync(dvcsScriptRepo); transaction.Commit(); } } await DispatcherInvoke(() => { ((MainWindowViewModel)DataContext).IsReady = true; ((MainWindowViewModel)DataContext).IsDone = false; ObservableCollection <BuildItemViewModel> itemsCollection = new ObservableCollection <BuildItemViewModel> (buildItems.Select(x => new BuildItemViewModel(x, Dispatcher))); ((MainWindowViewModel)DataContext).Items = itemsCollection; }); }
internal async Task <ExternalProcess> LaunchApplication(string options, CancellationToken cancellationToken) { ExternalProcess logcatProcess = null; if (Options.SaveLogCat != null) { await ClearLogCat(cancellationToken).ConfigureAwait(false); var output = new StreamWriter(Options.SaveLogCat); logcatProcess = await StartLogCat(output, cancellationToken); } var args = new StringBuilder(); args.Append("shell am start "); args.Append("-W -S "); args.AppendFormat(" -e XAMARIN_ASYNCTESTS_OPTIONS \\'{0}\\' ", options); args.Append(Program.Options.Application); Program.Debug("Launching apk: {0}", args); var process = await ProcessHelper.StartCommand(Adb, args.ToString(), cancellationToken).ConfigureAwait(false); if (logcatProcess != null) { process.ExitedEvent += (sender, e) => logcatProcess.Dispose(); } return(process); }
/// <summary> /// Run a, executable with a given set of arguments. /// </summary> /// <param name="exePath">Path the executable.</param> /// <param name="exeArgs">The command line arguments.</param> /// <returns>The ExternalProcessResult if run successfully, or null if an error was thrown.</returns> private ExternalProcessResult ExecuteProcess(string exePath, string exeArgs) { var process = new ExternalProcess { CommandPath = exePath, Arguments = exeArgs, WorkingDirectory = LocalStoragePath }; try { return(process.Run()); } catch (ExternalProcessException ex) { string outputInfo = "No program output"; if (!string.IsNullOrEmpty(ex.StandardError) || !string.IsNullOrEmpty(ex.StandardOutput)) { outputInfo = Environment.NewLine + "stderr: " + ex.StandardError + Environment.NewLine + "stdout: " + ex.StandardOutput; } Log.Error("Failed to invoke command {0} {1}: exit code was {2}. {3}", ex.CommandPath, ex.Arguments, ex.ExitCode, outputInfo); return(null); } catch (Exception ex) { Log.Error("Error in task processor: {0}", ex.ToString()); return(null); } }
public static void Browse(string path) { if (IsInstalled()) { ExternalProcess.Start(getBinaryFilePath(), String.Format("-f {0}", StringUtils.EscapeSpaces(path)), false, "."); } }
/// ------------------------------------------------------------------------------------ public static ExternalProcess StartProcessToMonitor(IEnumerable <string> args, DataReceivedEventHandler outputDataHandler, DataReceivedEventHandler errorDataHandler) { return(ExternalProcess.StartProcessToMonitor(MPlayerPath, args, outputDataHandler, errorDataHandler, LocalizationManager.GetString( "CommonToMultipleViews.MediaPlayer.UnableToStartMplayerProcessMsg", "Unable to start mplayer."))); }
public static bool IsInstalled() { IEnumerable <string> whereOutput = ExternalProcess.Start("where", BinaryFileName, true, ".").StdOut; return(whereOutput != null && whereOutput.Any() && !whereOutput.First().Contains("Could not find files for the given pattern(s)")); }
public async Task ShouldUpdateDotnetClassicProject() { const string oldPackageVersion = "5.2.3"; const string newPackageVersion = "5.2.4"; const string expectedPackageString = "<package id=\"Microsoft.AspNet.WebApi.Client\" version=\"{packageVersion}\" targetFramework=\"net47\" />"; const string testFolder = nameof(ShouldUpdateDotnetClassicProject); var testProject = $"{testFolder}.csproj"; var workDirectory = Path.Combine(_uniqueTemporaryFolder.FullPath, testFolder); Directory.CreateDirectory(workDirectory); var packagesFolder = Path.Combine(workDirectory, "packages"); Directory.CreateDirectory(packagesFolder); var projectContents = _testDotNetClassicProject.Replace("{packageVersion}", oldPackageVersion, StringComparison.OrdinalIgnoreCase); var projectPath = Path.Combine(workDirectory, testProject); await File.WriteAllTextAsync(projectPath, projectContents); var packagesConfigContents = _testPackagesConfig.Replace("{packageVersion}", oldPackageVersion, StringComparison.OrdinalIgnoreCase); var packagesConfigPath = Path.Combine(workDirectory, "packages.config"); await File.WriteAllTextAsync(packagesConfigPath, packagesConfigContents); await File.WriteAllTextAsync(Path.Combine(workDirectory, "nuget.config"), _nugetConfig); var logger = NukeeperLogger; var externalProcess = new ExternalProcess(logger); var monoExecutor = new MonoExecutor(logger, externalProcess); var nuGetPath = new NuGetPath(logger); var nuGetVersion = new NuGetVersion(newPackageVersion); var packageSource = new PackageSource(NuGetConstants.V3FeedUrl); var restoreCommand = new NuGetFileRestoreCommand(logger, nuGetPath, monoExecutor, externalProcess); var updateCommand = new NuGetUpdatePackageCommand(logger, nuGetPath, monoExecutor, externalProcess); var packageToUpdate = new PackageInProject("Microsoft.AspNet.WebApi.Client", oldPackageVersion, new PackagePath(workDirectory, testProject, PackageReferenceType.PackagesConfig)); await restoreCommand.Invoke(packageToUpdate, nuGetVersion, packageSource, NuGetSources.GlobalFeed); await updateCommand.Invoke(packageToUpdate, nuGetVersion, packageSource, NuGetSources.GlobalFeed); var contents = await File.ReadAllTextAsync(packagesConfigPath); Assert.That(contents, Does.Contain(expectedPackageString.Replace("{packageVersion}", newPackageVersion, StringComparison.OrdinalIgnoreCase))); Assert.That(contents, Does.Not.Contain(expectedPackageString.Replace("{packageVersion}", oldPackageVersion, StringComparison.OrdinalIgnoreCase))); }
public async Task InvalidCommandShouldFail() { var process = new ExternalProcess(); var result = await process.Run(Guid.NewGuid().ToString("N"), false); Assert.That(result.ExitCode, Is.Not.EqualTo(0)); Assert.That(result.ErrorOutput, Is.Not.Empty); Assert.That(result.Success, Is.False); }
public async Task ValidCommandShouldSucceed() { var process = new ExternalProcess(); var result = await process.Run("dir", false); Assert.That(result.ExitCode, Is.EqualTo(0)); Assert.That(result.Output, Is.Not.Empty); Assert.That(result.Success, Is.True); }
/// ------------------------------------------------------------------------------------ private void HandleGetStartedButtonClick(object sender, EventArgs e) { _buttonGetStarted.Enabled = false; ExternalProcess.CleanUpAllProcesses(); string newAnnotationFile = null; if (_radioButtonManual.Checked) { Settings.Default.DefaultSegmentationMethod = 0; newAnnotationFile = ManualSegmenterDlg.ShowDialog(_file, this, -1); } else if (_radioButtonCarefulSpeech.Checked) { Settings.Default.DefaultSegmentationMethod = 1; newAnnotationFile = (!AudioUtils.GetCanRecordAudio()) ? null : _file.RecordAnnotations(FindForm(), AudioRecordingType.Careful); } else if (_radioButtonElan.Checked) { var caption = LocalizationManager.GetString( "DialogBoxes.Transcription.CreateAnnotationFileDlg.LoadSegmentFileDlgCaption", "Select Segment File"); var filetype = LocalizationManager.GetString( "DialogBoxes.Transcription.CreateAnnotationFileDlg.ElanFileTypeString", "ELAN File (*.eaf)|*.eaf"); newAnnotationFile = GetAudacityOrElanFile(caption, filetype); Settings.Default.DefaultSegmentationMethod = 2; } else if (_radioButtonAudacity.Checked) { var caption = LocalizationManager.GetString( "DialogBoxes.Transcription.CreateAnnotationFileDlg.AudacityLabelOpenFileDlg.Caption", "Select Audacity Label File"); var filetype = LocalizationManager.GetString( "DialogBoxes.Transcription.CreateAnnotationFileDlg.AudacityLabelOpenFileDlg.FileTypeString", "Audacity Label File (*.txt)|*.txt"); newAnnotationFile = GetAudacityOrElanFile(caption, filetype); Settings.Default.DefaultSegmentationMethod = 3; } else if (_radioButtonAutoSegmenter.Checked) { var segmenter = new AutoSegmenter(_file, _project); newAnnotationFile = segmenter.Run(); Settings.Default.DefaultSegmentationMethod = 4; } if (newAnnotationFile != null && ComponentFileListRefreshAction != null) { ComponentFileListRefreshAction(newAnnotationFile, null); } _buttonGetStarted.Enabled = true; }
protected bool Execute() { File.Copy("SafetySharp.Modeling.dll", Path.Combine(_directory, "Binaries/Release/SafetySharp.Modeling.dll"), overwrite: true); var process = new ExternalProcess(Path.Combine(_directory, "Binaries/Release/Test.exe"), ""); process.Run(); return(process.ExitCode == 0); }
private void CheckPrismVersion(string pathToJavaExe, string pathToPrism) { var javaMachineCode = ExternalProcess.GetDllMachineType(pathToJavaExe); var fileNameToPrismDll = System.IO.Path.Combine(pathToPrism, "lib", "prism.dll"); var prismMachineCode = ExternalProcess.GetDllMachineType(fileNameToPrismDll); if (javaMachineCode != prismMachineCode) { throw new Exception("JAVA VM and PRISM version are not compiled for the same architecture."); } }
/// ------------------------------------------------------------------------------------ private static void SetUpErrorHandling() { Application.ApplicationExit += (sender, args) => ExternalProcess.CleanUpAllProcesses(); Application.ThreadException += (sender, args) => ExternalProcess.CleanUpAllProcesses(); AppDomain.CurrentDomain.UnhandledException += (sender, args) => ExternalProcess.CleanUpAllProcesses(); ErrorReport.EmailAddress = "*****@*****.**"; ErrorReport.AddStandardProperties(); ExceptionHandler.Init(); ExceptionHandler.AddDelegate((w, e) => Analytics.ReportException(e.Exception)); }
public static void LaunchSessionServer() { string filePathName = @"External\HoloToolkit\Sharing\Server\SharingService.exe"; if (!File.Exists(filePathName)) { Debug.LogError("Sharing service does not exist at location: " + filePathName); Debug.LogError("Manually copy SharingService.exe to this path from HoloToolkit-Unity\\External."); return; } ExternalProcess.FindAndLaunch(filePathName, @"-local"); }
public static void LaunchSessionUI() { string filePathName = @"External\MixedRealityToolkit\Sharing\Tools\SessionManager\x86\SessionManager.UI.exe"; if (!File.Exists(filePathName)) { Debug.LogError("Session Manager UI does not exist at location: " + filePathName); Debug.LogError("Please enable the Sharing Service via Mixed Reality Toolkit -> Configure -> Apply Mixed Reality Project Settings."); return; } ExternalProcess.FindAndLaunch(filePathName); }
public static void LaunchProfilerX() { string filePathName = @"External\HoloToolkit\Sharing\Tools\Profiler\x86\ProfilerX.exe"; if (!File.Exists(filePathName)) { Debug.LogError("Profiler does not exist at location: " + filePathName); Debug.LogError("Manually copy ProfilerX.exe to this path from HoloToolkit-Unity\\External."); return; } ExternalProcess.FindAndLaunch(filePathName); }
public static void LaunchProfilerX() { string filePathName = @"External\HoloToolkit\Sharing\Tools\Profiler\x86\ProfilerX.exe"; if (!File.Exists(filePathName)) { Debug.LogError("Profiler does not exist at location: " + filePathName); Debug.LogError("Please enable the Sharing Service via HoloToolkit -> Configure -> Apply Project Settings."); return; } ExternalProcess.FindAndLaunch(filePathName); }
/// <summary> /// Creates a new <see cref="_ltsMin" /> process instance that checks the <paramref name="modelFile" />. /// </summary> /// <param name="modelFile">The model that should be checked.</param> /// <param name="checkArgument">The argument passed to LtsMin that indicates which kind of check to perform.</param> private void CreateProcess(string modelFile, string checkArgument) { Requires.That(_ltsMin == null, "An instance of LtsMin is already running."); var loaderAssembly = Path.Combine(Environment.CurrentDirectory, "SafetySharp.LtsMin.dll"); _ltsMin = new ExternalProcess( fileName: "pins2lts-seq.exe", commandLineArguments: $"--loader=\"{loaderAssembly}\" \"{modelFile}\" {checkArgument}", outputCallback: output => OutputWritten?.Invoke(output)) { WorkingDirectory = Environment.CurrentDirectory }; }
protected ExternalProcess.Result startExternalProcess( string appName, string arguments, string path, bool wait, int[] successcodes) { try { return(ExternalProcess.Start(appName, arguments, wait, path, successcodes)); } catch (ExternalProcessFailureException ex) { throw new GitCommandServiceInternalException(ex); } catch (ExternalProcessSystemException ex) { throw new GitCommandServiceInternalException(ex); } }
protected bool Compile(string testFile) { var projectPath = Path.Combine(_directory, "TestProject.csproj"); File.Copy("End2End/Files/TestProject.csproj", projectPath, overwrite: true); File.Copy(Path.Combine("End2End/Files", testFile), Path.Combine(_directory, "TestCode.cs"), overwrite: true); var msbuildPath = ToolLocationHelper.GetPathToBuildTools(ToolLocationHelper.CurrentToolsVersion); var process = new ExternalProcess(Path.Combine(msbuildPath, "msbuild.exe"), $"\"{projectPath}\" /p:Configuration=Release /p:Platform=AnyCPU /nr:false", message => Output.Log("{0}", message)); process.Run(); return(process.ExitCode == 0); }
/// ------------------------------------------------------------------------------------ public static Image GetImageFromVideo(string videoPath, float seconds) { Image img = null; videoPath = videoPath.Replace('\\', '/'); var prs = new ExternalProcess(MPlayerPath); var tmpFolder = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(tmpFolder); var tmpFile = Path.Combine(tmpFolder, "00000001.jpg"); try { prs.StartInfo.Arguments = string.Format("-nocache -nofontconfig -really-quiet -frames 1 -ss {0} -nosound -vo jpeg:outdir=\"\"\"{1}\"\"\" \"{2}\"", seconds, tmpFolder, videoPath); prs.StartProcess(); prs.WaitForExit(); prs.Close(); // I'm hesitant to comment out this line, but because of SP-248, we'll see what happens. //ComponentFile.WaitForFileRelease(videoPath); if (File.Exists(tmpFile)) { // I could use Image.FromFile, but that leaves // a lock on the file, for some reason. var stream = new FileStream(tmpFile, FileMode.Open); img = Image.FromStream(stream); stream.Close(); } } finally { if (File.Exists(tmpFile)) { File.Delete(tmpFile); } try { Directory.Delete(tmpFolder); } catch { } } return(img); }
/// <summary> /// Executes the external process for processing the task /// </summary> /// <param name="task">The task to be processed.</param> /// <param name="settings">Contains information about the processing request.</param> /// <returns>The result of task processing.</returns> protected override TaskProcessResult RunExternalTaskProcess(ITask task, TaskExecutionSettings settings) { var process = new ExternalProcess { CommandPath = ExecutablePath(@"TitanSpikeClusterer.exe"), Arguments = string.Format("ClusterWorkerBlockRange {8} {0} {1} {2} {3} {4} {5} {6} {7}", task.Parameters["HostName"], task.Parameters["DataFileName"], task.Parameters["NumChannels"], task.Parameters["OutFileName"], task.Parameters["MinTemp"], task.Parameters["MaxTemp"], task.Parameters["FirstBlock"], task.Parameters["NumBlocks"], LocalPath("Clusterer")), WorkingDirectory = LocalStoragePath }; try { ExternalProcessResult processOutput = process.Run(); return(new TaskProcessResult { Success = TaskProcessSuccess.Succeeded }); } catch (ExternalProcessException ex) { string outputInfo = "No program output"; if (!string.IsNullOrEmpty(ex.StandardError) || !string.IsNullOrEmpty(ex.StandardOutput)) { outputInfo = Environment.NewLine + "stderr: " + ex.StandardError + Environment.NewLine + "stdout: " + ex.StandardOutput; } Log.Error("Failed to invoke command {0} {1}: exit code was {2}. {3}", ex.CommandPath, ex.Arguments, ex.ExitCode, outputInfo); } catch (Exception ex) { Log.Error("Error in task processor: {0}", ex.ToString()); } return(new TaskProcessResult { Success = TaskProcessSuccess.RetryableFailure }); }
/// <summary> /// Checks whether the <paramref name="formula" /> holds in all states of the <paramref name="model" />. /// </summary> /// <param name="model">The model that should be checked.</param> /// <param name="formula">The formula that should be checked.</param> /// <param name="checkArgument">The argument passed to LtsMin that indicates which kind of check to perform.</param> private AnalysisResult Check(ModelBase model, Formula formula, string checkArgument) { try { using (var modelFile = new TemporaryFile("ssharp")) { File.WriteAllBytes(modelFile.FilePath, RuntimeModelSerializer.Save(model, formula)); try { CreateProcess(modelFile.FilePath, checkArgument); Run(); } catch (Win32Exception e) { throw new InvalidOperationException( "Failed to start LTSMin. Ensure that pins2lts-seq.exe can be found by either copying it next " + "to the executing assembly or by adding it to the system path. The required cygwin dependencies " + $"must also be available. The original error message was: {e.Message}", e); } var success = InterpretExitCode(_ltsMin.ExitCode); return new AnalysisResult { FormulaHolds = success }; } } finally { _ltsMin = null; } }
private async Task Update(DatabaseSetting dbSetting, DvcsScriptRepositoryBase.RevisionIdentifierBase sourceChangeset) { ICollection<BuildItem> buildItems; using (var connection = new SqlConnection(dbSetting.ConnectionString)) { await connection.OpenAsync(); using (var transaction = connection.BeginTransaction()) { var fileSystem = new FileSystem(); var db = dbSetting.Create(connection, transaction); var gitProcess = new ExternalProcess(pathToGit.FullName); var dvcsScriptRepo = new GitScriptRepository(dbSetting.ScriptsPath, dbSetting.ServerName, dbSetting.DatabaseName, gitProcess, fileSystem, sqlParser, new ConsoleLogger(SeverityLevel.Warning), false); dvcsScriptRepo.SourceChangeset = sourceChangeset; buildItems = await db.GetChangedBuildItemsAsync(dvcsScriptRepo); transaction.Commit(); } } await DispatcherInvoke(() => { ((MainWindowViewModel)DataContext).IsReady = true; ((MainWindowViewModel)DataContext).IsDone = false; ObservableCollection<BuildItemViewModel> itemsCollection = new ObservableCollection<BuildItemViewModel> (buildItems.Select(x => new BuildItemViewModel(x, Dispatcher))); ((MainWindowViewModel)DataContext).Items = itemsCollection; }); }