public void Upload_Empty_Path_sec_arg() { FileSystemExtensions.Upload(FileSystem, "source_upload.txt", ""); }
public void Upload_Bad_Name() { FileSystemExtensions.Upload(FileSystem, "*sdfaj.d.txt", "dest_upload.txt"); }
public void Upload_Path_Too_Long_sec_arg() { FileSystemExtensions.Upload(FileSystem, "source_upload.txt", very_long_String); }
public void Upload_Path_Too_Long() { FileSystemExtensions.Upload(FileSystem, very_long_String, "dest_upload.txt"); }
public void Upload_Empty_Path() { FileSystemExtensions.Upload(FileSystem, "", "dest_upload.txt"); }
protected void SaveConfig() => FileSystemExtensions.SaveConfig(ConfigFile, this);
public void Upload_Not_Found() { FileSystemExtensions.Upload(FileSystem, "imaginary_source.txt", "dest_upload.txt"); }
public void Upload_Bad_Name_sec_arg() { FileSystemExtensions.Upload(FileSystem, "source_upload.txt", "*:.txt"); }
public void Upload() { FileSystemExtensions.Upload(FileSystem, "source_upload.txt", "dest_upload.txt"); }
public virtual void AddFiles(IEnumerable <IPackageFile> files, string rootDir) { FileSystemExtensions.AddFiles(this, files, rootDir); }
/// <summary> /// Runs a child process, synchronously, with the specified input. /// This method should be called by the parent process. It starts the child process, providing it /// with specific command line arguments that will allow the child process to support cancellation /// and error handling. /// The child process should call <see cref="RunAndListenToParentAsync{TInput,TOutput}"/>, provide /// it with the command line arguments and the main method that receives the input object and returns /// an object of type <typeparamref name="TOutput"/>. /// </summary> /// <example> /// Parent process: /// <code> /// private async cTask<OutputData> RunInChildProcess(string childProcessName, InputData input, ITracer tracer, CancellationToken cancellationToken) /// { /// IChildProcessManager childProcessManager = new ChildProcessManager(); /// OutputData output = await childProcessManager.RunChildProcessAsync<OutputData>(childProcessName, input, tracer, cancellationToken); /// return output; /// } /// </code> /// Child process: /// <code> /// public static void Main(string[] args) /// { /// ITracer tracer; /// // Initialize tracer... /// /// IChildProcessManager childProcessManager = new ChildProcessManager(); /// childProcessManager.RunAndListenToParentAsync<InputData, OutputData>(args, MainFunction, tracer).Wait(); /// } /// /// private static OutputData MainFunction(InputData input, CancellationToken cancellationToken) /// { /// // ... /// /// return output; /// } /// </code> /// </example> /// <typeparam name="TOutput">The child process output type</typeparam> /// <param name="exePath">The child process' executable file path</param> /// <param name="input">The child process input</param> /// <param name="cancellationToken">The cancellation token</param> /// <exception cref="InvalidOperationException">The child process could not be started</exception> /// <exception cref="ChildProcessException">The child process failed - see InnerException for details</exception> /// <returns>A <see cref="Task{TResult}"/>, returning the child process output</returns> public async Task <TOutput> RunChildProcessAsync <TOutput>(string exePath, object input, CancellationToken cancellationToken) { this.CurrentStatus = RunChildProcessStatus.Initializing; this.tracer.TraceInformation($"Starting to run child process {exePath}"); // Create a temporary folder for the child process string tempFolder = FileSystemExtensions.CreateTempFolder(TempSubFolderName); this.tracer.TraceInformation($"Created temporary folder for child process: {tempFolder}"); try { // The pipe from the parent to the child is used to pass a cancellation instruction // The pipe from the child to the parent is used to pass the child process output using (AnonymousPipeServerStream pipeParentToChild = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable)) { using (AnonymousPipeServerStream pipeChildToParent = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable)) { using (Process childProcess = new Process()) { // Write the output to the pipe await this.WriteToStream(input, pipeParentToChild, cancellationToken); // Get pipe handles string pipeParentToChildHandle = pipeParentToChild.GetClientHandleAsString(); string pipeChildToParentHandle = pipeChildToParent.GetClientHandleAsString(); // Prepare command line arguments ChildProcessArguments arguments = new ChildProcessArguments( pipeParentToChildHandle, pipeChildToParentHandle, this.tracer.SessionId, this.tracer.GetCustomProperties(), tempFolder); // Setup the child process childProcess.StartInfo = new ProcessStartInfo(exePath) { Arguments = ChildProcessArguments.ToCommandLineArguments(arguments), CreateNoWindow = true, UseShellExecute = false, RedirectStandardError = true }; // Start the child process Stopwatch sw = Stopwatch.StartNew(); childProcess.Start(); this.tracer.TraceInformation($"Started to run child process '{Path.GetFileName(exePath)}', process ID {childProcess.Id}"); this.CurrentStatus = RunChildProcessStatus.WaitingForProcessToExit; this.ChildProcessIds.Add(childProcess.Id); // Dispose the local copy of the client handle pipeParentToChild.DisposeLocalCopyOfClientHandle(); pipeChildToParent.DisposeLocalCopyOfClientHandle(); // Wait for the child process to finish bool wasChildTerminatedByParent = false; MemoryStream outputStream = new MemoryStream(); using (cancellationToken.Register(() => { this.CancelChildProcess(childProcess, pipeParentToChild, ref wasChildTerminatedByParent); })) { // Read the child's output // We do not use the cancellation token here - we want to wait for the child to gracefully cancel await pipeChildToParent.CopyToAsync(outputStream, 2048, default(CancellationToken)); // Ensure the child existed childProcess.WaitForExit(); } this.CurrentStatus = RunChildProcessStatus.Finalizing; sw.Stop(); this.tracer.TraceInformation($"Process {exePath} completed, duration {sw.ElapsedMilliseconds / 1000}s, exit code {childProcess.ExitCode}"); // If the child process was terminated by the parent, throw appropriate exception if (wasChildTerminatedByParent) { throw new ChildProcessTerminatedByParentException(); } // If the child process has exited with an error code, throw appropriate exception if (childProcess.ExitCode != 0) { // This read ignores the cancellation token - if there was a cancellation, the process output will contain the appropriate exception outputStream.Seek(0, SeekOrigin.Begin); string processOutput = await this.ReadFromStream <string>(outputStream, default(CancellationToken)); throw new ChildProcessFailedException(childProcess.ExitCode, processOutput); } // Read the process result from the stream outputStream.Seek(0, SeekOrigin.Begin); TOutput processResult = await this.ReadFromStream <TOutput>(outputStream, cancellationToken); // Return process result this.CurrentStatus = RunChildProcessStatus.Completed; return(processResult); } } } } catch (Exception) { this.CurrentStatus = cancellationToken.IsCancellationRequested ? RunChildProcessStatus.Canceled : RunChildProcessStatus.Failed; throw; } finally { FileSystemExtensions.TryDeleteFolder(tempFolder, this.tracer); FileSystemExtensions.CleanupTempFolders(TempSubFolderName, tracer: this.tracer); } }
public void CreateBootStick(Logger logger) { var tempDirectory = FileSystemExtensions.MakeDirectoryUnique(Path.Combine(Path.GetTempPath(), "GodlikeStick")); logger.Status("Create temp directory"); tempDirectory.Create(); try { var targetDirectory = new DirectoryInfo(Path.Combine(_drive.RootDirectory.FullName, DriveDirectory)); if (!targetDirectory.Exists) { logger.Status($"Create /{DriveDirectory} directory on drive"); targetDirectory.Create(); } if (!File.Exists(Path.Combine(targetDirectory.FullName, "libcom32.c32"))) { InstallSysLinux(_drive, tempDirectory, logger); } logger.Status("Write syslinux config"); var sysLinuxFile = new FileInfo(Path.Combine(targetDirectory.FullName, "syslinux.cfg")); if (sysLinuxFile.Exists) { SysLinuxConfigFile = SysLinuxConfigFile.OpenFile(sysLinuxFile.FullName, _sysLinuxAppearance); } else { SysLinuxConfigFile = SysLinuxConfigFile.Create(sysLinuxFile.FullName, _sysLinuxAppearance); } logger.Status("Copy background.png"); var backgroundFilePath = Path.Combine(targetDirectory.FullName, "background.png"); if (!string.IsNullOrEmpty(_sysLinuxAppearance.ScreenBackground) && File.Exists(_sysLinuxAppearance.ScreenBackground)) { File.Copy(_sysLinuxAppearance.ScreenBackground, backgroundFilePath); } else if (!File.Exists(backgroundFilePath)) { //only copy if the file does not exist because the user could have already installed syslinux with a different background image WpfUtilities.WriteResourceToFile( new Uri("pack://application:,,,/Resources/SysLinuxFiles/background.png"), backgroundFilePath); } var randomFiles = new[] { "chain.c32", "libcom32.c32", "libutil.c32", "memdisk", "menu.c32", "vesamenu.c32", "grub.exe" }; foreach (var randomFile in randomFiles) { var resource = Application.GetResourceStream( new Uri($"pack://application:,,,/Resources/SysLinuxFiles/{randomFile}")); if (resource == null) { throw new FileNotFoundException(); } var targetFile = Path.Combine(targetDirectory.FullName, randomFile); if (File.Exists(targetFile)) { byte[] resourceHash; byte[] fileHash; using (var md5 = new MD5CryptoServiceProvider()) { resourceHash = md5.ComputeHash(resource.Stream); using (var fs = new FileStream(targetFile, FileMode.Open, FileAccess.Read)) fileHash = md5.ComputeHash(fs); } if (resourceHash.SequenceEqual(fileHash)) { logger.Status($"{randomFile} already exists"); continue; } } logger.Status($"Write \"{Path.Combine(targetDirectory.FullName, randomFile)}\""); WpfUtilities.WriteResourceToFile( new Uri($"pack://application:,,,/Resources/SysLinuxFiles/{randomFile}"), Path.Combine(targetDirectory.FullName, randomFile)); } } finally { logger.Status("Delete temp directory"); tempDirectory.Delete(true); } }
/// <summary> /// Raises the <see cref="Application.Startup" /> event. /// </summary> /// <param name="e">A <see cref="StartupEventArgs" /> that contains the event data.</param> protected override void OnStartup(StartupEventArgs e) { // Cleanup previous temp folders (that are at least 2 days old), and create a new temp folder FileSystemExtensions.CleanupTempFolders(TempSubFolderName, 48); tempFolder = FileSystemExtensions.CreateTempFolder(TempSubFolderName); NotificationService notificationService = new NotificationService(); ITracer consoleTracer = new ConsoleTracer(string.Empty); var smartDetectorLoader = new SmartDetectorLoader(tempFolder, consoleTracer); // *Temporary*: if package file path wasn't accepted, raise file selection window to allow package file selection. // This option should be removed before launching version for customers (bug for tracking: 1177247) string smartDetectorPackagePath = e.Args.Length != 1 ? GetSmartDetectorPackagePath() : Diagnostics.EnsureStringNotNullOrWhiteSpace(() => e.Args[0]); SmartDetectorPackage smartDetectorPackage; using (var fileStream = new FileStream(smartDetectorPackagePath, FileMode.Open)) { smartDetectorPackage = SmartDetectorPackage.CreateFromStream(fileStream); } try { SmartDetectorManifest smartDetectorManifest = smartDetectorPackage.Manifest; ISmartDetector detector = smartDetectorLoader.LoadSmartDetector(smartDetectorPackage); // Authenticate the user to Active Directory IAuthenticationServices authenticationServices = new AuthenticationServices(); authenticationServices.AuthenticateUserAsync().Wait(); ICredentialsFactory credentialsFactory = new ActiveDirectoryCredentialsFactory(authenticationServices); IHttpClientWrapper httpClientWrapper = new HttpClientWrapper(); IExtendedAzureResourceManagerClient azureResourceManagerClient = new ExtendedAzureResourceManagerClient(httpClientWrapper, credentialsFactory, consoleTracer); // Create analysis service factory IInternalAnalysisServicesFactory analysisServicesFactory = new AnalysisServicesFactory(consoleTracer, httpClientWrapper, credentialsFactory, azureResourceManagerClient); // Create state repository factory IStateRepositoryFactory stateRepositoryFactory = new EmulationStateRepositoryFactory(); // Load user settings var userSettings = UserSettings.LoadUserSettings(); // Create the detector runner IPageableLogArchive logArchive = new PageableLogArchive(smartDetectorManifest.Name); IEmulationSmartDetectorRunner smartDetectorRunner = new SmartDetectorRunner( detector, analysisServicesFactory, smartDetectorManifest, stateRepositoryFactory, azureResourceManagerClient, logArchive); // Create a Unity container with all the required models and view models registrations Container = new UnityContainer(); Container .RegisterInstance(notificationService) .RegisterInstance <ITracer>(consoleTracer) .RegisterInstance(new AlertsRepository()) .RegisterInstance(authenticationServices) .RegisterInstance(azureResourceManagerClient) .RegisterInstance(detector) .RegisterInstance(smartDetectorManifest) .RegisterInstance(analysisServicesFactory) .RegisterInstance(logArchive) .RegisterInstance(smartDetectorRunner) .RegisterInstance(stateRepositoryFactory) .RegisterInstance(userSettings); } catch (Exception exception) { var message = $"{exception.Message}. {Environment.NewLine}{exception.InnerException?.Message}"; MessageBox.Show(message); System.Diagnostics.Trace.WriteLine(message); Environment.Exit(1); } }
private async Task <bool> DoYourStuff(ProcessViewModel processView) { await Task.Delay(500); //wait for the view to build up and subscribe to the logger event processView.Logger.Status("Check if drive is still plugged in..."); if (!UsbStickSettings.Drive.IsReady) { processView.Logger.Error("Drive is not ready. Please plug it in again"); return(false); } var stopwatch = Stopwatch.StartNew(); //progress: //10 % = install syslinux etc. //60 % = install systems //30 % = download & copy applications processView.Logger.Success("Drive plugged in"); if (UsbStickSettings.FormatDrive) { if (MessageBoxEx.Show(Application.Current.MainWindow, $"Warning: You selected the formatting option. Formatting will erease ALL data on the drive {UsbStickSettings.Drive.Name}. If you want to continue, press ok.", $"Format drive {UsbStickSettings.Drive.Name}", MessageBoxButton.OKCancel, MessageBoxImage.Warning, MessageBoxResult.Cancel) != MessageBoxResult.OK) { return(false); } processView.Message = "Format USB stick to FAT32"; processView.Logger.Status($"Formatting drive {UsbStickSettings.Drive.Name} with FAT32"); var driveLetter = UsbStickSettings.Drive.Name.Substring(0, 2); FormatResponse formatResponse; if (User.IsAdministrator) { formatResponse = await Task.Run( () => DriveUtilities.FormatDrive(driveLetter, "FAT32", true, 8192, App.DriveLabel, false)); } else { var process = new Process { StartInfo = { FileName = Assembly.GetExecutingAssembly().Location, Arguments = $"/format {driveLetter}", Verb = "runas" } }; if (!process.Start()) { processView.Logger.Error( "Was not able to restart application with administrator privileges to format the drive"); return(false); } await Task.Run(() => process.WaitForExit()); formatResponse = (FormatResponse)process.ExitCode; } if (formatResponse != FormatResponse.Success) { processView.Logger.Error("Formatting drive failed: " + formatResponse); return(false); } processView.Logger.Success("Successfully formatted drive"); } processView.Message = "Creating bootable stick"; if (UsbStickSettings.Drive.VolumeLabel != App.DriveLabel) { processView.Logger.Status("Change volume label to " + App.DriveLabel); UsbStickSettings.Drive.VolumeLabel = App.DriveLabel; } if (UsbStickSettings.Drive.DriveFormat != "FAT32") { processView.Logger.Warn( $"The drive {UsbStickSettings.Drive.RootDirectory.FullName} is formatted with {UsbStickSettings.Drive.DriveFormat} which may be incompatible with SysLinux (it is recommended to format it as FAT32)"); } var bootStickCreator = new BootStickCreator(UsbStickSettings.Drive, UsbStickSettings.SysLinuxAppearance); processView.CurrentProgress = 0.05; await Task.Run(() => bootStickCreator.CreateBootStick(processView.Logger)); processView.CurrentProgress = 0.1; var installSystemPercentage = UsbStickSettings.ApplicationInfo.Any(x => x.Add) ? 0.6 : 0.9; var systemSizes = UsbStickSettings.Systems.ToDictionary(x => x, y => new FileInfo(y.Filename).Length); long processedSize = 0; var totalSize = systemSizes.Sum(x => x.Value); bool?skipAllExistingSystems = null; for (int i = 0; i < UsbStickSettings.Systems.Count; i++) { var systemInfo = UsbStickSettings.Systems[i]; var progressReporter = new SystemProgressReporter(); progressReporter.ProgressChanged += (sender, d) => processView.CurrentProgress = 0.1 + (processedSize + systemSizes[systemInfo] * d) / totalSize * installSystemPercentage; progressReporter.MessageChanged += (sender, s) => { processView.Message = $"Install {systemInfo.Name} ({i + 1} / {UsbStickSettings.Systems.Count}): " + s; processView.Logger.Status(s); }; if (bootStickCreator.SysLinuxConfigFile.ContainsSystem(systemInfo)) { if (skipAllExistingSystems == true) { continue; } if (skipAllExistingSystems == null) { var directory = bootStickCreator.SysLinuxConfigFile.GetSystemDirectory(systemInfo); var newFileName = Path.GetFileNameWithoutExtension(systemInfo.Filename); if (directory == newFileName) { var applyForAll = false; if (MessageBoxChk.Show(Application.Current.MainWindow, $"The system \"{systemInfo.Name}\" already exists on the drive. Should it be overwritten (else skip)?", systemInfo.Name + " already exists", "Apply for all", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No, ref applyForAll) != MessageBoxResult.Yes) { if (applyForAll) { skipAllExistingSystems = true; } continue; } if (applyForAll) { skipAllExistingSystems = false; } } } await Task.Run(() => bootStickCreator.RemoveSystem(systemInfo)); } processView.Message = $"Install {systemInfo.Name} ({i + 1} / {UsbStickSettings.Systems.Count}): Add to config"; await Task.Run( () => bootStickCreator.AddSystemToBootStick(systemInfo, processView.Logger, progressReporter)); processView.Logger.Success("Added " + systemInfo.Name); processedSize += systemSizes[systemInfo]; } processView.CurrentProgress = 0.7; processView.Logger.Success("All systems installed"); var applicationsToInstall = UsbStickSettings.ApplicationInfo.Where(x => x.Add).ToList(); for (int i = 0; i < applicationsToInstall.Count; i++) { var application = applicationsToInstall[i]; processView.Message = $"Install {application.Name} ({i + 1} / {applicationsToInstall.Count}): Download"; var downloadUrl = await Task.Run(() => application.DownloadUrl.Value); processView.Logger.Status($"Download {downloadUrl}"); var tempFile = FileSystemExtensions.GetFreeTempFileName(application.Extension ?? new FileInfo(new Uri(downloadUrl).AbsolutePath).Extension.Remove(0, 1)); //remove the dot of the extension var webClient = new WebClient(); webClient.DownloadProgressChanged += (sender, args) => processView.CurrentProgress = 0.1 + 0.6 + (0.3 / applicationsToInstall.Count * i + 0.3 / applicationsToInstall.Count * (args.ProgressPercentage / 100d)); await webClient.DownloadFileTaskAsync(downloadUrl, tempFile); processView.Logger.Success("Application downloaded successfully"); processView.Logger.Status("Extract zip archive"); processView.Message = $"Install {application.Name} ({i + 1} / {applicationsToInstall.Count}): Extract"; var targetDirectory = new DirectoryInfo(Path.Combine(UsbStickSettings.Drive.RootDirectory.FullName, "Tools", EnumUtilities.GetDescription(application.ApplicationCategory), application.Name)); if (targetDirectory.Exists) { processView.Logger.Warn("Old application found, removing..."); FileSystemExtensions.DeleteDirectory(targetDirectory.FullName); } targetDirectory.Create(); using (var file = new SevenZipExtractor(tempFile)) using (var autoResetEvent = new AutoResetEvent(false)) { EventHandler <EventArgs> setHandler = (sender, args) => autoResetEvent.Set(); file.ExtractionFinished += setHandler; file.BeginExtractArchive(targetDirectory.FullName); await Task.Run(() => autoResetEvent.WaitOne()); file.ExtractionFinished -= setHandler; } File.Delete(tempFile); var entries = targetDirectory.GetFileSystemInfos(); if (entries.Length == 1 && (entries[0].Attributes & FileAttributes.Directory) == FileAttributes.Directory) { var directory = new DirectoryInfo(entries[0].FullName); await Task.Run(() => { directory.MoveTo(Path.Combine(directory.Parent.FullName, Guid.NewGuid().ToString("D"))); //in case that there's a directory with the same name foreach (var fileInfo in directory.GetFiles()) { fileInfo.MoveTo(Path.Combine(targetDirectory.FullName, fileInfo.Name)); } foreach (var directoryInfo in directory.GetDirectories()) { directoryInfo.MoveTo(Path.Combine(targetDirectory.FullName, directoryInfo.Name)); } directory.Delete(); }); } processView.Logger.Success("Application successfully installed"); } processView.CurrentProgress = 1; processView.Logger.Success($"Finished in {stopwatch.Elapsed.ToString("g")}"); return(true); }
private void hasFile(string directory, string fileName, ContentType contentType) { MockFor <IFileSystem>().Stub(x => FileSystemExtensions.FileExists(x, directory, contentType.ToString(), fileName)).Return(true); }
public void Upload_Null() { FileSystemExtensions.Upload(null, "source_upload.txt", "dest_upload.txt"); }
public void RestoreBackup(IComponent component) { if (!_backupLookup.ContainsKey(component)) { return; } var backupFile = _backupLookup[component]; var componentFile = component.GetFilePath(); var remove = true; try { if (string.IsNullOrEmpty(backupFile)) { if (!File.Exists(componentFile)) { return; } var success = FileSystemExtensions.DeleteFileWithRetry(componentFile, out _); if (success) { return; } remove = false; throw new IOException("Unable to restore the backup. Please restart your computer!"); } else { if (!File.Exists(backupFile)) { return; } if (File.Exists(componentFile)) { var backupHash = UpdaterUtilities.GetFileHash(backupFile !, HashType.Sha256); var fileHash = UpdaterUtilities.GetFileHash(backupFile !, HashType.Sha256); if (backupHash.SequenceEqual(fileHash)) { remove = false; return; } } var success = FileSystemExtensions.MoveFile(backupFile, component.GetFilePath(), true); if (!success) { remove = false; throw new IOException($"Unable to restore the backup file '{backupFile}'. Please restart your computer!"); } if (UpdateConfiguration.Instance.DownloadOnlyMode) { ComponentDownloadPathStorage.Instance.Remove(component); } try { FileSystemExtensions.DeleteFileWithRetry(backupFile !, out _); } catch { remove = false; } } } finally { if (remove) { lock (_syncObject) _backupLookup.Remove(component); } } }
protected bool LoadConfig() => FileSystemExtensions.LoadConfig(ConfigFile, this);