public void ReadTranspondersTest() { const string transponderType = "MYLAPS ProChip"; var file = Resources.AFile; var converter = new MylapsTransponderCodeConverter(); var labelConverter = new Func <string, long?>(s => { long code; return(converter.TryConvertLabel(transponderType, s, out code) ? code : new long?()); }); IList <Transponder> transponders; using (var reader = new StringReader(file)) transponders = AFile.ReadTransponders(reader, transponderType, labelConverter).ToList(); Assert.AreEqual(78, transponders.Count); Assert.IsTrue(transponders.All(t => t.Type == transponderType)); Assert.AreEqual(102061448, transponders[38].Code); Assert.AreEqual("CX-98152", transponders[38].Label); Assert.AreEqual(102000459, transponders[39].Code); Assert.AreEqual("CX-37163", transponders[39].Label); Assert.AreEqual("HC-81093", transponders.Last().Label); }
private void Rename(AFile file) { /* 不接受空文件 */ if (file == null || OldName == null) { return; } /* 文件名不接受斜杠 */ NewName = file.Name; /* 不接受空文件名 */ if (string.IsNullOrEmpty(NewName)) { file.Name = NewName = OldName; } /* 同名无需操作 */ if (NewName == OldName) { return; } bool result = ShowErrMessage(Adb.Rename(NewName, OldName)); /* 更新列表 */ ForceReflush(); string filename = result ? OldName : NewName; /* 选中被修改的文件 */ FileList.SelectedItem = FileList.Items.Cast <AFile>().First(new_file => new_file.Name.ToString().Equals(filename)); /* 清空新文件名缓存 */ NewName = null; }
/// <summary> /// Fills submenu File -> Workspace -> Recent. /// </summary> public void ZFillMenuRecentWorkspaces(ToolStripDropDownMenu dd) { void _Add(string path, bool bold) { var mi = dd.Items.Add(path, null, (o, u) => ZLoadWorkspace(o.ToString())); if(bold) mi.Font = Au.Util.AFontsCached_.Bold; } dd.SuspendLayout(); dd.Items.Clear(); _Add(Program.Settings.workspace, true); var ar = Program.Settings.recentWS; int nRemoved = 0; for(int i = 0, n = ar?.Length ?? 0; i < n; i++) { var path = ar[i]; if(dd.Items.Count >= 20 || !AFile.ExistsAsDirectory(path)) { ar[i] = null; nRemoved++; } else _Add(path, false); } if(nRemoved > 0) { var an = new string[ar.Length - nRemoved]; for(int i = 0, j = 0; i < ar.Length; i++) if(ar[i] != null) an[j++] = ar[i]; Program.Settings.recentWS = an; } dd.ResumeLayout(); }
static void Upload(string docDir) { if (!ARegistry.GetString(out var user, "kas", @"\Help") || !ARegistry.GetString(out var pass, "kaip", @"\Help") || !ARegistry.GetString(out var pass2, "kaip2", @"\Help") ) { throw new FileNotFoundException("user or password not found in registry"); } //upload pass = Encoding.UTF8.GetString(Convert.FromBase64String(pass)); var name = @"\_site.tar.bz2"; var path = docDir + name; using (var client = new WebClient()) { client.Credentials = new NetworkCredential(user, pass); client.UploadFile("ftp://ftp.quickmacros.com/public_html/au" + name, WebRequestMethods.Ftp.UploadFile, path); } AFile.Delete(path); AOutput.Write("Uploaded"); //extract using (var client = new WebClient()) { string r1 = client.DownloadString($"https://www.quickmacros.com/au/extract_help.php?kaip={pass2}"); if (r1 != "done") { AOutput.Write(r1); return; } } AOutput.Write("<>Extracted to <link>https://www.quickmacros.com/au/help/</link>"); }
static void ProcessHtmlFiles(string siteDir, bool test) { string files = "*.html"; if (test) { //files = @"\api\Au.AaaDocFX*"; //files = @"\api\Au.ARegex.Replace"; files = @"\api\Au.AAcc.Find"; files = @"\api\Au.ADialog.Show"; files = @"\articles\Wildcard expression"; files += ".html"; } foreach (var f in AFile.EnumDirectory(siteDir, FEFlags.AndSubdirectories | FEFlags.NeedRelativePaths)) { if (f.IsDirectory) { continue; } var name = f.Name; if (!name.Like(files, true) || name.Ends(@"\toc.html")) { continue; } var file = f.FullPath; //if(test) AOutput.Write($"<><c 0xff>{file}</c>"); var s = File.ReadAllText(file); bool modified = ProcessHtmlFile(ref s, name.Starts(@"\api"), siteDir); if (modified) { File.WriteAllText(!test ? file : file.Remove(file.Length - 1), s); } } ProcessJs(siteDir); }
public void Show() { if (_path != null && AFile.ExistsAsFile(_path)) { AExec.TryRun(_path); } }
public void MainTest() { // Sample Initialization string FilesExamplePath = AHelper.BASE_PATH + @"\FilesExample", ExampleFileName = "demoFile.txt"; Directory.CreateDirectory(FilesExamplePath); using (StreamWriter streamWriter = new StreamWriter(FilesExamplePath + @"\" + ExampleFileName, false)) { streamWriter.WriteLine("Hello Alterful!"); } AFile.Add("demo", FilesExamplePath + @"\" + ExampleFileName); // ----Instruction Sample---- // new AInstruction_Startup("demo demo-f").Execute(); // new AInstruction_Macro("@new a.txt b.txt").Execute(); // new AInstruction_Macro(@"@add f f:\").Execute(); // new AInstruction_Macro("f").Execute(); // new AInstruction_Macro(@"@del f").Execute(); // -----Demo End----- // ----Sample For fun---- string yourChromePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"; AInstruction.GetInstruction("@add chrome " + yourChromePath).Execute(); AInstruction.GetInstruction("@add #fy chrome-o/https://fanyi.baidu.com/#zh/en/").Execute(); AInstruction.GetInstruction("#fy+键盘增强").Execute(); // ----Sample For fun---- }
/// <summary> /// 执行宏删除指令 /// </summary> /// <exception cref="MacroFormatException"></exception> /// <exception cref="AFile.StartupItemNotFoundException"></exception> /// <exception cref="UnauthorizedAccessException"></exception> private void ExecuteMacroDel() { // MacroDeleteType - Const Instruction if ((Instruction.IndexOf("(") < Instruction.IndexOf(")")) && Instruction.IndexOf(")") != -1 && Instruction.IndexOf(")") == Instruction.Length - 1) { try { AConstInstruction.Delete(AInstruction_Const.GetConstInstructionFromMacroInstruction(Instruction)); return; } catch (Exception exception) { throw exception; } } List <string> macroInstructionParametersRaw = GetMacroInstructionParametersList(); if (macroInstructionParametersRaw.Count < 1) { throw new MacroFormatException(); } foreach (string delItemString in macroInstructionParametersRaw) { switch (GetMacroDelType(delItemString)) { case MacroDelType.STARTUP: AFile.Delete(delItemString); break; case MacroDelType.CONST_QUOTE: ExecuteMacroDelConstQuote(delItemString); break; } } }
public void GetTargetPathOfShortcutFileTest() { string lnkFilePath = AFile.GetFullPathOfShortcutFile(@"\startupItemTest", UNITTEST_DIRECTORY_APATH); string expected = @"C:\"; string actual = AFile.GetTargetPathOfShortcutFile(lnkFilePath); Assert.AreEqual(expected, actual); }
/**<summary>记录重命名前状态</summary>**/ private void FileList_BeginningEdit(object sender, DataGridBeginningEditEventArgs e) { if (e.Row.Item is AFile file) { EditingFile = file; OldName = EditingFile.Name; } }
//protected override void OnGotFocus(EventArgs e) { _c.Focus(); } /// <summary> /// Loads existing or new workspace. /// If fails, shows a task dialog with several choices - retry, load another, create new, cancel. If then fails, ends process. /// Sets Model and Text properties of the main form. Updates recent files. /// By default runs startup script. /// </summary> /// <param name="wsDir"> /// Workspace's directory. The directory should contain file "files.xml" and subdirectory "files". /// If null, loads the last used workspace (its path is in settings). /// If the setting does not exist, uses AFolders.ThisAppDocuments + @"Main". /// If the file does not exist, copies from AFolders.ThisApp + @"Default\Workspace". /// </param> public FilesModel ZLoadWorkspace(string wsDir = null) { wsDir ??= Program.Settings.workspace; if(wsDir.NE()) wsDir = AFolders.ThisAppDocuments + "Main"; var xmlFile = wsDir + @"\files.xml"; var oldModel = _model; FilesModel m = null; _isNewWorkspace = false; g1: try { //SHOULDDO: if editor runs as admin, the workspace directory should be write-protected from non-admin processes. if(_isNewWorkspace = !AFile.ExistsAsFile(xmlFile)) { AFile.Copy(AFolders.ThisAppBS + @"Default\Workspace", wsDir); } _model?.UnloadingWorkspace(); //saves all, closes documents, sets current file = null m = new FilesModel(_c, xmlFile); _c.Model = m; } catch(Exception ex) { m?.Dispose(); m = null; //AOutput.Write($"Failed to load '{wsDir}'. {ex.Message}"); switch(ADialog.ShowError("Failed to load workspace", wsDir, "1 Retry|2 Load another|3 Create new|0 Cancel", owner: this, expandedText: ex.ToString())) { case 1: goto g1; case 2: m = ZLoadAnotherWorkspace(); break; case 3: m = ZLoadNewWorkspace(); break; } if(m != null) return m; if(_model != null) return _model; Environment.Exit(1); } oldModel?.Dispose(); Program.Model = _model = m; //CONSIDER: unexpand path if(wsDir != Program.Settings.workspace) { if(Program.Settings.workspace != null) { var ar = Program.Settings.recentWS ?? Array.Empty<string>(); int i = Array.IndexOf(ar, wsDir); if(i >= 0) ar = ar.RemoveAt(i); Program.Settings.recentWS = ar.InsertAt(0, Program.Settings.workspace); } Program.Settings.workspace = wsDir; } Program.MainForm.ZSetTitle(); if(Program.Loaded >= EProgramState.LoadedWorkspace) { ZOpenDocuments(); ZModel.RunStartupScripts(); } return _model; }
static JSettings _Load(string file, Type type, bool useDefault) { JSettings R = null; if (AFile.ExistsAsAny(file)) { try { if (useDefault) { AFile.Delete(file); } else { var b = AFile.LoadBytes(file); var opt = new JsonSerializerOptions { IgnoreNullValues = true, AllowTrailingCommas = true }; R = JsonSerializer.Deserialize(b, type, opt) as JSettings; } } catch (Exception ex) { string es = ex.ToStringWithoutStack(); if (useDefault) { AOutput.Write($"Failed to delete settings file '{file}'. {es}"); } else { string backup = file + ".backup"; try { AFile.Move(file, backup, IfExists.Delete); } catch { backup = "failed"; } AOutput.Write( $@"Failed to load settings from {file}. Will use default settings. {es} Backup: {backup}" ); } } } R ??= Activator.CreateInstance(type) as JSettings; R._file = file; R._loaded = true; //autosave if (Interlocked.Exchange(ref s_loadedOnce, 1) == 0) { AThread.Start(() => { for (; ;) { Thread.Sleep(2000); _SaveAllIfNeed(); } }, sta: false); AProcess.Exit += (unu, sed) => _SaveAllIfNeed(); //info: Core does not call finalizers when process exits } lock (s_list) s_list.Add(R); return(R); }
public ActionResult Edit(Guid?id) { AFile file = new AFile(); if (id != null) { file = reposetory.GetFile((Guid)id); } return(View(file)); }
public static ASqlite OpenWinapi() { string copy = Program.Settings.db_copy_winapi; if (copy != null) { Program.Settings.db_copy_winapi = null; AFile.CopyTo(copy, AFolders.ThisApp, IfExists.Delete); } return(new ASqlite(AFolders.ThisAppBS + "winapi.db", SLFlags.SQLITE_OPEN_READONLY)); }
/// <summary> /// Loads XML file and creates tree of nodes from it. /// Returns the root node. /// </summary> /// <param name="file">XML file. Must be full path. Can contain environment variables etc, see <see cref="APath.ExpandEnvVar"/>.</param> /// <param name="nodeReader">Callback function that reads current XML element and creates/returns new node. See example.</param> /// <exception cref="ArgumentException">Not full path.</exception> /// <exception cref="Exception">Exceptions of <see cref="XmlReader.Create(string)"/>.</exception> /// <exception cref="XmlException">An error occurred while parsing the XML.</exception> /// <example><see cref="ATreeBase{T}"/></example> protected static T XmlLoad(string file, XmlNodeReader nodeReader) { file = APath.NormalizeForNET_(file); var xs = new XmlReaderSettings() { IgnoreComments = true, IgnoreProcessingInstructions = true, IgnoreWhitespace = true }; using var r = AFile.WaitIfLocked(() => XmlReader.Create(file, xs)); return(XmlLoad(r, nodeReader)); }
/// <summary> /// 执行宏新建指令 /// </summary> /// <exception cref="UnauthorizedAccessException"></exception> private void ExecuteMacroNew() { List <string> macroInstructionParameters = GetMacroInstructionParametersList(); // Handle [in] sytex string inWhere = AFile.ATEMP_PATH; if (macroInstructionParameters.Count >= 3 && "in" == macroInstructionParameters[macroInstructionParameters.Count - 2]) { string lastParam = macroInstructionParameters[macroInstructionParameters.Count - 1]; if (AFile.Exists(lastParam)) { // If the item is already a directory string itemPath = AFile.GetFullPath(lastParam); if (Directory.Exists(itemPath)) { inWhere = itemPath; } // If the item is exist else if (File.Exists(itemPath)) { inWhere = Path.GetDirectoryName(itemPath); } else { throw new NotImplementedException("The startup item [" + lastParam + "] is not found in disk."); } } else if (Directory.Exists(lastParam)) { inWhere = lastParam; } else { throw new NotImplementedException("The directory [" + lastParam + "] is not exist."); } macroInstructionParameters.RemoveRange(macroInstructionParameters.Count - 2, 2); } // Remove the last '\' if (inWhere.Last() == '\\') { inWhere = inWhere.Substring(0, inWhere.Length - 1); } foreach (string newFileName in macroInstructionParameters) { string fileName = AConstQuote.ConstQuoteParse(newFileName); string filePath = inWhere + @"\" + fileName; using (StreamWriter streamWriter = new StreamWriter(filePath, false)) { } AFile.StartupProcess(filePath); //AFile.LaunchTempFile(fileName); } }
/// <summary> /// Saves tree of nodes (this and descendants) to an XML file. /// </summary> /// <param name="file">XML file. Must be full path. Can contain environment variables etc, see <see cref="APath.ExpandEnvVar"/>.</param> /// <param name="nodeWriter">Callback function that writes node's XML start element (see <see cref="XmlWriter.WriteStartElement(string)"/>) and attributes (see <see cref="XmlWriter.WriteAttributeString(string, string)"/>). Must not write children and end element. Also should not write value, unless your reader knows how to read it.</param> /// <param name="sett">XML formatting settings. Optional.</param> /// <param name="children">If not null, writes these nodes as if they were children of this node.</param> /// <exception cref="ArgumentException">Not full path.</exception> /// <exception cref="Exception">Exceptions of <see cref="XmlWriter.Create(string)"/> and other <b>XmlWriter</b> methods.</exception> /// <remarks> /// Uses <see cref="AFile.Save"/>. It ensures that existing file data is not damaged on exception etc. /// </remarks> /// <example><see cref="ATreeBase{T}"/></example> protected void XmlSave(string file, XmlNodeWriter nodeWriter, XmlWriterSettings sett = null, IEnumerable <T> children = null) { file = APath.NormalizeForNET_(file); sett ??= new XmlWriterSettings() { OmitXmlDeclaration = true, Indent = true, IndentChars = " " }; AFile.Save(file, temp => { using var x = XmlWriter.Create(temp, sett); XmlSave(x, nodeWriter, children); }); }
/**<summary>跳转到文件所在位置</summary>**/ private void Go2File(AFile file) { if (file == null) { return; } /* 选中文件 */ FileList.SelectedItem = file; /* 对焦单元格 */ FileList.CurrentCell = new DataGridCellInfo(file, FileNameCol); /* 滚动至目标 */ FileList.ScrollIntoView(file); }
private void _ButtonBrowse_Click(object sender, EventArgs e) { var d = new FolderBrowserDialog(); d.Description = "Location. In the selected folder will be created the main folder of the workspace."; d.ShowNewFolderButton = true; d.SelectedPath = AFile.ExistsAsDirectory(textLocation.Text) ? textLocation.Text : (string)AFolders.ThisAppDocuments; if (d.ShowDialog(this) != DialogResult.OK) { return; } textLocation.Text = d.SelectedPath; }
/// <exception cref="MDSParseException">path reference no longer points to file</exception> private Dictionary <int, IBlob> MountBlobs(AFile mdsf, Disc disc) { Dictionary <int, IBlob> BlobIndex = new Dictionary <int, IBlob>(); int count = 0; foreach (var track in mdsf.Tracks) { foreach (var file in track.ImageFileNamePaths.Distinct()) { if (!File.Exists(file)) { throw new MDSParseException($"Malformed MDS format: nonexistent image file: {file}"); } IBlob mdfBlob = null; long mdfLen = -1; //mount the file if (mdfBlob == null) { var mdfFile = new Blob_RawFile() { PhysicalPath = file }; mdfLen = mdfFile.Length; mdfBlob = mdfFile; } bool dupe = false; foreach (var re in disc.DisposableResources) { if (re.ToString() == mdfBlob.ToString()) { dupe = true; } } if (!dupe) { // wrap in zeropadadapter disc.DisposableResources.Add(mdfBlob); BlobIndex[count++] = mdfBlob; } } } return(BlobIndex); }
private void _ButtonOK_Click(object sender, EventArgs e) { var ok = true; var path = textPath.Text; if (!APath.IsFullPath(path)) { ok = false; } else if (AFile.ExistsAsAny(path)) { ADialog.ShowError("Already exists", path, owner: this); ok = false; } this.DialogResult = ok ? DialogResult.OK : DialogResult.None; }
/// <summary> /// Appends lines to a file. If the file doesn't exist, this method creates the file, writes the lines to the it, and then closes the it. /// </summary> /// <param name="file">The file.</param> /// <param name="contents">The contents.</param> /// <returns>Whether the write was successful or not.</returns> public static bool AppendAllLines(AFile file, IEnumerable<string> contents) { Exceptions.NotNullException<AFile>(file, nameof(file)); Exceptions.NotNullException<IEnumerable<string>>(contents, nameof(contents)); if (!file.IsOpen) { var str = new StringBuilder(); foreach (var line in contents) str.AppendLine(line); return file.WriteAll(str.ToString(), WriteMode.Append); } return false; }
static void _CreateRef(string dbFile, string dir1, string dir2) { AFile.Delete(dbFile); using var d = new ASqlite(dbFile); using var trans = d.Transaction(); d.Execute("CREATE TABLE ref (name TEXT PRIMARY KEY, data BLOB)"); using var statInsert = d.Statement("INSERT OR REPLACE INTO ref VALUES (?, ?)"); _AddDir(dir1, "WindowsBase", "System.Drawing"); _AddDir(dir2); trans.Commit(); d.Execute("VACUUM"); AOutput.Write("Created " + dbFile); void _AddDir(string dir, params string[] skip) { foreach (var f in AFile.EnumDirectory(dir)) { if (f.IsDirectory) { continue; } if (!f.Name.Ends(".dll", true)) { continue; } var asmName = f.Name.RemoveSuffix(4); if (skip.Contains(asmName)) { continue; } _AddFile(asmName, f.FullPath); //break; } } void _AddFile(string asmName, string asmFile) { //AOutput.Write(asmName); statInsert.Bind(1, asmName); statInsert.Bind(2, File.ReadAllBytes(asmFile)); statInsert.Step(); statInsert.Reset(); } }
/// <summary> /// Creates SQLite database containing Windows API declarations. /// </summary> public static void CreateWinapi(string csDir = @"Q:\app\Au\Other\Api", string dataDir = @"Q:\app\Au\Other\Data") { Cursor.Current = Cursors.WaitCursor; string dbFile = dataDir + @"\winapi.db"; AFile.Delete(dbFile); string s = File.ReadAllText(csDir + @"\Api.cs"); using var d = new ASqlite(dbFile); using var trans = d.Transaction(); d.Execute("CREATE TABLE api (name TEXT, def TEXT)"); //note: no PRIMARY KEY. Don't need index. using var statInsert = d.Statement("INSERT INTO api VALUES (?, ?)"); string rxType = @"(?ms)^(?:\[[^\r\n]+\r\n)*internal (?:struct|enum|interface|class) (\w+)[^\r\n\{]+\{(?:\}$|.+?^\})"; string rxFunc = @"(?m)^(?:\[[^\r\n]+\r\n)*internal (?:static extern|delegate) \w+\** (\w+)\(.+;$"; string rxVarConst = @"(?m)^internal (?:const|readonly|static) \w+ (\w+) =.+;$"; foreach (var m in s.RegexFindAll(rxType)) { _Add(m); } foreach (var m in s.RegexFindAll(rxFunc)) { _Add(m); } foreach (var m in s.RegexFindAll(rxVarConst)) { _Add(m); } void _Add(RXMatch m) { statInsert.Bind(1, m[1].Value); statInsert.Bind(2, m.Value); statInsert.Step(); statInsert.Reset(); } trans.Commit(); d.Execute("VACUUM"); Program.Settings.db_copy_winapi = dbFile; AOutput.Write("CreateWinapi done."); Cursor.Current = Cursors.Arrow; }
private void ExecuteMacroLocate() { List <string> macroInstructionParametersRaw = GetMacroInstructionParametersList(); foreach (string item in macroInstructionParametersRaw) { if (AFile.Exists(item)) { AFile.ShowInExplorer(item); } else { reportType = ReportType.ERROR; ReportInfo.Add("Startup item [" + item + "] is not exist."); } } }
/// <summary> /// Creates SQLite databases containing design-time assemblies and XML documentation files of a .NET Core runtime. The SDK must be installed. /// </summary> /// <remarks> /// Shows a list dialog. /// If selected All, creates for all runtime versions starting from 3.1, with names ref.version.db (eg ref.3.1.0.db) and doc.version.db, in AFolders.ThisAppBS. /// Else creates only for the selected runtime version, with names ref.db and doc.db, in dataDir, and sets to copy to AFolders.ThisAppBS when opening next time after process restarts. /// We ship and at run time load databases of single version, named ref.db and doc.db. In the future should allow to download and use multiple versions. /// Also this function allows users to create databases from SDKs installed on their PC, but currently this feature is not exposed. Would need to add UI and exception handling. /// ref.db contains dlls from 'dotnet\packs' folder. They contain only metadata of public API, not all code like dlls in the 'dotnet\shared' folder. /// Why need it when we can load PortableExecutableReference from 'dotnet\shared' folder? Because: /// 1. They are big and may add 100 MB of process memory. We need to load all, because cannot know which are actually used in various stages of compilation. /// 2. When loading from dll files, Windows Defender makes it as slow as 2.5 s or more, unless the files already are in OS file buffers. /// 3. Better compatibility. See https://github.com/dotnet/standard/blob/master/docs/history/evolution-of-design-time-assemblies.md /// doc.db contains XML documentation files of .NET Core assemblies. From the same 'dotnet\packs' folder. /// Why need it: /// 1. Else users would have to download whole .NET Core SDK. Now need only runtimes. /// 2. Parsed XML files can use eg 200 MB of process memory. Now we get doc of a single type/method/etc from database only when need; all other data is not in memory. /// /// Need to run this after changing Core version of C# projects (<TargetFramework>netcoreapp3.1</TargetFramework>). Also update COREVER2 etc in AppHost.cpp. /// </remarks> public static void CreateRefAndDoc(string dataDir = @"Q:\app\Au\Other\Data") { Cursor.Current = Cursors.WaitCursor; if (0 == AFolders.NetRuntimeBS.RegexReplace(@"(?i)\\shared\\(Microsoft\.NETCore\.App)\\.+", @"\packs\$1.Ref", out var refDir, 1)) { throw new AuException(); } //AOutput.Write(refDir); var a = new List <string>(); foreach (var f in AFile.EnumDirectory(refDir, FEFlags.UseRawPath)) //for each version { if (!f.IsDirectory) { continue; } var s = f.Name; int v1 = s.ToInt(0, out int ne), v2 = s.ToInt(ne + 1); if (v1 < 3 || v2 < 1) { continue; //must be 3.1 or later } a.Add(s); } a.Add("All"); int i = ADialog.ShowList(a, "Create database", "For runtime") - 1; if (i < 0) { return; } int n = a.Count - 1; if (i < n) { _CreateRefAndDoc(refDir, a[i], false, dataDir); } else { for (i = 0; i < n; i++) { _CreateRefAndDoc(refDir, a[i], true, dataDir); } } AOutput.Write("CreateRefAndDoc done."); Cursor.Current = Cursors.Arrow; }
/// <summary> /// Saves now if need. /// Don't need to call explicitly. Autosaving is every 2 s, also on process exit and <b>Dispose</b>. /// </summary> public void SaveIfNeed() { //AOutput.QM2.Write(_save); if (Interlocked.Exchange(ref _save, 0) != 0) { try { var opt = new JsonSerializerOptions { IgnoreNullValues = true, IgnoreReadOnlyProperties = true, WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; var b = JsonSerializer.SerializeToUtf8Bytes(this, GetType(), opt); AFile.SaveBytes(_file, b); //AOutput.QM2.Write(GetType().Name + " saved"); } catch (Exception ex) { SaveLater(); AOutput.Write($"Failed to save settings to '{_file}'. {ex.ToStringWithoutStack()}"); } } }
static void _Prepare1() { _SetComApartment(ApartmentState.STA); //JIT slowest-to-JIT methods //APerf.First(); //if(!Au.Util.Assembly_.IsAuNgened) { Au.Util.AJit.Compile(typeof(RunAssembly), nameof(RunAssembly.Run)); Au.Util.AJit.Compile(typeof(Au.Util.Serializer_), "Deserialize"); AFile.WaitIfLocked(() => (FileStream)null); //} //APerf.NW(); //Core ~15 ms //Core assembly loading is fast, but let's save several ms anyway _ = typeof(Stack <string>).Assembly; //System.Collections using (var stream = AFile.WaitIfLocked(() => File.OpenRead(Assembly.GetExecutingAssembly().Location))) stream.ReadByte(); //Core is not JIT-ed therefore opens file first time much slower than Framework. //TODO: too dirty _Hook(); }
/// <summary> /// If <see cref="AVersion.Is32BitProcessAnd64BitOS"/> is true and path starts with <see cref="AFolders.System"/>, replaces that path part with <see cref="AFolders.SystemX64"/>. /// It disables redirection to <see cref="AFolders.SystemX86"/> for that path. /// </summary> /// <param name="path">Normalized path. This function does not normalize. Also it is unaware of <c>@"\\?\"</c>.</param> /// <param name="ifExistsOnlyThere">Don't replace path if the file or directory exists in the redirected folder or does not exist in the non-redirected folder.</param> public static string GetNonRedirectedSystemPath(string path, bool ifExistsOnlyThere = false) { int i = _IsSystem64PathIn32BitProcess(path); if (i == 0) { return(path); } if (ifExistsOnlyThere && AFile.ExistsAsAny(path)) { return(path); } var s = path.ReplaceAt(0, i, AFolders.SystemX64); if (ifExistsOnlyThere && !AFile.ExistsAsAny(s)) { return(path); } return(s); }
private void TokenIterator(JToken jToken) { JProperty jProperty = jToken as JProperty; foreach (JProperty prop in jProperty.Value.Children()) { int size = -1; int offset = -1; foreach (JProperty nextProp in prop.Value.Children()) { if (nextProp.Name == "files") { /* ENABLE FOR EMPTY FOLDERS (ONLY IF NEEDED) */ if (_emptyDir) { AFile afile = new AFile(prop.Path, "", size, offset); _filesToExtract.Add(afile); } TokenIterator(nextProp); } else { if (nextProp.Name == "size") { size = Int32.Parse(nextProp.Value.ToString()); } if (nextProp.Name == "offset") { offset = Int32.Parse(nextProp.Value.ToString()); } } } if (size > -1 && offset > -1) { AFile afile = new AFile(prop.Path, prop.Name, size, offset); _filesToExtract.Add(afile); } } }
public void ReadRaceTranspondersTest() { string file = Resources.AFile; var races = new List <Race> { new Race { Heat = 16, Lane = 1, Competitor = new PersonCompetitor { PersonId = new Guid("{4F6178BB-0D05-493C-A600-5A9E2D3C40E1}"), StartNumber = 4, Name = new Name("S.", "Shannon", "Rempel") } } }; var transponders = new List <Transponder> { new Transponder { Code = 111140411, Label = "NZ-77115" }, new Transponder { Code = 102433532, Label = "FG-70236" } }; IList <RaceTransponder> raceTransponders; using (var reader = new StringReader(file)) raceTransponders = AFile.ReadRaceTransponders(reader, races, transponders, false).ToList(); Assert.AreEqual(2, raceTransponders.Count); Assert.AreEqual("Shannon Rempel", raceTransponders[0].Race.Competitor.FullName); Assert.AreEqual(102433532, raceTransponders[1].Transponder.Code); Assert.AreEqual(new Guid("{4F6178BB-0D05-493C-A600-5A9E2D3C40E1}"), raceTransponders[0].PersonId); }
/// <summary> /// Reads the entire file and returns the contents as a string enumberable, with each item representing a different line. /// </summary> /// <param name="file">The file.</param> /// <returns>A string enumberable representing the contents of the file.</returns> public static IEnumerable<string> ReadLines(AFile file) { Exceptions.NotNullException<AFile>(file, nameof(file)); return file.ReadAllLines(); }
/// <summary> /// Reads the entire file and returns the contents as a string list, with each item representing a different line. /// </summary> /// <param name="file">The file.</param> /// <returns>A string list representing the contents of the file.</returns> public static List<string> ReadLinesList(AFile file) { Exceptions.NotNullException<AFile>(file, nameof(file)); return new List<string>(file.ReadAllLines()); }
/// <summary> /// Gets the last access time of the file. /// </summary> /// <param name="file">The file.</param> /// <returns>The time the file was last accessed.</returns> public static DateTime GetLastAccessTime(AFile file) { Exceptions.NotNullException<AFile>(file, nameof(file)); return file.LastAccessedTime; }
/// <summary> /// Writes content to the file. If the file does not exist, this method will create the file, write to the file, and then close the file. /// </summary> /// <param name="file">The file.</param> /// <param name="contents">The contents.</param> /// <param name="writeMode">The write mode.</param> /// <returns>Whether the contents were written or not.</returns> public static bool WriteAllText(AFile file, string contents, WriteMode writeMode = WriteMode.Truncate) { Exceptions.NotNullException<AFile>(file, nameof(file)); Exceptions.NotNullException<string>(contents, nameof(contents)); return file.WriteAll(contents, writeMode); }
/// <summary> /// Asynchronously writes content to the file. If the file does not exist, this method will create the file, write to the file, and then close the file. /// </summary> /// <param name="file">The file.</param> /// <param name="contents">The contents.</param> /// <param name="writeMode">The write mode.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A boolean task to write to the file. The boolean represents whether the contents were written or not.</returns> public static async Task<bool> WriteAllTextAsync(AFile file, string contents, WriteMode writeMode = WriteMode.Truncate, CancellationToken? cancellationToken = null) { await AwaitHelpers.CreateTaskScheduler(AwaitHelpers.CheckCancellationToken(cancellationToken)); return WriteAllText(file, contents, writeMode); }
/// <summary> /// Asynchronously reads the entire file and returns the contents as a byte array. /// </summary> /// <param name="file">The file.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A byte array task to read the file. The byte array represents the contents of the file.</returns> public static async Task<byte[]> ReadAllBytesAsync(AFile file, CancellationToken? cancellationToken = null) { await AwaitHelpers.CreateTaskScheduler(AwaitHelpers.CheckCancellationToken(cancellationToken)); return ReadAllBytes(file); }
/// <summary> /// Deletes the specified file. /// </summary> /// <param name="file">The file.</param> /// <returns>Whether the file was deleted or not.</returns> public static bool Delete(AFile file) { Exceptions.NotNullException<AFile>(file, nameof(file)); return file.Delete(); }
/// <summary> /// Asynchronously returns whether the specified file exists. /// </summary> /// <param name="file">The file.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A boolean task to check file existence. The boolean represents whether the file exists or not.</returns> public static async Task<bool> ExistsAsync(AFile file, CancellationToken? cancellationToken = null) { await AwaitHelpers.CreateTaskScheduler(AwaitHelpers.CheckCancellationToken(cancellationToken)); return Exists(file); }
/// <summary> /// Opens the specified file with the file access. /// </summary> /// <param name="file">The file.</param> /// <param name="fileAccess">The file access.</param> /// <param name="fileMode">The file mode.</param> /// <returns>The stream representing the opened file.</returns> public static Stream Open(AFile file, FileAccess fileAccess = FileAccess.ReadWrite, FileMode fileMode = FileMode.OpenOrCreate) { Exceptions.NotNullException<AFile>(file, nameof(file)); return file.Open(fileAccess, fileMode); }
/// <summary> /// Asynchronously moves the specified file to the destination. /// </summary> /// <param name="source">The source.</param> /// <param name="destination">The destination.</param> /// <param name="overwrite">if set to <c>true</c> [overwrite].</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A boolean task to move the file. The boolean represents whether the file was moved or not.</returns> public static async Task<bool> MoveAsync(AFile source, AFile destination, bool overwrite = false, CancellationToken? cancellationToken = null) { await AwaitHelpers.CreateTaskScheduler(AwaitHelpers.CheckCancellationToken(cancellationToken)); return Move(source, destination, overwrite); }
/// <summary> /// Asynchronously appends lines to a file. If the file doesn't exist, this method creates the file, writes the lines to the it, and then closes the it. /// </summary> /// <param name="file">The file.</param> /// <param name="contents">The contents.</param> /// <param name="cancellationToken">The cancellation token. Defaults to null.</param> /// <returns>A boolean task to append lines to the file. The boolean represents whether the write was successful or not.</returns> public static async Task<bool> AppendAllLinesAsync(AFile file, IEnumerable<string> contents, CancellationToken? cancellationToken = null) { await AwaitHelpers.CreateTaskScheduler(AwaitHelpers.CheckCancellationToken(cancellationToken)); return AppendAllLines(file, contents); }
/// <summary> /// Moves the specified file to the destination. /// </summary> /// <param name="source">The source.</param> /// <param name="destination">The destination.</param> /// <param name="overwrite">if set to <c>true</c> [overwrite].</param> /// <returns>Whether the file was moved or not.</returns> public static bool Move(AFile source, AFile destination, bool overwrite = false) { Exceptions.NotNullException<AFile>(source, nameof(source)); Exceptions.NotNullException<AFile>(destination, nameof(destination)); if ((!overwrite && Fenrir.FileSystem.FileExists(destination.FullPath)) || !Fenrir.FileSystem.FileExists(source.FullPath)) return false; return source.Move(destination.FullPath, FileCollisionOption.ReplaceExisting); }
/// <summary> /// Asynchronously gets the UTC last modified time of the file. /// </summary> /// <param name="file">The file.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A DateTime task to get the last modified time. The time represents the time the file was last modified.</returns> public static async Task<DateTime> GetLastModifiedTimeUtcAsync(AFile file, CancellationToken? cancellationToken = null) { await AwaitHelpers.CreateTaskScheduler(AwaitHelpers.CheckCancellationToken(cancellationToken)); return GetLastModifiedTimeUtc(file); }
/// <summary> /// Gets the UTC last modified time of the file. /// </summary> /// <param name="file">The file.</param> /// <returns>The time the file was last accessed.</returns> public static DateTime GetLastModifiedTimeUtc(AFile file) { Exceptions.NotNullException<AFile>(file, nameof(file)); return file.LastModifiedTimeUtc; }
/// <summary> /// Reads the entire file and returns the contents as a string. /// </summary> /// <param name="file">The file.</param> /// <returns>A string representing the contents of the file.</returns> public static string ReadAllText(AFile file) { Exceptions.NotNullException<AFile>(file, nameof(file)); return file.ReadAll(); }
/// <summary> /// Reads the entire file and returns the contents as a string array, with each item representing a different line. /// </summary> /// <param name="file">The file.</param> /// <returns>A string array representing the contents of the file.</returns> public static string[] ReadAllLines(AFile file) { Exceptions.NotNullException<AFile>(file, nameof(file)); return file.ReadAllLines(); }
/// <summary> /// Writes content to the file. If the file does not exist, this method will create the file, write to the file, and then close the file. /// </summary> /// <param name="file">The file.</param> /// <param name="contents">The contents.</param> /// <param name="writeMode">The write mode.</param> /// <returns>Whether the contents were written or not.</returns> public static bool WriteAllLines(AFile file, List<string> contents, WriteMode writeMode = WriteMode.Truncate) { Exceptions.NotNullException<AFile>(file, nameof(file)); Exceptions.NotNullException<List<string>>(contents, nameof(contents)); var str = new StringBuilder(); foreach (var line in contents) str.AppendLine(line); return file.WriteAll(str.ToString(), writeMode); }
/// <summary> /// Copies the file at the source to the destination. /// </summary> /// <param name="source">The source.</param> /// <param name="destination">The destination.</param> /// <param name="overwrite">if set to <c>true</c> [overwrite]. By default, is set to false (do not overwrite the destination file).</param> /// <returns>Whether the copy was successful or not.</returns> public static bool Copy(AFile source, string destination, bool overwrite = false) { Exceptions.NotNullException<AFile>(source, nameof(source)); Exceptions.NotNullOrEmptyException(destination, nameof(destination)); if ((!overwrite && Fenrir.FileSystem.FileExists(destination)) || !Fenrir.FileSystem.FileExists(source.FullPath)) return false; return source.Copy(destination, FileCollisionOption.ReplaceExisting) != null; }
/// <summary> /// Returns whether the specified file exists. /// </summary> /// <param name="file">The file.</param> /// <returns>Whether the file exists or not.</returns> public static bool Exists(AFile file) { Exceptions.NotNullException<AFile>(file, nameof(file)); return Fenrir.FileSystem.FileExists(file.FullPath); }
/// <summary> /// Reads the entire file and returns the contents as a byte array. /// </summary> /// <param name="file">The file.</param> /// <returns>A byte array representing the contents of the file.</returns> public static byte[] ReadAllBytes(AFile file) { Exceptions.NotNullException<AFile>(file, nameof(file)); var output = new byte[0]; if (!file.IsOpen) file.Open(FileAccess.Read, FileMode.Open); long length = file.Stream.Length; long position = 0; output = new byte[length]; var tmp = new byte[0]; while (length > 0) { var tmpLength = (int)(Int32.MaxValue - length); if (tmpLength < 0) tmpLength = (int)length; tmp = new byte[tmpLength]; file.Stream.Read(tmp, 0, tmpLength); for (int i = 0; i < tmpLength; i++) output[position++] = tmp[i]; length -= tmpLength; } return output; }
/// <summary> /// Asynchronously appends text to a file. If the file doesn't exist, this method creates the file, writes the text to the it, and then closes the it. /// </summary> /// <param name="file">The file.</param> /// <param name="contents">The contents.</param> /// <param name="cancellationToken">The cancellation token. Defaults to null.</param> /// <returns>A boolean task to append lines to the file. The boolean represents whether the write was successful or not.</returns> public static async Task<bool> AppendAllTextAsync(AFile file, string contents, CancellationToken? cancellationToken = null) { await AwaitHelpers.CreateTaskScheduler(AwaitHelpers.CheckCancellationToken(cancellationToken)); return AppendAllText(file, contents); }
/// <summary> /// Asynchronously opens the file for appending. If the file does not exist, this method will create the file and then open it for appending. /// </summary> /// <param name="file">The file.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A Stream task to open the file for appending. The Stream is for appending text to the file.</returns> public static async Task<Stream> AppendTextAsync(AFile file, CancellationToken? cancellationToken = null) { await AwaitHelpers.CreateTaskScheduler(AwaitHelpers.CheckCancellationToken(cancellationToken)); return AppendText(file); }
/// <summary> /// Asynchronously reads the entire file and returns the contents as a string list, with each item representing a different line. /// </summary> /// <param name="file">The file.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A string list task to read all lines in the file. The string list represents the contents of the file.</returns> public static async Task<List<string>> ReadLinesListAsync(AFile file, CancellationToken? cancellationToken = null) { await AwaitHelpers.CreateTaskScheduler(AwaitHelpers.CheckCancellationToken(cancellationToken)); return ReadLinesList(file); }
/// <summary> /// Asynchronously opens the specified file with the file access. /// </summary> /// <param name="file">The file.</param> /// <param name="fileAccess">The file access.</param> /// <param name="fileMode">The file mode.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A Stream task to open the file. The stream represents the opened file.</returns> public static async Task<Stream> OpenAsync(AFile file, FileAccess fileAccess = FileAccess.ReadWrite, FileMode fileMode = FileMode.OpenOrCreate, CancellationToken? cancellationToken = null) { await AwaitHelpers.CreateTaskScheduler(AwaitHelpers.CheckCancellationToken(cancellationToken)); return Open(file, fileAccess, fileMode); }
/// <summary> /// Writes content to the file. If the file does not exist, this method will create the file, write to the file, and then close the file. /// </summary> /// <param name="file">The file.</param> /// <param name="contents">The contents.</param> /// <param name="writeMode">The write mode.</param> /// <returns>Whether the contents were written or not.</returns> public static bool WriteAllBytes(AFile file, byte[] contents, WriteMode writeMode = WriteMode.Truncate) { Exceptions.NotNullException<AFile>(file, nameof(file)); Exceptions.NotNullException<byte[]>(contents, nameof(contents)); return file.WriteAll(Convert.ToString(contents), writeMode); }
/// <summary> /// Asynchronously replaces the contents of the destination file (if it exists) with the contents of the source file, making a backup of the original destination file (if it exists). If the file doesn't exist, this copies the source file to the destination. /// </summary> /// <param name="source">The source.</param> /// <param name="destination">The destination.</param> /// <param name="backup">The backup.</param> /// <param name="overwriteBackup">if set to <c>true</c>, will overwrite the backup file if it already exists.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A boolean task to do the replace. The boolean represents whether the replace was successful or not.</returns> public static async Task<bool> ReplaceAsync(AFile source, AFile destination, AFile backup, bool overwriteBackup = true, CancellationToken? cancellationToken = null) { await AwaitHelpers.CreateTaskScheduler(AwaitHelpers.CheckCancellationToken(cancellationToken)); return Replace(source, destination, backup, overwriteBackup); }
/// <summary> /// Replaces the contents of the destination file (if it exists) with the contents of the source file, making a backup of the original destination file (if it exists). If the file doesn't exist, this copies the source file to the destination. /// </summary> /// <param name="source">The source.</param> /// <param name="destination">The destination.</param> /// <param name="backup">The backup.</param> /// <param name="overwriteBackup">if set to <c>true</c>, will overwrite the backup file if it already exists.</param> /// <returns>Whether the replace was successful or not.</returns> public static bool Replace(AFile source, AFile destination, AFile backup, bool overwriteBackup = true) { Exceptions.NotNullException<AFile>(source, nameof(source)); Exceptions.NotNullException<AFile>(destination, nameof(destination)); Exceptions.NotNullException<AFile>(backup, nameof(backup)); Copy(destination, backup, overwriteBackup); return Copy(source, destination, true); }
/// <summary> /// Gets the UTC creation time of the file. /// </summary> /// <param name="file">The file.</param> /// <returns>The time the file was created.</returns> public static DateTime GetCreationTimeUtc(AFile file) { Exceptions.NotNullException<AFile>(file, nameof(file)); return file.CreationTimeUtc; }
/// <summary> /// Opens the file for appending. If the file does not exist, this method will create the file and then open it for appending. /// </summary> /// <param name="file">The file.</param> /// <returns>A Stream for appending text to the file.</returns> public static Stream AppendText(AFile file) { Exceptions.NotNullException<AFile>(file, nameof(file)); return file.Open(FileAccess.Write, FileMode.Append); }