private static async Task DownloadManifests( FileInfo?config = null, string output = ".", bool step = false, string?proxy = null) { config ??= new FileInfo("config.json"); var manifest = new Manifest(config, output); await manifest.SaveAllManifests(step? 1 : -1); manifest.SaveConfig(config); }
private async Task ImportVatCodesHandler( FileInfo input, EFormatType inputformat, FileInfo?output, EFormatType outputformat) { var fSyncFilePath = input.FullName; var fVatCodeList = File.ReadAllText(fSyncFilePath); var fVatCodes = _utilities.ReadAs <VatCode>(inputformat, fVatCodeList); if (fVatCodes is null) { return; } var fSuccessList = new List <VatCode>(); var fFailedList = new List <VatCode>(); var fCount = 1; var fTotalVATCodes = fVatCodes.Count; foreach (var fVatCode in fVatCodes) { var fResult = await _vatCodeService.CreateOrUpdate(fVatCode); if (fResult.Object == null) { fFailedList.Add(fVatCode); _logger.LogWarning($"{fCount}/{fTotalVATCodes}: Failed syncing VATCode '{fVatCode.Name}' - {fResult.ErrorMessage}"); } else { fSuccessList.Add(fResult.Object); Console.WriteLine($"{fCount}/{fTotalVATCodes} Successfully synced VATCode '{fVatCode.Name}'"); } fCount++; } Console.WriteLine($"{fSuccessList.Count}/{fTotalVATCodes} VATCodes have been successfully imported"); await _utilities.HandleOutput(outputformat, fSuccessList, output); if (output != null) { await _utilities.HandleOutputToFilePath(outputformat, fFailedList, $"{output?.Directory?.FullName}/failed_{output?.Name ?? "NO_FILE_PATH_PROVIDED"}"); await _utilities.HandleOutputToFilePath(outputformat, fSuccessList, $"{output?.Directory?.FullName}/succeed_{output?.Name ?? "NO_FILE_PATH_PROVIDED"}"); } }
public static async Task <int> Main(bool version = false, FileInfo?log = null, bool whatIf = false, string[]?command = null, string host = "localhost", int tcpPort = 1113, int httpPort = 2113, int timeout = Timeout.Infinite, int readWindow = 2000, int writeWindow = 2000, int pingWindow = 2000, bool reconnect = true, bool useTls = false, bool tlsValidateServer = false) { Log.Logger = EventStoreLoggerConfiguration.ConsoleLog; try { var logsDirectory = log?.FullName ?? Locations.DefaultTestClientLogDirectory; EventStoreLoggerConfiguration.Initialize(logsDirectory, "client"); var options = new ClientOptions { Timeout = timeout, HttpPort = httpPort, Host = host, TcpPort = tcpPort, Reconnect = reconnect, PingWindow = pingWindow, ReadWindow = readWindow, WriteWindow = writeWindow, UseTls = useTls, TlsValidateServer = tlsValidateServer, Command = command ?? Array.Empty <string>() }; var hostedService = new TestClientHostedService(options); if (whatIf) { await Console.Out.WriteLineAsync(options.ToString()); } if (version || whatIf) { await Console.Out.WriteLineAsync(VersionInfo.Text); await Console.Out.FlushAsync(); return(0); } await CreateHostBuilder(hostedService, Environment.GetCommandLineArgs()) .RunConsoleAsync(options => options.SuppressStatusMessages = true, hostedService.CancellationToken); return(await hostedService.Exited); } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly."); return(1); } finally { Log.CloseAndFlush(); } }
public static bool FindSeasEp(FileInfo?fi, out int seas, out int ep, out int maxEp, ShowConfiguration?si, IEnumerable <TVSettings.FilenameProcessorRE> rexps, out TVSettings.FilenameProcessorRE?re) { if (fi is null) { re = null; seas = -1; ep = -1; maxEp = -1; return(false); } return(FindSeasEp(fi.Directory.FullName, fi.RemoveExtension(), out seas, out ep, out maxEp, si, rexps, out re)); }
public static void ClassInit(TestContext context) { beforeLogger = TraceBase.Logger; log4netFileInfo = new FileInfo("C:/Logs/DebugTrace/Log4net.log"); nLogFileInfo = new FileInfo("C:/Logs/DebugTrace/NLog.log"); try { using (var stream = log4netFileInfo.Open(FileMode.Truncate)) {} } catch (Exception) {} try { using (var stream = nLogFileInfo.Open(FileMode.Truncate)) {} } catch (Exception) {} }
public void Setup(FileInfo?loadFrom, FileInfo cache, CommandLineArgs cla) { System.Diagnostics.Debug.Assert(cache != null); CacheFile = cache; //assume that the data is up to date (this will be overridden by the value in the XML if we have a prior install) //If we have no prior install then the app has no shows and is by definition up-to-date latestMovieUpdateTime = new UpdateTimeTracker(); latestTvUpdateTime = new UpdateTimeTracker(); LastErrorMessage = string.Empty; LoadOk = loadFrom is null || (CachePersistor.LoadMovieCache(loadFrom, this) && CachePersistor.LoadTvCache(loadFrom, this)); }
protected void DeleteOrRecycleFile(FileInfo?file) { if (file is null) { return; } if (Tidyup is null || Tidyup.DeleteEmptyIsRecycle) { LOGGER.Info($"Recycling {file.FullName}"); Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(file.FullName, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin); }
private static bool ValidateParameters(FileInfo?file, FileInfo[] references) { var errors = new List <string>(); if (file == null) { errors.Add($"No file was provided."); } else if (!file.Exists) { errors.Add($"File {file} does not exist."); } if (references is { } && references.Length > 0)
public async Task Start(CancellationToken cancellationToken) { _info = new FileInfo(FilePath); _lastWriteTime = _info.LastWriteTime; while (!cancellationToken.IsCancellationRequested) { await Task.Delay(PollingInterval, cancellationToken).ConfigureAwait(false); if (!cancellationToken.IsCancellationRequested) { PerformCheck(); } } }
protected NewCommandHandlerBase(FileInfo?outputPath, FileInfo?publicOutputPath, string?password, uint?iterationCount, uint?saltSize, string?alg, string?use, List <string?> keyOps, string?kid, bool noKid, bool force, IStore store) { _outputPath = outputPath; _publicOutputPath = publicOutputPath; _password = password; _iterationCount = iterationCount ?? 1000; _saltSize = saltSize ?? 8; _alg = alg; _use = use; _keyOps = keyOps; _kid = kid; _noKid = noKid; _force = force; _store = store; }
public void Set(ReadOnlyMemory <byte> content) { Content = content; if (TempFile != null && TempFile.Exists) { try { TempFile.Delete(); } catch (Exception) { WebServerLog.Add(ServerLogType.Information, GetType(), "POST", "Cannot delete temp file"); } } TempFile = null; }
public void Set(FileInfo tempFile) { Content = null; if (TempFile != null && TempFile.FullName != tempFile.FullName) { try { TempFile.Delete(); } catch (Exception) { WebServerLog.Add(ServerLogType.Information, GetType(), "POST", "Cannot delete temp file"); } } TempFile = tempFile; }
/// <inheritdoc/> public override bool Equals(FileInfo?x, FileInfo?y) { if (x is null) { throw new ArgumentNullException(nameof(x)); } if (y is null) { throw new ArgumentNullException(nameof(y)); } x.Refresh(); y.Refresh(); return(string.Equals(x.FullName, y.FullName, StringComparison.OrdinalIgnoreCase)); }
private static async Task GenerateAsync(FileInfo?solution, FileInfo?project, FileInfo?compilerInvocation, string?output, LsifFormat outputFormat, string?log) { // If we have an output file, we'll write to that, else we'll use Console.Out using var outputFile = output != null ? new StreamWriter(output) : null; var outputWriter = outputFile ?? Console.Out; using var logFile = log != null ? new StreamWriter(log) : TextWriter.Null; ILsifJsonWriter lsifWriter = outputFormat switch { LsifFormat.Json => new JsonModeLsifJsonWriter(outputWriter), LsifFormat.Line => new LineModeLsifJsonWriter(outputWriter), _ => throw new NotImplementedException() }; try { // Exactly one of "solution", or "project" or "compilerInvocation" should be specified if (solution != null && project == null && compilerInvocation == null) { await GenerateFromSolutionAsync(solution, lsifWriter, logFile); } else if (solution == null && project != null && compilerInvocation == null) { await GenerateFromProjectAsync(project, lsifWriter, logFile); } else if (solution == null && project == null && compilerInvocation != null) { await GenerateFromCompilerInvocationAsync(compilerInvocation, lsifWriter, logFile); } else { throw new Exception("Exactly one of either a solution path, project path or a compiler invocation path should be supplied."); } } catch (Exception e) { // If it failed, write out to the logs and error, but propagate the error too var message = "Unhandled exception: " + e.ToString(); await logFile.WriteLineAsync(message); Console.Error.WriteLine(message); throw; } (lsifWriter as IDisposable)?.Dispose(); await logFile.WriteLineAsync("Generation complete."); }
#pragma warning restore CS8629 // 可为 null 的值类型可为 null。 /// <summary> /// 解压文件。 /// </summary> /// <param name="compressFile">给定的压缩文件。</param> /// <returns>返回解压的文件数组。</returns> public FileInfo[]? UncompressFiles(FileInfo?compressFile) { if (compressFile is null || !compressFile.Exists || string.IsNullOrEmpty(CompressedFile)) { return(null); } var uncompressFilePath = compressFile.FullName.TrimEnd(compressFile.Extension); // 解压文件 if (!uncompressFilePath.UncompressProcess(compressFile.FullName, CompressedFile)) { return(null); } return(uncompressFilePath.GetFileInfos()); }
private bool TryGetFile(string filename, [NotNullWhen(true)] out FileInfo?file) { var shaderLocalPath = Path.Combine(ShaderDirectory, filename); var appLocalPath = Path.Combine(AppDirectory, filename); if (File.Exists(shaderLocalPath)) { file = new FileInfo(shaderLocalPath); } else if (File.Exists(appLocalPath)) { file = new FileInfo(appLocalPath); } else if (_lastDirectory is not null && Path.Combine(_lastDirectory, filename) is var lastPath && File.Exists(lastPath)) { file = new FileInfo(lastPath); }
/// <summary> /// Create an excel report of the new found /// </summary> /// <param name="keywords">A list of words to check the notes with</param> /// <param name="changeNotes">A list of the new change notes</param> public void CreateReport(List <string> keywords, List <List <string> > changeNotes, bool doCheckKeywords = false) { var date = DateTime.Now.ToString().Replace(":", "-"); var reportPath = Path.GetFullPath(Path.Combine(reportDir, date + "_ReleaseNotesReport.xlsx")); this.excelFile = new FileInfo(reportPath); this.excelPackage.Workbook.Worksheets.Add("Release Notes"); var reportWorksheet = excelPackage.Workbook.Worksheets["Release Notes"]; var headerRow = new List <string[]> { new string[] { "Release", "Change Headline", "Change Notes" } }; var headerRange = "A1:" + char.ConvertFromUtf32(headerRow[0].Length + 64) + "1"; reportWorksheet.Cells[headerRange].LoadFromArrays(headerRow); reportWorksheet.Cells[2, 1].LoadFromArrays(new List <string[]> { changeNotes[0].ToArray() }); int row = 2; for (int i = 1; i < changeNotes.Count; i++) { if (i % 2 == 1) { if (doCheckKeywords && (keywords.Any(keyword => changeNotes[i][0].IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0))) { HighlightNote(reportWorksheet, row, 2); } reportWorksheet.Cells[row++, 2].Value = changeNotes[i][0]; } else { for (int j = 0; j < changeNotes[i].Count; j++) { if (doCheckKeywords && (keywords.Any(keyword => changeNotes[i][j].IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0))) { HighlightNote(reportWorksheet, row, 3); } reportWorksheet.Cells[row++, 3].Value = changeNotes[i][j]; } } } AutoFitColumns(reportWorksheet, headerRow[0].Length); excelPackage.SaveAs(excelFile); }
public bool TryGetPaketFiles([NotNullWhen(true)] out FileInfo?dependencies, [NotNullWhen(true)] out FileInfo? @lock, [NotNullWhen(true)] out FileInfo?paketExe) { if (this.Directory.EnumerateFiles("paket.dependencies").FirstOrDefault() is { } deps&& this.Directory.EnumerateDirectories(".paket").FirstOrDefault() is { } paketDir&& paketDir.EnumerateFiles("paket.exe").FirstOrDefault() is { } exe) { dependencies = deps; @lock = this.Directory.EnumerateFiles("paket.lock").FirstOrDefault(); paketExe = exe; return(true); } dependencies = null; @lock = null; paketExe = null; return(false); }
public static async Task HandleFiles( ILogger logger, DirectoryInfo projectPath, OptionsFile options) { ArgumentNullException.ThrowIfNull(projectPath); ArgumentNullException.ThrowIfNull(options); ProjectSanityCheckHelper.CheckFiles( throwIf: true, logger, projectPath, options.ProjectTarget); HandleEditorConfigFiles(logger, projectPath, options); if (options.ProjectTarget is SupportedProjectTargetType.DotNetCore or SupportedProjectTargetType.DotNet5 or SupportedProjectTargetType.DotNet6) { HandleDirectoryBuildPropsFiles(logger, projectPath, options); if (options.UseTemporarySuppressions) { DirectoryInfo?temporarySuppressionsPath = null; if (!string.IsNullOrEmpty(options.TemporarySuppressionsPath)) { temporarySuppressionsPath = new DirectoryInfo(options.TemporarySuppressionsPath); } FileInfo?buildFile = null; if (!string.IsNullOrEmpty(options.BuildFile)) { buildFile = new FileInfo(options.BuildFile); } await HandleTemporarySuppressions( logger, projectPath, buildFile, temporarySuppressionsPath, options.TemporarySuppressionAsExcel); } } }
// gets this macro content from the cache // ensuring that it is appropriate to use the cache private MacroContent?GetMacroContentFromCache(MacroModel model) { if (!_umbracoContextAccessor.TryGetUmbracoContext(out IUmbracoContext? umbracoContext)) { return(null); } // only if cache is enabled if (umbracoContext.InPreviewMode || model.CacheDuration <= 0) { return(null); } IAppPolicyCache cache = _appCaches.RuntimeCache; MacroContent? macroContent = cache.GetCacheItem <MacroContent>(CacheKeys.MacroContentCacheKey + model.CacheIdentifier); if (macroContent == null) { return(null); } _logger.LogDebug("Macro content loaded from cache '{MacroCacheId}'", model.CacheIdentifier); // ensure that the source has not changed // note: does not handle dependencies, and never has FileInfo?macroSource = GetMacroFile(model); // null if macro is not file-based if (macroSource != null) { if (macroSource.Exists == false) { _logger.LogDebug("Macro source does not exist anymore, ignore cache."); return(null); } if (macroContent.Date < macroSource.LastWriteTime) { _logger.LogDebug("Macro source has changed, ignore cache."); return(null); } } return(macroContent); }
private static IEnumerable <FilteredPackageInfo>?LoadKnownPackagesList(CommandArgs config) { if (!config.DiffMode || config.DiffOverrideKnownPackagesLocation == null) { return(null); } FileInfo?fileLocation = config.DiffOverrideKnownPackagesLocation; Verbose.WriteLine($"Opening {fileLocation.FullName}"); using (var fileStream = fileLocation.OpenRead()) using (var textReader = new StreamReader(fileStream, System.Text.Encoding.UTF8, true)) using (var jsonReader = new JsonTextReader(textReader)) { return(new JsonSerializer().Deserialize <IEnumerable <FilteredPackageInfo> >(jsonReader)); } }
/// <summary> /// Extract master database from source. /// </summary> /// <param name="source">The asset file containing database.</param> /// <param name="dest">Destination to save file. Default to master.bytes.</param> /// <exception cref="NotSupportedException">Bundle is not AssetBundle.</exception> public static void ExtractMasterData(FileInfo source, FileInfo?dest = null) { var am = new AssetsManager(); am.LoadFiles(source.FullName); var obj = am.assetsFileList[0].Objects[1]; dest ??= new FileInfo("master.bytes"); if (obj is TextAsset database) { using var f = dest.Create(); f.Write(database.m_Script); } else { throw new NotSupportedException("bundle is not AssetBundle"); } }
internal static FileInfo?GetFilePart(int index, FileInfo part1) //base the name on the first part { FileInfo?item = null; //split 001, 002 ... Match m = Regex.Match(part1.Name, @"^(.*\.)([0-9]+)$", RegexOptions.IgnoreCase); if (m.Success) { item = new FileInfo(Path.Combine(part1.DirectoryName !, String.Concat(m.Groups[1].Value, (index + 1).ToString().PadLeft(m.Groups[2].Value.Length, '0')))); } if (item != null && item.Exists) { return(item); } return(null); }
static string?IsYTD(FileInfo?file) { if (file == null) { return("But which .YTD sire?"); } if (!file.Exists) { return($"I'm sorry my sire, but {file.FullName} isn't a valid file"); } using (var fs = file.OpenRead()) { if (fs.ReadByte() != 'R' || fs.ReadByte() != 'S' || fs.ReadByte() != 'C' || fs.ReadByte() != '7') { return($"It appears that {file.Name} is not a GTA V (PC) Resource7 file"); } } return(null); }
public void TestF() { { FCalled = false; FAParameter = null; const string fileName = "Towel_Testing.xml"; HandleArguments(new[] { "F", "--a", fileName }); Assert.IsTrue(FCalled); Assert.IsTrue(FAParameter is not null && FAParameter.Name == fileName); } { FCalled = false; FAParameter = null; HandleArguments(new[] { "F" }); Assert.IsTrue(!FCalled); Assert.IsTrue(FAParameter is null); } }
/// <summary> /// Generates a SQL import script from a folder of a full json export from Exist.io /// </summary> /// <param name="inputFolder">Folder containing Exist.io json files. Defaults to current directory.</param> /// <param name="outputFile">Path to output SQL script. Defaults to inputFolder\ImportExistJson.sql</param> private static void Main(DirectoryInfo?inputFolder = null, FileInfo?outputFile = null) { if (inputFolder == null) { inputFolder = new DirectoryInfo(Directory.GetCurrentDirectory()); } if (outputFile == null) { outputFile = new FileInfo(Path.Combine(inputFolder.FullName, "ImportExistJson.sql")); } Console.WriteLine($"Looking for Exist json files in folder: {inputFolder.FullName}"); Console.WriteLine($"Writing output script to {outputFile.FullName}"); var gen = new ScriptGenerator(); gen.GenerateFromFolder(inputFolder.FullName, outputFile.FullName); }
/// <summary> /// Sets and configures minimal user interface. /// </summary> /// <param name="project"></param> /// <param name="backgroundImage"> /// Installer dialogs background. /// If not specified default image will be used. /// If the image is to be used in the default ManagedUI dialogs it will be left-docked /// at runtime and will effectively play the role of a left-aligned dialog banner. /// Thus if it is too wide it can push away (to right) the all other UI elements. /// The optimal size of the image for ManagedUI is 494 by 312 pixels. /// The optimal format is BMP. /// </param> /// <param name="bannerImage"> /// Installer banner visible on top of the window. /// If not specified, default image will be used. /// The optimal format is BMP. /// The optimal size of the image is 500 by 63 pixels. /// </param> /// <param name="licenceRtfFile"></param> /// <returns></returns> public static TProject SetMinimalUI <TProject>(this TProject project, FileInfo?backgroundImage = null, FileInfo?bannerImage = null, FileInfo?licenceRtfFile = null) where TProject : Project { if (project is null) { throw new ArgumentNullException(nameof(project)); } project.UI = WUI.WixUI_Minimal; project.BackgroundImage = backgroundImage?.FullName; project.ValidateBackgroundImage = false; // ignoring incorrect banner resolution project.BannerImage = bannerImage?.FullName; project.LicenceFile = licenceRtfFile?.FullName; return(project); }
/// <summary> /// Constructor /// </summary> /// <param name="loggerFactory">The logger factory</param> /// <param name="options">The options</param> public ConnectMagicService( ILoggerFactory loggerFactory, IOptions <Configuration> options ) { InitializeComponent(); _logger = loggerFactory.CreateLogger <ConnectMagicService>(); _configuration = options.Value; _cancellationTokenSource = new CancellationTokenSource(); // Create State object _state = _configuration.State; // Store Max file age _maxFileAge = TimeSpan.FromHours(_configuration.MaxFileAgeHours); // Create task list _connectedSystemTasks = new List <Task>(); // Set up the Event Log try { if (!EventLog.SourceExists(EventLogSourceName)) { EventLog.CreateEventSource(EventLogSourceName, "Application"); } if (EventLog.SourceExists(EventLogSourceName)) { _eventLogClient = new EventLogClient(EventLogSourceName); } } catch { // This is OK, we just don't have access to the event log } if (!string.IsNullOrWhiteSpace(_configuration.State.CacheFileName)) { _stateFileInfo = new FileInfo(_configuration.State.CacheFileName); } _loggerFactory = loggerFactory; }
/// <summary> /// Extract text resource from const text file. /// </summary> /// <param name="source">The Unity asset file.</param> /// <param name="json">Export json to given file. If this is null, no export is done.</param> /// <param name="yaml">Export yaml to given file. If this is null, no export is done.</param> public static void ExtractConstText(FileInfo source, FileInfo?json = null, FileInfo?yaml = null) { var file = Unity3dResource.LoadAssetFile(source); var ls = file.Objects.OfType <MonoBehaviour>().First().ToType(); var data = ls["dataArray"]; if (data is not List <object> list) { Console.Error.WriteLine($"Invalid dataArray type {data?.GetType()}."); return; } if (json != null) { using var fs = json.Create(); JsonSerializer.SerializeAsync(fs, list, Json.Options).Wait(); } if (yaml != null) { var dict = new Dictionary <int, ConstText>(); list.ForEach(x => { if (x is OrderedDictionary od && od["TextId"] is int id && od["TextString"] is string str) { str = str.Replace("\\n", "\n"); var textId = (TextId)id; dict.Add(id, new ConstText { Name = Enum.IsDefined(textId) ? textId.ToString() : null, Value = str }); } }); using var fy = yaml.CreateText(); var serializer = new SerializerBuilder() .WithEventEmitter(next => new LiteralMultilineEmitter(next)) .Build(); serializer.Serialize(fy, dict); } }
// TODO: optimise? internal static bool IsValidPath(string path) { FileInfo?fi = null; try { fi = new FileInfo(path); } catch (ArgumentException) { } catch (PathTooLongException) { } catch (NotSupportedException) { } return(fi is not null); }