public static Task CreateDesktopPwsIconCustomRepo(string name, string description, Uri target, IAbsoluteFilePath icon = null) => CreateShortcutAsync(new ShortcutInfo(GetDesktop(), name, Common.Paths.EntryLocation) { Arguments = target.ToString(), Description = description, Icon = icon });
public VariablePathResolvingStatus TryResolve(IEnumerable<KeyValuePair<string, string>> variables, out IAbsoluteFilePath resolvedPath, out IReadOnlyList<string> unresolvedVariables) { Argument.IsNotNull(nameof(variables), variables); string path; if (!TryResolve(variables, out path, out unresolvedVariables)) { resolvedPath = null; return VariablePathResolvingStatus.UnresolvedVariable; } if (!path.IsValidAbsoluteFilePath()) { resolvedPath = null; return VariablePathResolvingStatus.CannotConvertToAbsolutePath; } resolvedPath = path.ToAbsoluteFilePath(); return VariablePathResolvingStatus.Success; }
public static IAbsoluteFilePath GetUpdateExe(IAbsoluteFilePath location) { var parent = location.ParentDirectoryPath; var updateExe = parent.HasParentDirectory ? parent.ParentDirectoryPath.GetChildFileWithName("Update.exe") : null; return updateExe; }
public static IEnumerable<string> GenerateCommandLineExecution(IAbsoluteFilePath location, string executable, params string[] desiredParams) { var updateExe = GetUpdateExe(location); return (updateExe != null) && updateExe.Exists ? new[] {updateExe.ToString()}.Concat(Restarter.BuildUpdateExeArguments(executable, desiredParams)) : new[] {location.ToString()}.Concat(desiredParams); }
async Task<bool> TryCheckUac(IAbsoluteDirectoryPath mp, IAbsoluteFilePath path) { Exception ex; try { mp.MakeSurePathExists(); if (path.Exists) File.Delete(path.ToString()); using (File.CreateText(path.ToString())) {} File.Delete(path.ToString()); return false; } catch (UnauthorizedAccessException e) { ex = e; } catch (Exception e) { this.Logger().FormattedWarnException(e); return false; } var report = await UserErrorHandler.HandleUserError(new UserErrorModel("Restart the application elevated?", $"The application failed to write to the path, probably indicating permission issues\nWould you like to restart the application Elevated?\n\n {mp}", RecoveryCommands.YesNoCommands, null, ex)) == RecoveryOptionResultModel.RetryOperation; if (!report) return false; RestartWithUacInclEnvironmentCommandLine(); return true; }
void ProcessDll(IAbsoluteFilePath dll, bool force = true) { var fileName = dll.FileName.ToLower(); var ts332Path = _localMachineInfo.TS3_32_Path; var ts364Path = _localMachineInfo.TS3_64_Path; switch (fileName) { case "task_force_radio_win32.dll": { InstallTaskForceRadio(dll, ts332Path, force); break; } case "task_force_radio_win64.dll": { InstallTaskForceRadio(dll, ts364Path, force); break; } case "dsound.dll": { var path = _game.InstalledState.Directory; if (path != null) InstallDll(dll, path, null, force); break; } default: { if (ts332Dlls.Contains(fileName)) InstallTs3Plugin(dll, ts332Path, force); else if (ts364Dlls.Contains(fileName)) InstallTs3Plugin(dll, ts364Path, force); break; } } }
public static void SafeSave(Action<IAbsoluteFilePath> saveCode, IAbsoluteFilePath filePath) { var newFileName = (filePath + GenericTools.TmpExtension).ToAbsoluteFilePath(); saveCode(newFileName); FileUtil.Ops.Copy(newFileName, filePath); FileUtil.Ops.DeleteFile(newFileName); }
public virtual string Gzip(IAbsoluteFilePath file, IAbsoluteFilePath dest = null, bool preserveFileNameAndModificationTime = true, ITProgress status = null) { Contract.Requires<ArgumentNullException>(file != null); Contract.Requires<ArgumentException>(file.Exists); var defDest = (file + ".gz").ToAbsoluteFilePath(); if (dest == null) dest = defDest; var cmd = $"-f --best --rsyncable --keep \"{file}\""; if (!preserveFileNameAndModificationTime) cmd = "-n " + cmd; dest.RemoveReadonlyWhenExists(); var startInfo = new ProcessStartInfoBuilder(Common.Paths.ToolPath.GetChildFileWithName("gzip.exe"), cmd) { WorkingDirectory = file.ParentDirectoryPath }.Build(); var srcSize = file.FileInfo.Length; ProcessExitResultWithOutput ret; var predictedSize = srcSize*DefaultPredictedCompressionRatio; using (StatusProcessor.Conditional(defDest, status, (long) predictedSize)) ret = ProcessManager.LaunchAndGrabTool(startInfo, "Gzip pack"); if (Path.GetFullPath(dest.ToString()) != Path.GetFullPath(defDest.ToString())) FileUtil.Ops.MoveWithRetry(defDest, dest); return ret.StandardOutput + ret.StandardError; }
async Task TryDownloadAsync(TransferSpec spec, IWebClient webClient, IAbsoluteFilePath tmpFile) { try { tmpFile.RemoveReadonlyWhenExists(); if (!string.IsNullOrWhiteSpace(spec.Uri.UserInfo)) webClient.SetAuthInfo(spec.Uri); using (webClient.HandleCancellationToken(spec)) await webClient.DownloadFileTaskAsync(spec.Uri, tmpFile.ToString()).ConfigureAwait(false); VerifyIfNeeded(spec, tmpFile); _fileOps.Move(tmpFile, spec.LocalFile); } catch (OperationCanceledException e) { _fileOps.DeleteIfExists(tmpFile.ToString()); throw CreateTimeoutException(spec, e); } catch (WebException ex) { _fileOps.DeleteIfExists(tmpFile.ToString()); var cancelledEx = ex.InnerException as OperationCanceledException; if (cancelledEx != null) throw CreateTimeoutException(spec, cancelledEx); if (ex.Status == WebExceptionStatus.RequestCanceled) throw CreateTimeoutException(spec, ex); var response = ex.Response as HttpWebResponse; if (response == null) throw GenerateDownloadException(spec, ex); switch (response.StatusCode) { case HttpStatusCode.NotFound: throw new RequestFailedException("Received a 404: NotFound response", ex); case HttpStatusCode.Forbidden: throw new RequestFailedException("Received a 403: Forbidden response", ex); case HttpStatusCode.Unauthorized: throw new RequestFailedException("Received a 401: Unauthorized response", ex); } throw GenerateDownloadException(spec, ex); } }
public Package Import(Repository repo, IAbsoluteDirectoryPath workDir, IAbsoluteFilePath packageFilePath) { var metaData = Package.Load(packageFilePath); var package = new Package(workDir, metaData, repo); package.Commit(metaData.GetVersionInfo()); return package; }
public static Task CreateDesktopGameBat(string name, string description, string arguments, Game game, IAbsoluteFilePath icon = null) { return Tools.FileUtil.CreateBatFile(GetDesktop(), name, GenerateBatContent(game.InstalledState.LaunchExecutable, game.InstalledState.Directory, arguments)); // TODO: DEscription etc? Maybe just create a nice shortcut to this thing incl icon? }
public virtual string Gzip(IAbsoluteFilePath file, IAbsoluteFilePath dest = null, bool preserveFileNameAndModificationTime = false) { Contract.Requires<ArgumentNullException>(file != null); Contract.Requires<ArgumentException>(file.Exists); var defDest = (file + ".gz").ToAbsoluteFilePath(); if (dest == null) dest = defDest; var cmd = String.Format("-f --best --rsyncable --keep \"{0}\"", file); if (!preserveFileNameAndModificationTime) cmd = "-n " + cmd; dest.RemoveReadonlyWhenExists(); var startInfo = new ProcessStartInfoBuilder(Common.Paths.ToolPath.GetChildFileWithName("gzip.exe"), cmd) { WorkingDirectory = file.ParentDirectoryPath.ToString() }.Build(); var ret = ProcessManager.LaunchAndGrabTool(startInfo, "Gzip pack"); if (Path.GetFullPath(dest.ToString()) != Path.GetFullPath(defDest.ToString())) FileUtil.Ops.MoveWithRetry(defDest, dest); return ret.StandardOutput + ret.StandardError; }
public virtual void UnpackFile(IAbsoluteFilePath srcFile, IAbsoluteFilePath dstFile, IStatus status = null) { var dstPath = dstFile.ParentDirectoryPath; dstPath.MakeSurePathExists(); dstFile.RemoveReadonlyWhenExists(); Tools.Compression.Unpack(srcFile, dstPath, true, progress: status); }
public static Task CreateDesktopPwsIcon(string name, string description, string arguments, IAbsoluteFilePath icon = null) => CreateShortcutAsync(new ShortcutInfo(GetDesktop(), name, Common.Paths.EntryLocation) { Arguments = arguments, Icon = icon, Description = description });
public MultiMirrorFileDownloadSpec(string remoteFile, IAbsoluteFilePath localFile) { Contract.Requires<ArgumentNullException>(remoteFile != null); Contract.Requires<ArgumentNullException>(localFile != null); Contract.Requires<ArgumentException>(!remoteFile.Contains(@"\")); RemoteFile = remoteFile; LocalFile = localFile; }
void CaseChangeMove(IAbsoluteFilePath source, IAbsoluteFilePath destination) { var tmpFile = source + GenericTools.TmpExtension; DeleteIfExists(tmpFile); File.Move(source.ToString(), tmpFile); File.Move(tmpFile, destination.ToString()); }
public static PackageMetaData TryLoad(IAbsoluteFilePath metaDataPath) { try { return(Repository.Load <PackageMetaDataDto, PackageMetaData>(metaDataPath)); } catch (Exception) { return(null); } }
void SignFolderNotRecursively(IAbsoluteDirectoryPath folder, IAbsoluteFilePath privateFile, bool repackOnFailure = false) { foreach (var f in Directory.EnumerateFiles(folder.ToString(), "*.pbo")) { SignFile(f.ToAbsoluteFilePath(), privateFile, repackOnFailure); } }
public static Task CreateDesktopGameIcon(string name, string description, string arguments, Game game, IAbsoluteFilePath icon = null) => CreateShortcutAsync(new ShortcutInfo(GetDesktop(), name, game.InstalledState.LaunchExecutable) { WorkingDirectory = game.InstalledState.Directory, Arguments = arguments, Description = description, Icon = icon });
public YomaConfig(IAbsoluteFilePath inputAddonsFile, IAbsoluteFilePath inputModsFile, IAbsoluteFilePath inputServerFile = null) : this( XDocument.Load(inputAddonsFile.ToString()), XDocument.Load(inputModsFile.ToString()), inputServerFile == null ? null : XDocument.Load(inputServerFile.ToString())) { Contract.Requires<ArgumentOutOfRangeException>(inputAddonsFile != null); Contract.Requires<ArgumentOutOfRangeException>(inputModsFile != null); }
static string GenerateBatContent(IAbsoluteFilePath target, IAbsoluteDirectoryPath workDir, string pars) => String.Format(@" @echo off echo Starting: {0} echo From: {1} echo With params: {2} cd /D ""{1}"" ""{0}"" {2}", target, workDir, pars);
bool ConfirmFileValidity(IAbsoluteFilePath file, string md5) { if (!file.Exists) return false; var fileMd5 = Tools.HashEncryption.MD5FileHash(file); return fileMd5 == md5; }
public HandleKeyParams(IAbsoluteDirectoryPath keyPath, string prefix, bool copyKey, IAbsoluteDirectoryPath directory, IAbsoluteFilePath key) { KeyPath = keyPath; Prefix = prefix; CopyKey = copyKey; Directory = directory; Key = key; }
protected TransferSpec(Uri uri, IAbsoluteFilePath localFile, ITransferProgress progress) { Contract.Requires<ArgumentNullException>(uri != null); Contract.Requires<ArgumentNullException>(localFile != null); Uri = uri; LocalFile = localFile; Progress = progress ?? new TransferProgress(); }
public static void ConvertLegacy2(IAbsoluteFilePath settingsFile) { var data = File.ReadAllText(settingsFile.ToString()); var newData = ProcessNamespaces2(data); File.WriteAllText(settingsFile.ToString(), newData); }
public VariablePathResolvingStatus TryResolve(IEnumerable<KeyValuePair<string, string>> variables, out IAbsoluteFilePath resolvedPath) { Argument.IsNotNull(nameof(variables), variables); IReadOnlyList<string> unresolvedVariables; return TryResolve(variables, out resolvedPath, out unresolvedVariables); }
public GameInstalledState(IAbsoluteFilePath executable, IAbsoluteDirectoryPath directory, Version version = null) { Contract.Requires<ArgumentNullException>(executable != null); Contract.Requires<ArgumentNullException>(directory != null); Executable = executable; Directory = directory; Version = version; }
static void SetFileACL(IAbsoluteFilePath location, string user, FileSystemRights rights) { var fi = location.FileInfo; if (ModifyACL(user, rights, fi.GetAccessControl())) { fi.SetAccessControl(fi.GetAccessControl()); } }
public SignManyParams(IPath[] items, IAbsoluteFilePath privateFile, IAbsoluteDirectoryPath keyPath, string prefix, bool copyKey) { Items = items; PrivateFile = privateFile; KeyPath = keyPath; Prefix = prefix; CopyKey = copyKey; }
public ProcessDirectoryOrFileParams(IAbsoluteDirectoryPath keyPath, string prefix, bool copyKey, string arg, IAbsoluteFilePath key) { KeyPath = keyPath; Prefix = prefix; CopyKey = copyKey; Arg = arg; Key = key; }
public void Test_FileDontExist() { Assert.Throws(typeof(FileNotFoundException), delegate { DirForTest.Delete(); string dirForTestWithExecutingAssemblyFilePath = DirForTest.ExecutingAssemblyFilePathInDirForTest; IAbsoluteFilePath absoluteFilePath = dirForTestWithExecutingAssemblyFilePath.ToAbsoluteFilePath(); FileInfo fileInfo = absoluteFilePath.FileInfo; }); }
public void PackTar(IAbsoluteDirectoryPath directory, IAbsoluteFilePath outputFile) { using (var tarStream = File.OpenWrite(outputFile.ToString())) using (var af = WriterFactory.Open(tarStream, ArchiveType.Tar, CompressionType.None)) { foreach (var f in directory.DirectoryInfo.EnumerateFiles("*", SearchOption.AllDirectories)) af.Write(f.FullName.Replace(directory.ParentDirectoryPath + @"\", ""), f.FullName); // This ommits the root folder ('userconfig') //af.WriteAll(directory.ToString(), "*", SearchOption.AllDirectories); } }
private static Task HandleCopyFileInternal(IAbsoluteFilePath file, IAbsoluteFilePath dst, ITProgress status) { if (Common.Flags.Verbose) { MainLog.Logger.Info($"Copying {file} to {dst}"); } dst.MakeSureParentPathExists(); return(file.CopyAsync(dst, status: status)); }
public virtual void UnpackUpdater(IAbsoluteFilePath sourceFile, IAbsoluteDirectoryPath outputFolder, bool overwrite = false, bool fullPath = true) { Contract.Requires<ArgumentNullException>(sourceFile != null); Contract.Requires<ArgumentNullException>(outputFolder != null); Generic.RunUpdater(UpdaterCommands.Unpack, sourceFile.ToString(), outputFolder.ToString(), overwrite ? "--overwrite" : null, fullPath.ToString()); }
internal StatusProcessor(IAbsoluteFilePath dest, ITProgress status, long predictedSize) { _dest = dest; _status = status; _predictedSize = predictedSize; _startTime = DateTime.UtcNow; _timer = new TimerWithElapsedCancellationOnExceptionOnly(TimeSpan.FromMilliseconds(250), CalculateProgressAndSpeed); }
public virtual string GzipAuto(IAbsoluteFilePath inputFile, IAbsoluteFilePath outputFile = null, bool preserveFileNameAndModificationTime = true, ITProgress status = null) { if (inputFile.ToString().EndsWith(".gz", StringComparison.OrdinalIgnoreCase)) { return(GzipStdOut(inputFile, outputFile, preserveFileNameAndModificationTime, status)); } return(Gzip(inputFile, outputFile, preserveFileNameAndModificationTime, status)); }
public Package Import(Repository repo, IAbsoluteDirectoryPath workDir, IAbsoluteFilePath packageFilePath) { var metaData = Package.Load(packageFilePath); var package = new Package(workDir, metaData, repo); package.Commit(metaData.GetVersionInfo()); return(package); }
public static Task GenerateDiagnosticZip(IAbsoluteFilePath path) { var d = GetLogFilesDictionary(Common.Paths.LocalDataRootPath); return Task.Run( () => { var items = d.Where(x => !x.Value.EndsWith("cef.log", StringComparison.CurrentCultureIgnoreCase)); Tools.CompressionUtil.PackFiles(items, path); }); }
void RealMove(IAbsoluteFilePath source, IAbsoluteFilePath destination, bool overwrite) { if (overwrite && destination.Exists && !FileUtil.ComparePathsOsCaseSensitive(source, destination)) { DeleteIfExists(destination.ToString()); } File.Move(source.ToString(), destination.ToString()); }
public static IAbsoluteFilePath GetUpdateExe(IAbsoluteFilePath location) { var parent = location.ParentDirectoryPath; var updateExe = parent.HasParentDirectory ? parent.ParentDirectoryPath.GetChildFileWithName("Update.exe") : null; return(updateExe); }
public bool RegisterExisting(Uri url, IAbsoluteFilePath path) { if (_tasks.ContainsKey(url)) { _tasks[url].SetResult(path); _tasks.Remove(url); return true; } _cache[url] = path; return false; }
public void SignFolder(IAbsoluteDirectoryPath folder, IAbsoluteFilePath privateFile, bool repackOnFailure = false) { SignFolderNotRecursively(folder, privateFile, repackOnFailure); foreach (var d in addonFolders .Select(folder.GetChildDirectoryWithName) .Where(x => x.Exists)) SignFolderNotRecursively(d, privateFile, repackOnFailure); }
protected virtual void VerifyIfNeeded(TransferSpec spec, IAbsoluteFilePath localFile) { if ((spec.Verification == null) || spec.Verification(localFile)) { return; } Tools.FileUtil.Ops.DeleteFile(localFile); throw new VerificationError(localFile.ToString()); }
public Task CreateTextAsync(IAbsoluteFilePath filePath, params string[] text) => AddIORetryDialog(async() => { using (var fs = File.CreateText(filePath.ToString())) { foreach (var t in text) { await fs.WriteAsync(t).ConfigureAwait(false); } } }, filePath.ToString());
private static string TryReadHeader(IAbsoluteFilePath sourceFile) { try { return(ReadHeader(sourceFile)); } catch (Exception ex) { MainLog.Logger.FormattedWarnException(ex, "Could not read header from corrupt gzip file"); return("$W6$: Could not read file"); } }
public static IEnumerable <string> GenerateCommandLineExecution(IAbsoluteFilePath location, string executable, params string[] desiredParams) { var updateExe = GetUpdateExe(location); return(updateExe != null && updateExe.Exists ? new[] { updateExe.ToString() }.Concat(Restarter.BuildUpdateExeArguments(executable, desiredParams)) : new[] { location.ToString() }.Concat(desiredParams)); }
protected override void VerifyIfNeeded(TransferSpec spec, IAbsoluteFilePath localFile) { // To make sure we dont fall into zsync silent failure trap.. if (!localFile.Exists) { throw new ZsyncSoftException("Download failure, file doesn't exist"); } base.VerifyIfNeeded(spec, localFile); }
static void TryUserconfigUnpackOverwrite(IAbsoluteFilePath path, IAbsoluteDirectoryPath gamePath) { try { Tools.Compression.UnpackRetryUpdater(path, gamePath, true); } catch (Win32Exception ex) { if (ex.NativeErrorCode != Win32ErrorCodes.ERROR_CANCELLED_ELEVATION) throw; throw ex.HandleUserCancelled(); } }
void TryProcessDll(bool force, IAbsoluteFilePath dll) { try { ProcessDll(dll, force); } catch (PathDoesntExistException e) { this.Logger().FormattedWarnException(e, "Path: " + e.Path); } catch (Win32Exception e) { this.Logger().FormattedWarnException(e); } }
static async Task CopyAsyncInternal(IAbsoluteFilePath source, IAbsoluteFilePath destination, bool overwrite = true, ITProgress status = null) { using ( var sourceStream = File.Open(source.ToString(), FileMode.Open, FileAccess.Read, FileShare.Read)) using (var destinationStream = File.Create(destination.ToString())) using (new StatusProcessor(destination, status, source.FileInfo.Length)) await sourceStream.CopyToAsync(destinationStream).ConfigureAwait(false); CopyTimestamps(source, destination); }
public LocalModFileInfo(IAbsoluteFilePath path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } Name = path.FileName; Path = path.ParentDirectoryPath; }
public async Task ImportPwsSettings(IAbsoluteFilePath filePath) { try { await ImportPwsSettingsInternal(filePath).ConfigureAwait(false); } catch (Exception ex) { throw new ValidationException( "A problem ocurred while trying to import settings from PwS. Please make sure the settings are of the latest PwS version", ex); } }
public void RepackPbo(IAbsoluteFilePath pboFile) { var unpackedPboFolder = pboFile.GetBrotherDirectoryWithName(pboFile.FileNameWithoutExtension); using (new TmpDirectory(unpackedPboFolder)) { UnpackPbo(pboFile); CreatePboPrefixFileIfNeeded(unpackedPboFolder); PackFolder(unpackedPboFolder); } }
static void BackupEntry(IAbsoluteDirectoryPath workingDirectory, IAbsoluteDirectoryPath backupPath, IAbsoluteFilePath entry) { var backupDestination = entry.GetRelativePathFrom(workingDirectory).GetAbsolutePathFrom(backupPath); DeleteDestinationIfDirectory(backupDestination); DeleteParentFilesIfExists(backupDestination, backupPath); backupDestination.MakeSureParentPathExists(); entry.Move(backupDestination); }
Version TryGetVersionFromFile(IAbsoluteFilePath exePath) { try { return(Tools.FileUtil.GetVersion(exePath)); } catch (Exception e) { this.Logger() .FormattedWarnException(e, $"failed to get app local version from {exePath}"); return(new Version()); } }
public ArchiveContent CreateFromExisting(IAbsoluteDirectoryPath destination, IAbsoluteFilePath file, IFileDownloader downloader) { var name = GetName(file.ToString()); var ac = new ArchiveContent(name, destination.ToString(), downloader); ac.ImportFromArchive(file); return(ac); }