private void WriteNumber(long value) { //TODO: Optimize, this is too slow var buffer = _bufferWriter.GetSpan(); int written; while (!CustomFormatter.TryFormat(value, buffer, out written, JsonConstants.NumberFormat, SymbolTable.InvariantUtf16)) { buffer = EnsureBuffer(); } _bufferWriter.Advance(written); }
public Server(String serverAddress, int serverPort) { this.serverPort = serverPort; this.serverAddr = IPAddress.Parse(serverAddress); this.serverSocket = new TcpListener(serverAddr, serverPort); this.serverSocket.Start(); this.isRunning = true; this.formatter = new CustomFormatter(); Console.WriteLine("Server is working at port: " + serverPort); waitForClients(); }
public bool TryFormat(Span <byte> buffer, out int bytesWritten, StandardFormat format, SymbolTable symbolTable) { if (!CustomFormatter.TryFormat(_age, buffer, out bytesWritten, format, symbolTable)) { return(false); } char symbol = _inMonths ? 'm' : 'y'; if (!symbolTable.TryEncode((byte)symbol, buffer.Slice(bytesWritten), out int written)) { return(false); } bytesWritten += written; return(true); }
internal SqlClassifier(ITagAggregator <StringTag> tagger, IClassificationTypeRegistryService classificationRegistry) { this.tagger = tagger; keywordType = classificationRegistry.GetClassificationType("sql-keyword"); operatorType = classificationRegistry.GetClassificationType("sql-operator"); stringType = classificationRegistry.GetClassificationType("sql-string"); functionType = classificationRegistry.GetClassificationType("sql-function"); numberType = classificationRegistry.GetClassificationType("sql-number"); parameterType = classificationRegistry.GetClassificationType("sql-parameter"); commentType = classificationRegistry.GetClassificationType("sql-comment"); formatter = new CustomFormatter(); tokenizer = new TSqlStandardTokenizer(); parser = new TSqlStandardParser(); }
public static void Main(String[] args) { GetNumericValue.Go(); CharConvert.Go(); ComparingStringForEquality.Go(); ComparingStringsForSorting.Go(); Interning.Go(); UsingStringInfo.Go(); UsingStringBuilder.Go(); Formatting.Go(); CustomFormatter.Go(); Encodings.Go(); EncodingProperties.Go(); CodePageConverter.Go(args); Base64Encoding.Go(); UsingSecureString.Go(); }
public void SelfControlSerializationTest() { ISerializable _objectToSerialize = new SelfControlSerialization(987654321.123, 123456789.987); CustomFormatter _formatter = new CustomFormatter(); const string _fileName = "test.xml"; File.Delete(_fileName); using (Stream _stream = new FileStream("test.xml", FileMode.Create)) _formatter.Serialize(_stream, _objectToSerialize); FileInfo _info = new FileInfo(_fileName); Assert.IsTrue(_info.Exists); Assert.IsTrue(_info.Length >= 100, $"The file length is {_info.Length }"); string _fileContent = File.ReadAllText(_fileName, Encoding.UTF8); Debug.Write(_fileContent); }
static void EnumerateProcessesTwice() { var provider = new CustomFormatter { }; var entries = Toolhelp32.TakeSnapshot <WinProcessEntry>(Toolhelp32.SnapProcess, 0); foreach (var x in entries) { Debug.WriteLine(String.Format(provider, "1 .. {0}", x)); } // Snapshot disposed and created again foreach (var x in entries) { Debug.WriteLine(String.Format(provider, "2 .. {0}", x)); } }
public static bool TryFormat(float value, Span <byte> buffer, out int bytesWritten, StandardFormat format = default, SymbolTable symbolTable = null) { if (format.IsDefault) { format = 'G'; } symbolTable = symbolTable ?? SymbolTable.InvariantUtf8; switch (format.Symbol) { case 'G': return(CustomFormatter.TryFormatNumber(value, true, buffer, out bytesWritten, format, symbolTable)); default: throw new NotSupportedException(); } }
public void AllFormats() { var formatter = CustomFormatter.Default() .Add <CaseFormatter>() .Add <BracketFormatter>() .Add <QuoteFormatter>() .Add <DecimalColorFormatter>() .Add <HexadecimalColorFormatter>(); var text = "foo {a:double} {b:square} {c:u}".Format(new { a = "bar", b = "baz", c = "qux" }, formatter); Assert.AreEqual("foo \"bar\" [baz] QUX", text); }
public void WhenExceptinOccursInCustomFormater1() { string filename = "customFormatterException.log"; File.Delete(filename); var logger = MockEventSource.Logger; var formatter = new CustomFormatter(true); TestScenario.With1Listener( logger, (listener, errorsListener) => { listener.LogToFlatFile(filename, formatter); listener.EnableEvents(logger, EventLevel.LogAlways, Keywords.All); logger.LogSomeMessage("testing"); errorsListener.WaitEvents.Wait(3000); StringAssert.Contains(errorsListener.ToString(), "unhandled exception from formatter"); }); }
static void TestDateTimeFormat(DateTime dt, char format, SymbolTable symbolTable) { string expected; if (format == 'l') { expected = dt.ToString("R", CultureInfo.InvariantCulture).ToLowerInvariant(); } else { expected = dt.ToString(format.ToString(), CultureInfo.InvariantCulture); } var span = new Span <byte>(new byte[256]); Assert.True(CustomFormatter.TryFormat(dt, span, out int written, format, symbolTable)); var actual = TestHelper.SpanToString(span.Slice(0, written), symbolTable); Assert.Equal(expected, actual); }
public void CustomFormatterTest_v2() { Class1 class1 = new Class1(2.5f, DateTime.Now, "klasa 1"); Class2 class2 = new Class2(7.5f, DateTime.Now.AddDays(5), "klasa 2"); Class3 class3 = new Class3(12.2f, DateTime.Now.AddMonths(2), "klasa 3"); Class1 class1_1 = new Class1(0.5f, DateTime.Now.AddDays(8), "klasa 1_1"); class1.obj = class2; class2.obj = class3; class3.obj = class1; class1_1.obj = class2; CustomFormatter cs = new CustomFormatter(); FileStream a = new FileStream("plik2.txt", FileMode.Create); cs.Serialize(a, class1_1); a.Flush(); a.Close(); Class1 class1_1prim = cs.Deserialize(new FileStream("plik2.txt", FileMode.Open)) as Class1; Assert.AreEqual(class1_1.num, class1_1prim.num); Assert.AreEqual(class1_1.date.Date, class1_1prim.date.Date); Assert.AreEqual(class1_1.date.Hour, class1_1prim.date.Hour); Assert.AreEqual(class1_1.date.Minute, class1_1prim.date.Minute); Assert.AreEqual(class1_1.date.Second, class1_1prim.date.Second); Assert.AreEqual(class1_1.name, class1_1prim.name); Assert.AreEqual(class1_1.obj.num, class1_1prim.obj.num); Assert.AreEqual(class1_1.obj.date.Date, class1_1prim.obj.date.Date); Assert.AreEqual(class1_1.obj.date.Hour, class1_1prim.obj.date.Hour); Assert.AreEqual(class1_1.obj.date.Minute, class1_1prim.obj.date.Minute); Assert.AreEqual(class1_1.obj.date.Second, class1_1prim.obj.date.Second); Assert.AreEqual(class1_1.obj.name, class1_1prim.obj.name); Assert.AreEqual(class1_1.obj.obj.num, class1_1prim.obj.obj.num); Assert.AreEqual(class1_1.obj.obj.date.Date, class1_1prim.obj.obj.date.Date); Assert.AreEqual(class1_1.obj.obj.date.Hour, class1_1prim.obj.obj.date.Hour); Assert.AreEqual(class1_1.obj.obj.date.Minute, class1_1prim.obj.obj.date.Minute); Assert.AreEqual(class1_1.obj.obj.date.Second, class1_1prim.obj.obj.date.Second); Assert.AreEqual(class1_1.obj.obj.name, class1_1prim.obj.obj.name); }
static void TestDateTimeOffsetFormat(DateTimeOffset dto, char formatChar, SymbolTable symbolTable) { ParsedFormat format = (formatChar == 0) ? default(ParsedFormat) : formatChar; string expected; if (formatChar == 'l') { expected = dto.ToString("R", CultureInfo.InvariantCulture).ToLowerInvariant(); } else { expected = (format.IsDefault) ? dto.ToString(CultureInfo.InvariantCulture) : dto.ToString(formatChar.ToString(), CultureInfo.InvariantCulture); } var span = new Span <byte>(new byte[256]); Assert.True(CustomFormatter.TryFormat(dto, span, out int written, format, symbolTable)); var actual = TestHelper.SpanToString(span.Slice(0, written), symbolTable); Assert.Equal(expected, actual); }
public void TestInitialize() { classA = new ClassA("claaasdassA", 2684132, true); classB = new ClassB("cldsadsaassB", 13216549, 777.2); classC = new ClassC("dsadsadsa", 1354987); classA.ClassB = classB; classA.ClassC = classC; classB.ClassA = classA; classB.ClassC = classC; classC.ClassA = classA; classC.ClassB = classB; bookshelf = new Bookshelf( new List <Book> { new Book("123-456", 9.9), new Book("987-654", 1.1) }, new BookGenres[] { new BookGenres("Drama"), new BookGenres("Action"), new BookGenres("Poetry") } ); customFormatter = new CustomFormatter(); }
public static string Write <T>(IEnumerable <T> enumerable, CustomFormatter <T> formatter) { return(Write(enumerable, (i, s) => formatter(s) + Environment.NewLine, "Empty")); }
public static string Write <T>(IEnumerable <T> enumerable, CustomFormatter <T> formatter) { return(Write(enumerable, (i, s) => formatter(s), "Empty")); }
public Client() { clientSocket = new TcpClient(); customFormatter = new CustomFormatter(); }
/************************************************************************************/ protected virtual bool OnCustomSlashCommand(string strCommand, string[] astrParameters) { string strCondensedParameters = string.Join(" ", astrParameters).Trim(); switch (strCommand) { case "gc_assist": { Actor OffensiveTargetActor = GetNestedCombatAssistTarget(astrParameters[0]); if (OffensiveTargetActor != null) { OffensiveTargetActor.DoTarget(); } return(true); } /// Directly acquire an offensive target. case "gc_attack": { Actor MyTargetActor = MeActor.Target(); if (MyTargetActor.IsValid) { /// Don't bother filtering. Just grab the ID, let the other code determine if it's a legit target. m_iOffensiveTargetID = MyTargetActor.ID; Program.Log("Offensive target set to \"{0}\" ({1}).", MyTargetActor.Name, m_iOffensiveTargetID); } else { Program.Log("Invalid target selected."); } return(true); } /// This is the assist call; direct the bot to begin combat. /// Essentially combines gc_assist and gc_attack. case "gc_attackassist": { if (astrParameters.Length != 1) { Program.Log("gc_attackassist: Missing name of player to assist!"); return(true); } /// Force a recalculation. m_OffensiveTargetEncounterActorDictionary.Clear(); Actor OffensiveTargetActor = GetNestedCombatAssistTarget(astrParameters[0]); if (OffensiveTargetActor == null) { /// Combat is now cancelled. /// Maybe the commanding player misclicked or clicked off intentionally, but it doesn't matter. WithdrawFromCombat(); } else { /// Successful target acquisition. m_iOffensiveTargetID = OffensiveTargetActor.ID; Program.Log("New offensive target: {0}", OffensiveTargetActor.Name); /// An assist command promotes AFK into neutral positioning. if (m_ePositioningStance == PositioningStance.DoNothing) { ChangePositioningStance(PositioningStance.NeutralPosition); } } return(true); } /// Begin dropping all group buffs. case "gc_cancelgroupbuffs": { Program.Log("Cancelling all maintained group effects..."); m_bClearGroupMaintained = true; return(true); } /// Arbitrarily change an INI setting on the fly. case "gc_changesetting": { string strKey = string.Empty; string strValue = string.Empty; int iEqualsPosition = strCondensedParameters.IndexOf(" "); if (iEqualsPosition == -1) { strKey = strCondensedParameters; } else { strKey = strCondensedParameters.Substring(0, iEqualsPosition).TrimEnd(); strValue = strCondensedParameters.Substring(iEqualsPosition + 1).TrimStart(); } if (!string.IsNullOrEmpty(strKey)) { Program.Log("Changing setting \"{0}\" to new value \"{1}\"...", strKey, strValue); IniFile FakeIniFile = new IniFile(); FakeIniFile.WriteString(strKey, strValue); FakeIniFile.Mode = IniFile.TransferMode.Read; TransferINISettings(FakeIniFile); ApplySettings(); } return(true); } case "gc_debug": { if (astrParameters.Length == 0) { Program.Log("gc_debug: No option specified!"); return(true); } switch (astrParameters[0]) { case "whopet": Program.Log("gc_debug whopet: Listing player's primary pet..."); FlexStringBuilder ThisBuilder = new FlexStringBuilder(); AppendActorInfo(ThisBuilder, 1, Me.Pet()); Program.Log("{0}", ThisBuilder.ToString()); return(true); case "fullaffinities": Program.Log("Attempting to remove all affinity constraints on the process and its threads..."); uint uiCurrentProcessID = KERNEL32.GetCurrentProcessId(); IntPtr hProcess = KERNEL32.OpenProcess(KERNEL32.ProcessAccess.SetInformation | KERNEL32.ProcessAccess.QueryInformation, false, uiCurrentProcessID); if (hProcess == KERNEL32.INVALID_HANDLE_VALUE) { Program.Log("Unable to open process {0}.", uiCurrentProcessID); return(true); } UIntPtr uiProcessAffinityMask; UIntPtr uiSystemProcessorMask; KERNEL32.GetProcessAffinityMask(hProcess, out uiProcessAffinityMask, out uiSystemProcessorMask); Program.Log("Process {0} previous affinity mask: 0x{1:X8}", uiCurrentProcessID, uiProcessAffinityMask); KERNEL32.SetProcessAffinityMask(hProcess, uiSystemProcessorMask); KERNEL32.CloseHandle(hProcess); Program.Log("Attempting to remove all affinity constraints on the process threads..."); foreach (KERNEL32.THREADENTRY32 ThisThread in KERNEL32.EnumProcessThreads(uiCurrentProcessID)) { IntPtr hThread = KERNEL32.OpenThread(KERNEL32.ThreadAccess.SetInformation | KERNEL32.ThreadAccess.QueryInformation, false, ThisThread.th32ThreadID); if (hThread != IntPtr.Zero) { UIntPtr uiOldThreadAffinityMask = KERNEL32.SetThreadAffinityMask(hThread, uiSystemProcessorMask); Program.Log("Thread {0} previous affinity mask: 0x{1:X8}", ThisThread.th32ThreadID, uiOldThreadAffinityMask); KERNEL32.CloseHandle(hThread); } else { Program.Log("Can't open thread {0}.", ThisThread.th32ThreadID); } } return(true); case "memstat": Process CurrentProcess = Process.GetCurrentProcess(); Program.Log("Virtual Allocation: {0}", CustomFormatter.FormatByteCount(CurrentProcess.VirtualMemorySize64, "0.00")); Program.Log("Working Set: {0}", CustomFormatter.FormatByteCount(CurrentProcess.WorkingSet64, "0.00")); Program.Log(".NET Heap Allocation: {0}", CustomFormatter.FormatByteCount(GC.GetTotalMemory(false), "0.00")); Program.Log("Threads: {0}", CurrentProcess.Threads.Count); return(true); } Program.Log("Usage: gc_debug (whopet|fullaffinities|memstat)"); return(true); } case "gc_defaultverb": { string strActorName = strCondensedParameters; Actor IntendedTargetActor = null; /// Grab the targetted actor. if (string.IsNullOrEmpty(strActorName)) { Actor CurrentTargetActor = MeActor.Target(); if (CurrentTargetActor.IsValid) { IntendedTargetActor = CurrentTargetActor; } } /// Grab the so-named actor nearest to the commander. else { double fNearestDistance = 50.0; foreach (Actor ThisActor in EnumActors(strActorName)) { if (ThisActor.Name != strActorName) { continue; } double fThisDistance = ThisActor.Distance; if (fThisDistance < fNearestDistance) { fNearestDistance = fThisDistance; IntendedTargetActor = ThisActor; } } } /// No such actor found. if (IntendedTargetActor == null) { Program.Log("gc_defaultverb: actor not found."); } else { Program.Log("gc_defaultverb: Attempting to apply default verb on actor \"{0}\" ({1}).", strActorName, IntendedTargetActor.ID); IntendedTargetActor.DoubleClick(); } return(true); } case "gc_distance": { Actor MyTargetActor = MeActor.Target(); if (MyTargetActor.IsValid) { string strOutput = string.Format("Distance to target \"{0}\" ({1}): {2} meter(s).", MyTargetActor.Name, MyTargetActor.ID, MyTargetActor.Distance); RunCommand("/announce {0}", strOutput); Program.Log(strOutput); } return(true); } case "gc_dumpabilities": { /// Dump all abilities to a .CSV file specified as a parameter, on the next knowledge book refresh. s_strKnowledgeBookDumpPath = strCondensedParameters; s_bRefreshKnowledgeBook = true; return(true); } case "gc_exit": { Program.Log("Exit command received!"); s_bContinueBot = false; return(true); } case "gc_exitprocess": { Process.GetCurrentProcess().Kill(); return(true); } case "gc_findactor": { string strSearchString = strCondensedParameters.ToLower(); TrackNearestActors(5, true, strSearchString); return(true); } case "gc_openini": { Program.SafeShellExecute(s_strCurrentINIFilePath); return(true); } case "gc_openoverridesini": { Program.SafeShellExecute(s_strSharedOverridesINIFilePath); return(true); } case "gc_reloadsettings": { ReadINISettings(); ReleaseAllKeys(); /// If there's a bug, this will cure it. If not, no loss. s_bRefreshKnowledgeBook = true; return(true); } case "gc_stance": { if (astrParameters.Length < 1) { Program.Log("gc_stance failed: Missing stance parameter."); return(true); } string strStance = astrParameters[0].ToLower(); switch (strStance) { case "afk": Program.Log("Now ignoring all non-stance commands."); ChangePositioningStance(PositioningStance.DoNothing); break; case "customfollow": m_fCurrentMovementTargetCoordinateTolerance = m_fCustomAutoFollowMaximumRange; m_strPositionalCommandingPlayer = GetFirstExistingPartyMember(m_astrAutoFollowTargets, false); ChangePositioningStance(PositioningStance.CustomAutoFollow); break; case "shadow": m_fCurrentMovementTargetCoordinateTolerance = m_fStayInPlaceTolerance; m_strPositionalCommandingPlayer = GetFirstExistingPartyMember(m_astrAutoFollowTargets, false); ChangePositioningStance(PositioningStance.CustomAutoFollow); break; case "normal": case "follow": Program.Log("Positioning is now regular auto-follow."); ChangePositioningStance(PositioningStance.AutoFollow); break; case "neutral": Program.Log("Positioning is now neutral."); ChangePositioningStance(PositioningStance.NeutralPosition); break; case "dash": Program.Log("Dashing forward."); ChangePositioningStance(PositioningStance.ForwardDash); break; case "stay": Program.Log("Locking position to where the commanding player is now standing."); m_strPositionalCommandingPlayer = GetFirstExistingPartyMember(m_astrAutoFollowTargets, false); ChangePositioningStance(PositioningStance.StayInPlace); break; case "stayat": if (astrParameters.Length >= 4) { Point3D NewSpot = new Point3D(); if (double.TryParse(astrParameters[1], out NewSpot.X) && double.TryParse(astrParameters[2], out NewSpot.Y) && double.TryParse(astrParameters[3], out NewSpot.Z)) { m_strPositionalCommandingPlayer = string.Empty; m_ptStayLocation = NewSpot; ChangePositioningStance(PositioningStance.StayInPlace); } else { Program.Log("Bad coordinate input format."); } } else { Program.Log("You need 3 values to form a 3-D coordinate, but you specified {0}.", astrParameters.Length - 1); } break; case "stayself": Program.Log("Locking position to where you are now standing."); m_strPositionalCommandingPlayer = Name; ChangePositioningStance(PositioningStance.StayInPlace); break; default: Program.Log("Stance not recognized."); break; } return(true); } case "gc_spawnwatch": { m_bSpawnWatchTargetAnnounced = false; m_strSpawnWatchTarget = strCondensedParameters.ToLower().Trim(); Program.Log("Bot will now scan for actor \"{0}\".", m_strSpawnWatchTarget); ChangePositioningStance(PositioningStance.SpawnWatch); return(true); } /// A super-powerful direct targetter. case "gc_target": { Actor TargetActor = null; string strSearchString = strCondensedParameters.ToLower(); /// If they give an actual actor ID, then that's awesome. int iActorID = -1; if (int.TryParse(strSearchString, out iActorID)) { TargetActor = GetActor(iActorID); } else { foreach (Actor ThisActor in EnumActors()) { if (ThisActor.Name.ToLower().Contains(strSearchString)) { TargetActor = ThisActor; break; } } } if (TargetActor != null) { TargetActor.DoTarget(); } return(true); } /// Update the waypoint at a regular interval with the nearest location of an actor search string. case "gc_trackactor": { if (astrParameters.Length < 1) { Program.Log("gc_trackactor failed: Missing parameter."); return(true); } string strInterval = astrParameters[0].Trim().ToLower(); if (strInterval == "off") { RunCommand("/waypoint_cancel"); Program.Log("Actor tracking mode disabled."); m_bTrackActor = false; return(true); } double fIntervalSeconds = 0; if (!double.TryParse(strInterval, out fIntervalSeconds) || fIntervalSeconds < 0.0) { Program.Log("gc_trackactor failed: Invalid interval parameter."); return(false); } List <string> astrRemainingParameters = new List <string>(astrParameters); if (astrRemainingParameters.Count > 0) { astrRemainingParameters.RemoveAt(0); } string strRemainingCondensedParameters = string.Join(" ", astrRemainingParameters.ToArray()).Trim().ToLower(); /// Now we turn the mode on. m_TrackActorInterval = TimeSpan.FromSeconds(fIntervalSeconds); m_NextTrackActorAttemptTime = CurrentCycleTimestamp; m_strTrackActorSubstring = strRemainingCondensedParameters; m_bTrackActor = true; return(true); } /// Test the text-to-speech synthesizer using the current settings. case "gc_tts": { SayText(strCondensedParameters); return(true); } case "gc_version": { Program.DisplayVersion(); Program.Log("ISXEQ2 Version: " + s_ISXEQ2.Version); return(true); } /// Clear the offensive target. case "gc_withdraw": { Program.Log("Offensive target withdrawn."); WithdrawFromCombat(); return(true); } } return(false); }
static void Main(string[] args) { ClassA classA = new ClassA("classA", 789654, true); ClassB classB = new ClassB("classB", 123456897, 777); ClassC classC = new ClassC("classC", 98765188); classA.ClassB = classB; classA.ClassC = classC; classB.ClassA = classA; classB.ClassC = classC; classC.ClassA = classA; classC.ClassB = classB; Bookshelf bookshelf = new Bookshelf( new List <Book> { new Book("123-456", 9.9), new Book("987-654", 1.1) }, new BookGenres[] { new BookGenres("Drama"), new BookGenres("Action"), new BookGenres("Poetry") } ); CustomFormatter customFormatter; Console.WriteLine("Wciśnij:"); Console.WriteLine("1 - by zapisać stan programu w pliku JSON - ClassA"); Console.WriteLine("2 - by zapisać stan programu w pliku JSON - Bookshelf"); Console.WriteLine("3 - by zapisać stan programu własną metodą - ClassA"); Console.WriteLine("4 - by zapisać stan programu własną metodą - Bookshelf"); Console.WriteLine("5 - by wczytać stan programu z pliku JSON - ClassA"); Console.WriteLine("6 - by wczytać stan programu z pliku JSON - Bookshelf"); Console.WriteLine("7 - by wczytać stan programu własną metodą - ClassA"); Console.WriteLine("8 - by wczytać stan programu własną metodą - Bookshelf"); Console.WriteLine("9 - by wyłączyć program"); string option = "10"; string filePath; while (option != "9") { customFormatter = new CustomFormatter(); option = Console.ReadLine(); switch (option) { case "1": filePath = "..\\..\\..\\..\\TestResults\\jsonFileClassA.json"; JsonSerializer.Serialize(classA, filePath); break; case "2": filePath = "..\\..\\..\\..\\TestResults\\jsonFileBookshelf.json"; JsonSerializer.Serialize(bookshelf, filePath); break; case "3": filePath = "..\\..\\..\\..\\TestResults\\CustomSerializationClassA.txt"; using (Stream stream = new FileStream(filePath, FileMode.Create)) { customFormatter.Serialize(stream, classA); } break; case "4": filePath = "..\\..\\..\\..\\TestResults\\CustomSerializationBookshelf.txt"; using (Stream stream = new FileStream(filePath, FileMode.Create)) { customFormatter.Serialize(stream, bookshelf); } break; case "5": filePath = "..\\..\\..\\..\\TestResults\\jsonFileClassA.json"; ClassA classADeserialized = JsonSerializer.Deserialize <ClassA>(filePath); break; case "6": filePath = "..\\..\\..\\..\\TestResults\\jsonFileBookshelf.json"; Bookshelf bookshelfDeserialized = JsonSerializer.Deserialize <Bookshelf>(filePath); break; case "7": filePath = "..\\..\\..\\..\\TestResults\\CustomSerializationClassA.txt"; using (Stream stream = new FileStream(filePath, FileMode.Open)) { ClassA deserialized = (ClassA)customFormatter.Deserialize(stream); } break; case "8": filePath = "..\\..\\..\\..\\TestResults\\CustomSerializationBookshelf.txt"; using (Stream stream = new FileStream(filePath, FileMode.Open)) { Bookshelf deserialized = (Bookshelf)customFormatter.Deserialize(stream); } break; default: break; } } }
/// <summary> /// 格式化字符串,与<see cref="T:String.Format" />拥有相同的格式化说明 /// </summary> /// <param name="me">格式化说明</param> /// <param name="args">可以使用的参数</param> /// <param name="format">自定义的格式化委托<see cref="CustomFormatter" /></param> /// <param name="throwable">在参数不存在的情况下是否抛出异常,默认抛出</param> /// <returns>经过格式化后的字符串</returns> /// <example>"{参数,宽度(-前导为左对齐):格式化字符串}"</example> public static string Format(this string me, Data args, CustomFormatter format, bool throwable = true) { //Thrower.NullThrow(me, nameof(me)); if (string.IsNullOrEmpty(me)) { throw new ArgumentNullException(nameof(me)); } if (string.IsNullOrWhiteSpace(me) || args == null || args.Count == 0) { return(me); } var len = me.Length; var buffer = StringBuilderCache.Acquire((ushort)(len + args.Count * 3)); var pos = 0; var ch = '\x0'; unsafe { fixed(char *fmt = me) { while (true) { while (pos < len) { ch = fmt[pos]; pos++; if (ch == '}') { if (!(pos < len && fmt[pos] == '}')) { FormatError(); } pos++; } if (ch == '{') { if (pos < len && fmt[pos] == '{') // Treat as escape character for {{ { pos++; } else { pos--; break; } } buffer.Append(ch); } if (pos == len) { break; } pos++; while (pos < len && char.IsWhiteSpace(ch = fmt[pos])) { pos++; } if (!(pos != len && (ch = fmt[pos]) != ':' && ch != '}' && ch != ',')) { FormatError(); } var idSb = StringBuilderCache.Acquire(20); do { idSb.Append(ch); pos++; if (pos == len) { FormatError(); } ch = fmt[pos]; } while (pos != len && ch != ':' && ch != '}' && ch != ','); var id = StringBuilderCache.GetStringAndRelease(idSb); if (throwable && !args.HasIndex(id)) { throw new IndexOutOfRangeException($"{id} 超出索引"); } var arg = args.HasIndex(id) ? args[id] : $"{{{id}}}"; while (pos < len && char.IsWhiteSpace(ch = fmt[pos])) { pos++; } var leftJustify = false; var width = 0; if (ch == ',') { pos++; while (pos < len && char.IsWhiteSpace(fmt[pos])) { pos++; } if (pos == len) { FormatError(); } ch = fmt[pos]; if (ch == '-') { leftJustify = true; pos++; if (pos == len) { FormatError(); } ch = fmt[pos]; } if (ch < '0' || ch > '9') { FormatError(); } do { width = width * 10 + ch - '0'; pos++; if (pos == len) { FormatError(); } ch = fmt[pos]; } while (ch >= '0' && ch <= '9' && width < 1000000); } while (pos < len && char.IsWhiteSpace(ch = fmt[pos])) { pos++; } StringBuilder addition = null; if (ch == ':') { pos++; while (true) { if (pos == len) { FormatError(); } ch = fmt[pos]; pos++; if (ch == '{') { if (!(pos < len && fmt[pos] == '{')) { FormatError(); } pos++; } else if (ch == '}') { if (pos < len && fmt[pos] == '}') // Treat as escape character for }} { pos++; } else { pos--; break; } } if (addition == null) { addition = StringBuilderCache.Acquire(300); } addition.Append(ch); } } if (ch != '}') { FormatError(); } pos++; var customFormat = (string)null; var s = (string)null; if (addition != null) { customFormat = StringBuilderCache.GetStringAndRelease(addition).Trim(); } if (format != null) { s = format(id, customFormat, leftJustify, width, arg, !args.HasIndex(id)); } if (s != null) { buffer.Append(s); continue; } var formattableArg = arg as IFormattable; s = formattableArg?.ToString(customFormat, null) ?? arg.ToString(); var pad = width - s.Length; if (!leftJustify && pad > 0) { buffer.Append(' ', pad); } buffer.Append(s); if (leftJustify && pad > 0) { buffer.Append(' ', pad); } } return(StringBuilderCache.GetStringAndRelease(buffer)); } } }
/// <summary> /// 格式化字符串,与<see cref="T:String.Format" />拥有相同的格式化说明 /// </summary> /// <param name="me">格式化说明</param> /// <param name="args">可以使用的参数</param> /// <param name="format">自定义的格式化委托<see cref="CustomFormatter" /></param> /// <param name="throwable">在参数不存在的情况下是否抛出异常,默认抛出</param> /// <returns>经过格式化后的字符串</returns> /// <example>"{参数,宽度(-前导为左对齐):格式化字符串}"</example> public static string Format <T>(this string me, Dictionary <string, T> args, CustomFormatter format, bool throwable = true) { return(Format(me, Data.FromDictionary(args), format, throwable)); }
public static string Write <T>(IEnumerable <T> enumerable, string label, CustomFormatter <T> formatter) { return(Write(enumerable, (i, s) => string.Format("{0}[{1}] = {2}" + Environment.NewLine, label, i, formatter(s)), string.Format("{0} is empty", label))); }
/************************************************************************************/ public static void Run() { s_ParseThread.Start(); s_strSharedOverridesINIFilePath = Path.Combine(Program.ConfigurationFolderPath, "SharedOverrides.ini"); if (!File.Exists(s_strSharedOverridesINIFilePath)) { File.Create(s_strSharedOverridesINIFilePath).Close(); } string strPreviousSubClass = string.Empty; string strPreviousName = string.Empty; bool bFirstZoningFrame = true; bool bRunGarbageCollector = false; do { s_CurrentCycleTimestamp = DateTime.Now; /// Run this outside of the frame lock. if (bRunGarbageCollector) { Program.RunGarbageCollector(); bRunGarbageCollector = false; } Frame.Wait(true); try { /// Call the controller if we zone. During zoning, no game variables are assumed to be worth a damn. /// We go straight to a string check for now instead of the property (which uses <int> conversion) /// because the property has had a troubled past and returned buggy/invalid values. if (s_EQ2.GetMember <string>("Zoning") != "0") { if (bFirstZoningFrame) { Program.Log("Zoning..."); bFirstZoningFrame = false; ReleaseAllKeys(); s_RecentThrottledCommandCache.Clear(); if (s_Controller != null) { s_Controller.OnZoningBegin(); } bRunGarbageCollector = true; } continue; } else { if (!UpdateStaticGlobals()) { continue; } if (!bFirstZoningFrame) { Program.Log("Done zoning."); bFirstZoningFrame = true; if (s_Controller != null) { s_Controller.OnZoningComplete(); } ApplyGameSettings(); } } try { /// An amazing little thing I discovered while watching console spam. /// EQ2 will prefix your character name if you are watching a flythrough zone intro video. /// Pressing Escape kills it. if (Me.Group(0).Name.StartsWith("Flythrough_")) { Program.Log("Zone flythrough sequence detected, attempting to cancel with the Esc key..."); LavishScript.ExecuteCommand("press esc"); continue; } } catch { } /// Automatically accept a quest. if (s_Controller != null && !string.IsNullOrEmpty(s_EQ2.PendingQuestName) && s_EQ2.PendingQuestName != "None") { Program.Log("Quest offered: \"{0}\".", s_EQ2.PendingQuestName); if (s_Controller.m_ePositioningStance == PlayerController.PositioningStance.DoNothing) { Program.Log("Character is in do-nothing stance; ignoring offered quest."); } else { /// Stolen from "EQ2Quest.iss". The question I have: isn't AcceptPendingQuest() redundant then? /// eq2ui_popup_rewardpack.xml EQ2UIPage QuestPage = s_Extension.EQ2UIPage("Popup", "RewardPack"); if (QuestPage.IsValid) { EQ2UIElement QuestAcceptButton = QuestPage.Child("button", "RewardPack.Accept"); if (QuestAcceptButton.IsValid) { Program.Log("Automatically accepting quest \"{0}\"...", s_EQ2.PendingQuestName); s_EQ2.AcceptPendingQuest(); QuestAcceptButton.LeftClick(); } } } } unchecked { s_lFrameCount++; } /// Make sure the parse engine always knows the current character name. /// Unfortunately, there's no way to know the current language at this time. if (Name != strPreviousName) { s_ParseThread.PostNewNameLanguageMessage(Name, ChatEventArgs.GameLanguageType.Unknown); strPreviousName = Name; } /// If the subclass changes (startup, betrayal, etc), resync. /// The null check on SubClass is because it comes up as null when reviving. /// s_Controller is guaranteed to be non-null after this block (otherwise the program would have exited). /// TODO: State variables contained in the prior controller will be lost. Maybe make them static? if (!string.IsNullOrEmpty(Me.SubClass) && Me.SubClass != strPreviousSubClass) { Program.Log("New class found: \"{0}\"", Me.SubClass); strPreviousSubClass = Me.SubClass; s_bRefreshKnowledgeBook = true; switch (strPreviousSubClass.ToLower()) { case "coercer": s_Controller = new CoercerController(); break; case "defiler": s_Controller = new DefilerController(); break; case "dirge": s_Controller = new DirgeController(); break; case "fury": s_Controller = new FuryController(); break; case "illusionist": s_Controller = new IllusionistController(); break; case "inquisitor": s_Controller = new InquisitorController(); break; case "mystic": s_Controller = new MysticController(); break; case "templar": s_Controller = new TemplarController(); break; case "troubador": s_Controller = new TroubadorController(); break; case "warden": s_Controller = new WardenController(); break; case "warlock": s_Controller = new WarlockController(); break; case "wizard": s_Controller = new WizardController(); break; default: { Program.Log("Unrecognized or unsupported subclass type: {0}.", Me.SubClass); Program.Log("Will use generic controller without support for spells or combat arts."); s_Controller = new PlayerController(); break; } } /// Build the name of the INI file. string strFileName = string.Format("{0}.{1}.ini", ServerName, Name); s_strCurrentINIFilePath = Path.Combine(Program.ConfigurationFolderPath, strFileName); if (File.Exists(s_strCurrentINIFilePath)) { s_Controller.ReadINISettings(); } s_Controller.WriteINISettings(); SetWindowText(string.Format("{0} ({1})", Name, Me.SubClass)); ApplyGameSettings(); } /// If the size of the knowledge book changes, defer a resync. /// NOTE: If the user equips or unequips an ability-changing item, /// the ability table will be hosed but we'll have no way of knowing to force a refresh. if (s_Controller.AbilityCountChanged) { s_bRefreshKnowledgeBook = true; } /// Only if the knowledge book is intact can we safely assume that regular actions are OK. /// DoNextAction() might set s_bRefreshKnowledgeBook to true. This is fine. if (!s_bRefreshKnowledgeBook) { /// Handle all the log events that were generated by the parse thread so far. ConsoleLogEventArgs NewArgs = null; while (s_ChatEventQueue.Dequeue(ref NewArgs)) { if (NewArgs is ChatEventArgs) { s_Controller.OnLogChat(NewArgs as ChatEventArgs); } else { s_Controller.OnLogNarrative(NewArgs); } } s_Controller.DoNextAction(); s_Controller.UpdateEndOfRoundStatistics(); } /// Do certain checks only every 5th frame. if ((s_lFrameCount % 5) == 0) { /// Supposedly Process.VirtualMemorySize64 can return negative values because of casting bugs. Process CurrentProcess = Process.GetCurrentProcess(); long lActualVirtualAllocation = CurrentProcess.VirtualMemorySize64; if (lActualVirtualAllocation > (long)s_Controller.m_ulVirtualAllocationProcessTerminationThreshold && lActualVirtualAllocation < (long)(4 * CustomFormatter.GB)) /// This check is to prevent impossible values from causing crashes. { /// GAME OVER. using (StreamWriter OutputFile = Program.OpenCrashLog()) OutputFile.WriteLine("Process terminating immediately: current virtual allocation is {0}.", CustomFormatter.FormatByteCount(CurrentProcess.VirtualMemorySize64, "0.00")); CurrentProcess.Kill(); } if (s_Controller.m_bKillBotWhenCamping && Me.IsCamping) { Program.Log("Camping detected; aborting bot!"); s_bContinueBot = false; } } } finally { Frame.Unlock(); } /// If we have to refresh the knowledge book, then do it outside of the main lock. /// This is because we'll use frame waits and can't risk breaking cached data. if (s_bRefreshKnowledgeBook) { s_Controller.RefreshKnowledgeBook(); s_bRefreshKnowledgeBook = false; } /// Skip frames as configured. for (int iIndex = 0; iIndex < s_Controller.m_iFrameSkip; iIndex++) { Frame.Wait(false); unchecked { s_lFrameCount++; } } }while (s_bContinueBot); /// Don't overwrite files that already exist unless told to; people might have special comments in place. if (!File.Exists(s_strCurrentINIFilePath) || s_Controller.m_bWriteBackINI) { s_Controller.WriteINISettings(); } Program.Log("Shutting down parser thread..."); s_ParseThread.PostQuitMessageAndShutdownQueue(true); if (s_ParseThread.WaitForTermination(TimeSpan.FromSeconds(30.0))) { Program.Log("Parser thread terminated."); } else { Program.Log("Parser thread timed out."); } return; }
static void Main(string[] args) { int choice = 0; CustomFormatter customFormatter = new CustomFormatter(); JSONSerializer jSONSerializer = new JSONSerializer(); DummyClassA a = new DummyClassA(); a.Id = 1; DummyClassB b = new DummyClassB(); b.Id = 2; DummyClassC c = new DummyClassC(); c.Id = 3; a.Other = b; b.Other = c; c.Other = a; b.Text = "HELLO"; c.Time = new DateTime(2020, 1, 1); while (choice != 5) { Menu(); Console.Write("Wybieram: "); choice = Console.Read() - '0'; switch (choice) { case 1: string path = GetFile(); using (FileStream stream = File.Open(path, FileMode.OpenOrCreate)) { customFormatter.Serialize(stream, a); } Console.WriteLine("Serializacja wlasna zakonczona"); break; case 2: path = GetFile(); if (File.Exists(path)) { using (FileStream stream = File.Open(path, FileMode.Open)) { a = (DummyClassA)customFormatter.Deserialize(stream); Console.WriteLine("Deserializacja wlasna zakonczona"); } } else { Console.WriteLine("Plik nie istnieje"); } break; case 3: path = GetFile(); jSONSerializer.Serialize(path, a); Console.WriteLine("Serializacja JSON zakonczona"); break; case 4: path = GetFile(); if (File.Exists(path)) { a = jSONSerializer.Deserialize <DummyClassA>(path); Console.WriteLine("Deserializacja JSON zakonczona"); } else { Console.WriteLine("Plik nie istnieje"); } break; case 5: Environment.Exit(0); break; default: Console.WriteLine("Blad"); break; } } }
public static bool TryFormat(this long value, Span <byte> buffer, out int bytesWritten, ParsedFormat format = default, SymbolTable symbolTable = null) => CustomFormatter.TryFormat(value, buffer, out bytesWritten, format, symbolTable);
/// <summary> /// 格式化字符串,与<see cref="T:String.Format" />拥有相同的格式化说明 /// </summary> /// <param name="me">格式化说明</param> /// <param name="args">可以使用的参数</param> /// <param name="format">自定义的格式化委托<see cref="CustomFormatter" /></param> /// <param name="throwable">在参数不存在的情况下是否抛出异常,默认抛出</param> /// <returns>经过格式化后的字符串</returns> /// <example>"{参数,宽度(-前导为左对齐):格式化字符串}"</example> public static string Format(this string me, object args, CustomFormatter format, bool throwable = true) { return(Format(me, Data.FromObject(args), format, throwable)); }
public void Format_Int32_String() { var formatter = CustomFormatter.Default(); Assert.AreEqual("foo ' 32' bar", string.Format(formatter, "foo '{0,4}' bar", 32)); }