private void btnTest_Click(object sender, EventArgs e) { var iface = cbQuickInterface.SelectedItem as QuickSetupDatabase.ProgrammingInterface; if (iface != null && iface.UsbIdentities != null && iface.UsbIdentities.Length > 0) { if (!UsbDriverHelper.TryCheckDeviceAndInstallDriversInteractively(iface.UsbIdentities, iface.UniversalDriverId)) { return; } } Process process = new Process(); process.StartInfo.FileName = _OpenOCDDirectory + @"\bin\openocd.exe"; process.StartInfo.WorkingDirectory = _OpenOCDDirectory + @"\share\openocd\scripts"; process.StartInfo.Arguments = CommandLineTools.BuildCommandLine(_Method.GDBServerArguments, new Dictionary <string, string>(), Configuration); using (var frm = new CommandTestForm(process)) { frm.ShowDialog(); string output = frm.AllOutput; if (output.Contains("An adapter speed is not selected in the init script") && !cbQuickSpeed.Checked) { if (MessageBox.Show("OpenOCD could not determine JTAG speed. Do you want to specify it explicitly?", "VisualGDB", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { cbQuickSpeed.Checked = true; numSpeed2.Focus(); } } } }
private void btnTest_Click(object sender, EventArgs e) { var adapterCommand = (cbAdapter.SelectedItem as PropertyEntry.Enumerated.Suggestion)?.InternalValue; UsbDriverHelper.UsbIdentity id = new UsbDriverHelper.UsbIdentity { VID = "03eb" }; if (adapterCommand != null) { switch (adapterCommand) { case "-2": id.PID = "2103"; break; case "-g": id.PID = "2107"; break; } } if (id.PID != null) { if (!UsbDriverHelper.TryCheckDeviceAndInstallDriversInteractively(new UsbDriverHelper.UsbIdentity[] { id }, "com.sysprogs.libusb.mini")) { return; } } Process process = new Process(); process.StartInfo.FileName = _ToolchainBin + @"\avarice.exe"; process.StartInfo.WorkingDirectory = _ToolchainBin; var cfg = Configuration; cfg.Remove("com.sysprogs.avr.avarice.erase"); cfg.Remove("com.sysprogs.avr.avarice.program"); cfg.Remove("com.sysprogs.avr.avarice.verify"); cfg.Remove("com.sysprogs.avr.avarice.port"); process.StartInfo.Arguments = CommandLineTools.BuildCommandLine(_MyMethod.GDBServerArguments, new Dictionary <string, string>(), cfg).Replace(_MyMethod.GDBServerArguments.GNUArgumentPrefix, "") + " -l"; using (var frm = new CommandTestForm(process)) { frm.ShowDialog(); } }
static void Main(string[] args) { System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture; System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); try { Assembly assembly = Assembly.GetExecutingAssembly(); var name = (assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false).FirstOrDefault() as AssemblyProductAttribute).Product; var version = new Version((assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false).FirstOrDefault() as AssemblyFileVersionAttribute).Version); var description = (assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false).FirstOrDefault() as AssemblyDescriptionAttribute).Description; var copyright = (assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false).FirstOrDefault() as AssemblyCopyrightAttribute).Copyright; var informational = (assembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false).FirstOrDefault() as AssemblyInformationalVersionAttribute).InformationalVersion; IndentWriteLine("{0} v{1}.{2} ({3})", name, version.Major, version.Minor, informational); IndentWriteLine("{0}", description); IndentWriteLine("{0}", copyright); IndentWriteLine(); IndentWriteLine("Scarlet library information:"); indent++; foreach (AssemblyName referencedAssembly in Assembly.GetExecutingAssembly().GetReferencedAssemblies().Where(x => x.Name.StartsWith("Scarlet")).OrderBy(x => x.Name)) { var loadedAssembly = Assembly.Load(referencedAssembly.Name); var assemblyInformational = (loadedAssembly.GetCustomAttributes(typeof(AssemblyInformationalVersionAttribute), false).FirstOrDefault() as AssemblyInformationalVersionAttribute).InformationalVersion; IndentWriteLine("{0} v{1} ({2})", referencedAssembly.Name, referencedAssembly.Version, assemblyInformational); } indent--; IndentWriteLine(); args = CommandLineTools.CreateArgs(Environment.CommandLine); if (args.Length < 2) { throw new CommandLineArgsException("<input ...> [--keep | --output <directory>]"); } List <DirectoryInfo> inputDirs = new List <DirectoryInfo>(); List <FileInfo> inputFiles = new List <FileInfo>(); for (int i = 1; i < args.Length; i++) { DirectoryInfo directory = new DirectoryInfo(args[i]); if (directory.Exists) { IEnumerable <FileInfo> files = directory.EnumerateFiles("*", SearchOption.AllDirectories).Where(x => x.Extension != ".png"); IndentWriteLine("Adding directory '{0}', {1} file{2} found...", directory.Name, files.Count(), (files.Count() != 1 ? "s" : string.Empty)); inputDirs.Add(directory); continue; } FileInfo file = new FileInfo(args[i]); if (file.Exists) { IndentWriteLine("Adding file '{0}'...", file.Name); inputFiles.Add(file); continue; } if (args[i].StartsWith("-")) { switch (args[i].TrimStart('-')) { case "k": case "keep": keepFiles = true; break; case "o": case "output": globalOutputDir = new DirectoryInfo(args[++i]); break; default: IndentWriteLine("Unknown argument '{0}'.", args[i]); break; } continue; } IndentWriteLine("File or directory '{0}' not found.", args[i]); } if (inputDirs.Count > 0) { foreach (DirectoryInfo inputDir in inputDirs) { IndentWriteLine(); IndentWriteLine("Parsing directory '{0}'...", inputDir.Name); indent++; DirectoryInfo outputDir = (globalOutputDir != null ? globalOutputDir : new DirectoryInfo(inputDir.FullName + " " + defaultOutputDir)); foreach (FileInfo inputFile in inputDir.EnumerateFiles("*", SearchOption.AllDirectories).Where(x => x.Extension != ".png" && !IsSubdirectory(x.Directory, outputDir))) { ProcessInputFile(inputFile, inputDir, outputDir); } indent--; } } if (inputFiles.Count > 0) { IndentWriteLine(); IndentWriteLine("Parsing files..."); indent++; foreach (FileInfo inputFile in inputFiles) { DirectoryInfo outputDir = (globalOutputDir != null ? globalOutputDir : inputFile.Directory); ProcessInputFile(inputFile, inputFile.Directory, outputDir); } } } #if !DEBUG catch (CommandLineArgsException claEx) { IndentWriteLine("Invalid arguments; expected: {0}.", claEx.ExpectedArgs); } catch (Exception ex) { IndentWriteLine("Exception occured: {0}.", ex.Message); } #endif finally { stopwatch.Stop(); indent = 0; IndentWriteLine(); IndentWriteLine("Operation completed in {0}.", GetReadableTimespan(stopwatch.Elapsed)); IndentWriteLine(); IndentWriteLine("Press any key to exit."); Console.ReadKey(); } }
public byte[] Execute() { var exePath = UtilityExePath ?? HostingEnvironment.MapPath("~/App_Data/Reporting/wkhtmltopdf.exe"); if (!File.Exists(exePath)) { throw new InvalidOperationException(String.Format("Can't find wkhtmltopdf.exe which is required for PDF generation.\n" + "Please download a stable version from http://wkhtmltopdf.org/downloads.html\n and place it under directory '{0}'.", Path.GetDirectoryName(exePath))); } if (String.IsNullOrEmpty(this.Url)) { throw new ArgumentNullException("url"); } var args = new List <string>(); args.Add(!SmartShrinking ? "--disable-smart-shrinking" : "--enable-smart-shrinking"); if (!string.IsNullOrEmpty(PageSize)) { args.Add("--page-size"); args.Add(PageSize); } if (!string.IsNullOrEmpty(PageWidth)) { args.Add("--page-width"); args.Add(PageWidth); } if (!string.IsNullOrEmpty(PageHeight)) { args.Add("--page-height"); args.Add(PageHeight); } if (MarginLeft != null) { args.Add("--margin-left"); args.Add(MarginLeft); } if (MarginTop != null) { args.Add("--margin-top"); args.Add(MarginTop); } if (MarginRight != null) { args.Add("--margin-right"); args.Add(MarginRight); } if (MarginBottom != null) { args.Add("--margin-bottom"); args.Add(MarginBottom); } if (Dpi != null) { args.Add("--dpi"); args.Add(Dpi.Value.ToString(CultureInfo.InvariantCulture)); } if (Zoom != null) { args.Add("--zoom"); args.Add(Zoom); } if (UsePrintMediaType) { args.Add("--print-media-type"); } else { args.Add("--no-print-media-type"); } if (PrintBackground) { args.Add("--background"); } else { args.Add("--no-background"); } if (FooterHtmlUrl != null) { args.Add("--footer-html"); args.Add(FooterHtmlUrl); } if (Landscape) { args.Add("--orientation"); args.Add("Landscape"); } foreach (var cookie in Cookies) { args.Add("--cookie"); args.Add(cookie.Key); args.Add(cookie.Value); } foreach (var replace in FooterHeaderReplace) { args.Add("--replace"); args.Add(replace.Key); args.Add(replace.Value); } args.Add(this.Url); foreach (var additional in AdditionalUrls) { args.Add(additional); } foreach (var arg in CustomArgs) { args.Add(arg); } var tempFile = Path.GetTempFileName(); try { args.Add(tempFile); var process = new Process { StartInfo = new ProcessStartInfo(exePath, CommandLineTools.EscapeArguments(args.ToArray())) { UseShellExecute = false, CreateNoWindow = true } }; if (!process.Start()) { throw new InvalidOperationException("An error occured while starting PDF generator!"); } if (!process.WaitForExit(TimeoutSeconds * 1000)) // max 300 seconds { throw new InvalidOperationException("Timeout while PDF generation!"); } if (process.ExitCode != 0 && process.ExitCode != 1) { throw new InvalidOperationException(String.Format("PDF generator returned error code {0}!", process.ExitCode)); } if (!File.Exists(tempFile)) { throw new InvalidOperationException("Can't find generatored PDF file!"); } var bytes = File.ReadAllBytes(tempFile); if (bytes.Length == 0) { throw new InvalidOperationException("Generated PDF file is empty!"); } return(bytes); } finally { TemporaryFileHelper.TryDelete(tempFile); } }
public SetupAssistedProgressViewModel(FlutnetSetupInArg setupArguments, IScreen screen = null) : base("setup_assisted_progress", screen) { Title = "Configuration in progress"; Button1Visible = false; Button2Visible = false; Button3Visible = false; // Create the command that calls Flutnet CLI RunDiagnostic = ReactiveCommand.CreateFromTask(async ct => { CommandLineCallResult callResult = await CommandLineTools.Call <FlutnetSetupOutArg>(setupArguments, ct); // This is not the proper way to change property values and raise property change notifications: // we should return a public object and subscribe to the command observable // so that we can use ReactiveUI framework methods such as ToProperty, BindTo etc. SetupResult overallResult = null; FlutnetSetupOutArg setupResult = null; if (callResult.Canceled) { // Jump to finish page and notify the user that the operation has been canceled. overallResult = new SetupResult { OperationCanceled = true }; } else if (callResult.Failed) { // Jump to finish page and notify the user that an unexpected error occured. overallResult = new SetupResult { OperationFailed = true }; } else { FlutnetSetupOutArg result = (FlutnetSetupOutArg)callResult.CommandResult; if (!result.Success) { // Jump to finish page and notify the user that an unexpected error occured. overallResult = new SetupResult { OperationFailed = true }; } else { //setupResult = result; overallResult = new SetupResult { OperationResult = setupResult }; } } if (overallResult != null) { await HostScreen.Router.Navigate.Execute(new SetupFinishViewModel(overallResult, this, HostScreen)); } else { //await HostScreen.Router.Navigate.Execute(new SetupCheckFlutterErrorViewModel(checkResult, HostScreen)); } }); RunDiagnostic.IsExecuting.ToProperty(this, x => x.IsInProgress, out _isInProgress); RunDiagnostic.IsExecuting.BindTo(this, x => x.IsBusy); // Execute the command when the View is activated this.WhenActivated(disposables => { RunDiagnostic.Execute(Unit.Default).Subscribe().DisposeWith(disposables); }); }
public static ParsedBuildLog ParseRISCVBuildLog(string buildLogFile) { var rgBuildLine = new Regex("^riscv64-unknown-elf-gcc .*"); ParsedBuildLog result = new ParsedBuildLog(); foreach (var line in File.ReadAllLines(buildLogFile)) { if (rgBuildLine.IsMatch(line)) { var args = CommandLineTools.CommandLineToArgs(line); Dictionary <string, string> defines = new Dictionary <string, string>(); List <string> includes = new List <string>(); List <string> otherFlags = new List <string>(); string source = null; int skipNow = 0; bool isLinker = args.FirstOrDefault(a => a.StartsWith("-Wl,")) != null; foreach (var arg in args.Skip(1)) { if (skipNow-- > 0) { continue; } if (arg.StartsWith("-D")) { string key = arg.Substring(2), value = null; int idx = key.IndexOf('='); if (idx != -1) { value = key.Substring(idx + 1); key = key.Substring(0, idx); } defines[key] = value; } else if (arg.StartsWith("-I")) { includes.Add(arg.Substring(2)); } else if (arg.StartsWith("-m") || arg.StartsWith("--specs")) { otherFlags.Add(arg); } else if (arg.StartsWith("-f") && arg.EndsWith("-sections")) { continue; } else if (arg.StartsWith("-O") || arg.StartsWith("-g") || arg == "-c") { continue; } else if (arg == "-MT" || arg == "-MF" || arg == "-o") { skipNow = 1; continue; } else if (arg.StartsWith("-M")) { continue; } else if (arg.StartsWith("&&")) { break; } else if (arg.EndsWith(".c") || arg.EndsWith(".S")) { source = arg; } else if (isLinker) { if (arg == "-Wl,--gc-sections" || arg == "-Wl,--start-group" || arg == "-Wl,--end-group" || arg.StartsWith("-Wl,-Map") || arg.StartsWith("-L")) { continue; } else if (arg.StartsWith("-T")) { result.LinkerScript = arg.Substring(2); } else if (arg.StartsWith("-no")) { result.AllLDFlags.Add(arg); } else if (arg.StartsWith("-l")) { result.AllLibs.Add(arg.Substring(2)); } else { throw new Exception("Unknown linker argument: " + arg); } } else { throw new Exception("Unknown argument: " + arg); } } if (source == null) { throw new Exception("Unknown source file for command line"); } foreach (var kv in defines) { result.allDefines[kv.Key] = kv.Value; } foreach (var inc in includes) { result.allIncludes.Add(inc); } foreach (var flag in otherFlags) { result.allFlags.Add(flag); } result.AllSources.Add(source); } } return(result); }
public CreateProjectProgressViewModel(FlutnetAppSettings appSettings, FlutnetProjectSettings projectSettings, NewProjectViewModel screen = null) : base("newprj_progress", screen) { _appSettings = appSettings; _projectSettings = projectSettings; Title = "New Project"; Description = "The project will take some time to generate.\nWait until the procedure finish.\n"; IsDescriptionVisible = false; NextText = "Finish"; BackVisible = false; IsFinishPage = true; OutputLines = new ObservableCollection <string>(); // Observe any changes in the observable collection. // Note that the property has no public setters, so we // assume the collection is mutated by using the Add(), // Delete(), Clear() and other similar methods. OutputLines // Convert the collection to a stream of chunks, // so we have IObservable<IChangeSet<TKey, TValue>> // type also known as the DynamicData monad. .ToObservableChangeSet() // Each time the collection changes, we get // all updated items at once. .ToCollection() // Aggregate all the elements in the collection // into a multi-line string. .Select(lines => string.Join(Environment.NewLine, lines)) // Then, we convert the multi-line string to the // property a multi-line TextBox can bind. .ToProperty(this, x => x.Output, out _output, scheduler: RxApp.MainThreadScheduler); // Create the command that calls Flutnet CLI CreateProject = ReactiveCommand.CreateFromTask(async ct => { NewProjectInArg arguments = BuildCommandLineArg(); CommandLineCallResult callResult = await CommandLineTools.Call <NewProjectOutArg>(arguments, ct, line => { OutputLines.Add(line); }); // This is not the proper way to change property values and raise property change notifications: // we should return a public object and subscribe to the command observable // so that we can use ReactiveUI framework methods such as ToProperty, BindTo etc. if (callResult.Canceled) { IsCanceled = true; } else if (callResult.Failed) { IsFailed = true; } else { OutArg result = callResult.CommandResult; if (!result.Success) { IsFailed = true; } else { IsCompletedSuccessfully = true; } } }); CreateProject.IsExecuting.ToProperty(this, x => x.IsInProgress, out _isInProgress); CreateProject.IsExecuting.BindTo(this, x => x.IsBusy); BrowseProject = ReactiveCommand.Create( execute: () => Launcher.OpenFolder(Path.Combine(projectSettings.Location, projectSettings.SolutionName)), canExecute: this.WhenAnyValue(t => t.IsCompletedSuccessfully)); // Execute the command when the View is activated Activator = new ViewModelActivator(); this.WhenActivated(disposables => { CreateProject.Execute(Unit.Default).Subscribe().DisposeWith(disposables); }); this.WhenAnyValue(t => t.IsInProgress, t => !t).BindTo(this, t => t.NextEnabled); }
public ConfigureProjectViewModel(FlutnetAppSettings appSettings, IScreen screen = null) : base("newprj_project", screen) { _appSettings = appSettings; Title = "New Project"; Description = "Edit project settings: you'll see a preview in the right panel.\nPressing \"Create\" will generate the project folder and all relative files."; IsDescriptionVisible = true; NextText = "Create"; IsFinishPage = false; BrowseLocation = ReactiveCommand.CreateFromTask(BrowseLocationAsync); BrowseLocation.Where(t => !string.IsNullOrEmpty(t)).BindTo(this, t => t.Location); AppSettings.Default.Preferences.Reload(); _location = !string.IsNullOrEmpty(AppSettings.Default.Preferences.LastProjectLocation) ? AppSettings.Default.Preferences.LastProjectLocation : OperatingSystem.DefaultProjectsLocation(); if (appSettings != null) { string projectName = AppNameToProjectName(appSettings.AppName); if (!string.IsNullOrEmpty(projectName)) { _projectName = projectName; } } else { _projectName = DefaultProjectName; _solutionName = DefaultSolutionName; _flutterModuleName = DefaultFlutterModuleName; } this.WhenAnyValue(t => t.ProjectName) .Do(t => { this.RaisePropertyChanged(nameof(SolutionName)); this.RaisePropertyChanged(nameof(FlutterModuleName)); }) .Select(t => ToSafeFilename(t, DefaultAppName)) .ToProperty(this, t => t.OutputProjectName, out _outputProjectName, initialValue: ProjectName); this.WhenAnyValue(t => t.OutputProjectName) .Select(t => $"{t}.Android") .ToProperty(this, t => t.OutputProjectDroidName, out _outputProjectDroidName, initialValue: $"{OutputProjectName}.Android"); this.WhenAnyValue(t => t.OutputProjectName) .Select(t => $"{t}.iOS") .ToProperty(this, t => t.OutputProjectIosName, out _outputProjectIosName, initialValue: $"{OutputProjectName}.iOS"); this.WhenAnyValue(t => t.OutputProjectName) .Select(t => $"{t}.ServiceLibrary") .ToProperty(this, t => t.OutputProjectServiceLibName, out _outputProjectServiceLibName, initialValue: $"{OutputProjectName}.ServiceLibrary"); this.WhenAnyValue(t => t.SolutionName) .Select(t => ToSafeFilename(t, DefaultSolutionName)) .ToProperty(this, t => t.OutputSolutionName, out _outputSolutionName, initialValue: SolutionName ?? DefaultSolutionName); this.WhenAnyValue(t => t.FlutterModuleName) .Select(ToSafeDartPackageName) .ToProperty(this, t => t.OutputFlutterModuleName, out _outputFlutterModuleName, initialValue: FlutterModuleName ?? DefaultFlutterModuleName); this.WhenAnyValue(t => t.OutputFlutterModuleName) .Select(t => $"{t}_bridge") .ToProperty(this, t => t.OutputFlutterPackageName, out _outputFlutterPackageName, initialValue: $"{OutputFlutterModuleName}_bridge"); this.WhenAnyValue( t => t.ProjectName, t => t.SolutionName, t => t.FlutterModuleName, (prj, sln, flutter) => !string.IsNullOrWhiteSpace(prj) && !string.IsNullOrWhiteSpace(sln) && !string.IsNullOrWhiteSpace(flutter)) .BindTo(this, t => t.NextEnabled); BuildProjectTree(); // Command to check if the installed version of Flutter is supported CheckFlutterVersion = ReactiveCommand.CreateFromTask(async ct => { CommandLineCallResult callResult = await CommandLineTools.Call <FlutterInfoInArg, FlutterInfoOutArg>(ct); if (callResult.Canceled || callResult.Failed) { FlutterVersionHasIssues = true; FlutterVersionNotes = "Unable to detect installed Flutter version. Compatibility with Flutnet unknown."; return; } FlutterInfoOutArg result = (FlutterInfoOutArg)callResult.CommandResult; if (!result.Success) { FlutterVersionHasIssues = true; FlutterVersionNotes = "Unable to detect installed Flutter version. Compatibility with Flutnet unknown."; return; } StringBuilder sb = new StringBuilder(); sb.AppendLine($"Installed Flutter version: {result.InstalledVersion}"); switch (result.Compatibility) { case FlutterCompatibility.Supported: FlutterVersionHasIssues = false; break; case FlutterCompatibility.SupportNotGuaranteed: FlutterVersionHasIssues = true; sb.AppendLine("This version is NOT officially compatible with Flutnet and the resulting projects may not work or may exhibit unexpected behaviors."); if (!string.IsNullOrEmpty(result.NextSupportedVersion)) { sb.AppendLine($"We recommend that you update Flutter to the latest supported version ({result.LatestSupportedVersion})."); } else { sb.AppendLine($"The latest supported version is {result.LatestSupportedVersion}."); } break; case FlutterCompatibility.NotSupported: FlutterVersionHasIssues = true; NextEnabled = false; sb.AppendLine("Unfortunately this version is NOT compatible with Flutnet."); sb.AppendLine($"Please update Flutter to the latest supported version ({result.LatestSupportedVersion})."); break; } FlutterVersion = result.InstalledVersion; FlutterVersionNotes = sb.ToString(); }); CheckFlutterVersion.IsExecuting.BindTo(this, x => x.IsBusy); this.WhenAnyValue(t => t.IsBusy).Select(t => !t).BindTo(this, p => p.NextEnabled); FlutterVersionNotes = "Retrieving information about the installed version of Flutter..."; }
public byte[] Execute() { var exePath = UtilityExePath ?? HostingEnvironment.MapPath("~/Reports/Utility/wkhtmltopdf.exe"); if (!File.Exists(exePath)) { throw new InvalidOperationException(String.Format("Can't find wkhtmltopdf.exe which is required for PDF generation at location: '{0}'!", exePath)); } if (String.IsNullOrEmpty(this.Url)) { throw new ArgumentNullException("url"); } var args = new List <string>(); if (UsePrintMediaType) { args.Add("--print-media-type"); } else { args.Add("--no-print-media-type"); } foreach (var cookie in Cookies) { args.Add("--cookie"); args.Add(cookie.Key); args.Add(cookie.Value); } args.Add(this.Url); foreach (var additional in AdditionalUrls) { args.Add(additional); } var tempFile = Path.GetTempFileName(); try { args.Add(tempFile); var process = new Process { StartInfo = new ProcessStartInfo(exePath, CommandLineTools.EscapeArguments(args.ToArray())) { UseShellExecute = false, CreateNoWindow = true } }; if (!process.Start()) { throw new InvalidOperationException("An error occured while starting PDF generator!"); } if (!process.WaitForExit(TimeoutSeconds * 1000)) // max 300 seconds { throw new InvalidOperationException("Timeout while PDF generation!"); } if (process.ExitCode != 0 && process.ExitCode != 1) { throw new InvalidOperationException(String.Format("PDF generator returned error code {0}!", process.ExitCode)); } if (!File.Exists(tempFile)) { throw new InvalidOperationException("Can't find generatored PDF file!"); } var bytes = File.ReadAllBytes(tempFile); if (bytes.Length == 0) { throw new InvalidOperationException("Generated PDF file is empty!"); } return(bytes); } finally { TemporaryFileHelper.TryDelete(tempFile); } }
public AboutViewModel(IScreen hostScreen) : base("about", hostScreen) { Title = "About"; Description = ""; IsDescriptionVisible = false; OpenFlutnetWebsite = ReactiveCommand.Create(() => Launcher.OpenURL(FlutnetHome)); ContactFlutnetInfo = ReactiveCommand.Create(() => Launcher.MailTo("*****@*****.**")); ContactFlutnetSupport = ReactiveCommand.Create(() => Launcher.MailTo("*****@*****.**")); DownloadNewVersion = ReactiveCommand.Create(() => Launcher.OpenURL(_newVersionUrl)); // Create the command that calls Flutnet CLI // for contacting the server and checking for updates CheckForUpdates = ReactiveCommand.CreateFromTask(async ct => { CommandLineCallResult callResult = await CommandLineTools.Call <UpdateCheckInArg, UpdateCheckOutArg>(ct); // This is not the proper way to change property values and raise property change notifications: // we should return a public object and subscribe to the command observable // so that we can use ReactiveUI framework methods such as ToProperty, BindTo etc. if (callResult.Canceled || callResult.Failed) { IsNewVersionAvailable = false; FlutnetVersionMessage = "An unexpected error occured, please retry."; } else { UpdateCheckOutArg result = (UpdateCheckOutArg)callResult.CommandResult; if (!result.Success) { IsNewVersionAvailable = false; FlutnetVersionMessage = result.ErrorMessage; } else if (result.UpToDate) { IsNewVersionAvailable = false; FlutnetVersionMessage = "Your software is up to date."; } else { IsNewVersionAvailable = true; FlutnetVersionMessage = $"A new version of Flutnet ({result.NewVersion}) is available."; _newVersionUrl = result.DownloadUrl; } } }); CheckForUpdates.IsExecuting.ToProperty(this, x => x.IsCheckingForUpdates, out _isCheckingForUpdates); CheckForUpdates.IsExecuting.BindTo(this, x => x.IsBusy); this.WhenAnyValue(t => t.CheckForUpdatesAtStartup).Skip(1).Subscribe(value => { AppSettings.Default.Preferences.CheckForUpdatesAtStartup = value; AppSettings.Default.Preferences.Save(); }); // Load user preferences when the view is activated this.WhenActivated((Action <IDisposable> disposables) => { AppSettings.Default.Preferences.Reload(); CheckForUpdatesAtStartup = AppSettings.Default.Preferences.CheckForUpdatesAtStartup; CurrentFlutnetVersion = Assembly.GetExecutingAssembly().GetProductVersion(); }); }
public byte[] Execute() { var exePath = UtilityExePath ?? HostingEnvironment.MapPath("~/Reports/Utility/wkhtmltopdf.exe"); if (!File.Exists(exePath)) { throw new InvalidOperationException(String.Format("PDF üretimi için gereken wkhtmltopdf.exe dosyası '{0}' konumunda bulunamadı'", exePath)); } if (String.IsNullOrEmpty(this.Url)) { throw new ArgumentNullException("url"); } var args = new List <string>(); if (UsePrintMediaType) { args.Add("--print-media-type"); } else { args.Add("--no-print-media-type"); } foreach (var cookie in Cookies) { args.Add("--cookie"); args.Add(cookie.Key); args.Add(cookie.Value); } args.Add(this.Url); foreach (var additional in AdditionalUrls) { args.Add(additional); } var tempFile = Path.GetTempFileName(); try { args.Add(tempFile); var process = new Process { StartInfo = new ProcessStartInfo(exePath, CommandLineTools.EscapeArguments(args.ToArray())) { UseShellExecute = false, CreateNoWindow = true } }; if (!process.Start()) { throw new InvalidOperationException("PDF üretim programı başlatılırken hata oluştu!"); } if (!process.WaitForExit(TimeoutSeconds * 1000)) // max 300 sn de üretmeli { throw new InvalidOperationException("PDF üretilirken zaman aşımı oluştu!"); } if (process.ExitCode != 0 && process.ExitCode != 1) { throw new InvalidOperationException(String.Format("PDF üretim programı {0} hata kodu döndürdü!", process.ExitCode)); } if (!File.Exists(tempFile)) { throw new InvalidOperationException("PDF üretimi sonrasında geçici dosya bulunamadı!"); } var bytes = File.ReadAllBytes(tempFile); if (bytes.Length == 0) { throw new InvalidOperationException("Üretilen PDF dosyası boş!"); } return(bytes); } finally { TemporaryFileHelper.TryDelete(tempFile); } }