public void Not_Listed_Property_Is_Not_Invoked() { var dumper = new ObjectDumper <CrashedUfo>(); var crashed = new CrashedUfo() { Name = "Conqueror III", Speed = 10, Origin = new Planet() { Name = "Alpha Centauri 3", DaysPerYear = 452 } }; var desc = dumper.Dump(crashed); var twoPropertiesList = desc.Take(2).ToList(); // No exception at this point because ZLastProperty is *never* invoked Assert.AreEqual(2, twoPropertiesList.Count); }
public void DumpRight() { List <DataEntity> items = DataEntity.GetSeveral(); ObjectDumper <DataEntity> entityDumper = new ObjectDumper <DataEntity>(DataEntity.GetObjectDump); entityDumper.KrakenHorizontalAlignDefault = KrakenHorizontalAlign.Right; string dump = entityDumper.Dump(items); Assert.AreEqual(entityDumper.KrakenHorizontalAlignDefault, KrakenHorizontalAlign.Right); // CodeGen.GenerateAssertions(dump, "dump"); // The following assertions were generated on 24-Jan-2011 #region Generated Assertions Assert.AreEqual(@" Id IsCool Description Created Amount -- ------ ------------------------- ---------- ------------ 1 True Holy bat man boat monster 2000-01-01 14.23 1 False what boy wonder 2000-03-01 12314.23 1 True (null) 2010-01-01 14.213333333 ".NormaliseCrlf(), dump.NormaliseCrlf()); #endregion }
public void OnGet() { var dto = new TestDto { Success = true, Status = TestDto.TestDtoStatus.Ok, Person = new Entity.Person { Name = "試作", Age = 30 }, Exception = new NotSupportedException("テスト") }; _logger.LogInformation(ObjectDumper.Dump(dto, DumpStyle.CSharp)); var dto2 = new TestDto { }; _logger.LogInformation(ObjectDumper.Dump(dto2, DumpStyle.CSharp)); }
public void Template_For_Complex_Type_Is_Applied() { var ufo = new Ufo() { Name = "Conqueror III", Speed = 10, Origin = new Planet() { Name = "Alpha Centauri 3", DaysPerYear = 452 } }; var dumper = new ObjectDumper <Ufo>(); dumper.AddTemplateFor(u => u.Origin, o => string.Format("Planet: {0}", o.Name)); var desc = dumper.Dump(ufo); Assert.IsTrue(desc.Any(kvp => kvp.Key == "Origin" && kvp.Value == string.Format("Planet: {0}", ufo.Origin.Name))); }
private void MetroButton1_Click(object sender, EventArgs e) { var hwid = FingerPrint.Value(); var login = api.Login(keyinput.Text, hwid, Program.appToken); var personsDump = ObjectDumper.Dump(login, DumpStyle.CSharp); Console.WriteLine(personsDump); if (Convert.ToBoolean(login["success"]) == false) { string message = login["message"].ToString(); MessageBox.Show(message, "something wrong!", MessageBoxButtons.OK, MessageBoxIcon.Error ); } else if (Convert.ToBoolean(login["success"]) == true) { string message = login["message"].ToString(); MessageBox.Show(message, "Thanks!", MessageBoxButtons.OK, MessageBoxIcon.Information ); Program.syncKeyConfig(login); App app = new App(); app.Show(); this.Hide(); } else { MessageBox.Show("Unknown Error!", "Something Wrong!", MessageBoxButtons.OK, MessageBoxIcon.Error ); } }
public IHttpActionResult Post([FromBody] List <MonitorValue> commandValues) { _logger.Info("-----------------------------------------"); _logger.Info("MonitorValuesController..."); _logger.Info(ObjectDumper.Dump(commandValues)); var headers = Request.Headers; var serverGuid = headers.GetValues("server_guid").First(); if (!Util.IsServerGuidValid(serverGuid)) { throw new HttpResponseException(HttpStatusCode.Unauthorized); } try { var guid = headers.GetValues("agent_guid").First(); var agent = monitorDb.GetAgentByGuid(guid); monitorDb.DeleteOldHistory(DateTime.UtcNow); foreach (var commandValue in commandValues) { var MonitorValue = new BusinessLayer.MonitorValue() { AgentId = agent.AgentId, // This should be derived from header MonitorCommandId = commandValue.Id, ReturnCode = commandValue.ReturnCode, Value = commandValue.Value, ErrorMessage = commandValue.ErrorMessage }; _logger.Debug($"MonitorValuesController : UpsertMonitorValue"); monitorDb.UpsertMonitorValue(MonitorValue); _logger.Debug($"MonitorValuesController : UpdateLastReceivedReply"); monitorDb.UpdateLastReceivedReply(agent.AgentId); } return(Ok()); } catch (Exception e) { _logger.Error($"Post method Exception:{e.Message}"); return(BadRequest()); } }
public void ShouldDumpObject_WithDumpStyle() { // Arrange var person = PersonFactory.GetPersonThomas(); var dumpStyle = DumpStyle.CSharp; // Act var dump = ObjectDumper.Dump(person, dumpStyle); // Assert this.testOutputHelper.WriteLine(dump); dump.Should().NotBeNull(); dump.Should().Be("var person = new Person\r\n" + "{\r\n" + " Name = \"Thomas\",\r\n" + " Char = '',\r\n" + " Age = 30,\r\n" + " GetOnly = 11,\r\n" + " Bool = false,\r\n" + " Byte = 0,\r\n" + " ByteArray = new byte[]\r\n" + " {\r\n" + " 1,\r\n" + " 2,\r\n" + " 3,\r\n" + " 4\r\n" + " },\r\n" + " SByte = 0,\r\n" + " Float = 0f,\r\n" + " Uint = 0u,\r\n" + " Long = 0L,\r\n" + " ULong = 0UL,\r\n" + " Short = 0,\r\n" + " UShort = 0,\r\n" + " Decimal = 0m,\r\n" + " Double = 0d,\r\n" + " DateTime = DateTime.MinValue,\r\n" + " NullableDateTime = null,\r\n" + " Enum = DateTimeKind.Unspecified\r\n" + "};"); }
public async Task <ActionResult> Post([FromRoute] int id, System.Threading.CancellationToken cancellationToken) { TestModel testModel = new TestModel { Id = 1, IntValue = 1, Name = "name test", StringValue = "String Value StringValue" }; //_elasticClient.CreateIndex(); var data = await _elasticClient.IndexDocumentAsync(testModel, cancellationToken); _logger.LogDebug("Get {0}", ObjectDumper.Dump(data)); if (data.IsValid) { return(Ok(data)); } return(StatusCode(500, data.ServerError.Error.Reason)); }
public async Task <string[]> Run( [OrchestrationTrigger] IDurableOrchestrationContext context, ILogger log) { var logger = context.CreateReplaySafeLogger(log); logger.LogInformation("Fan out summoner names to retrieve account ids."); var accountIdTasks = new List <Task <string> >(); foreach (var summonerName in _lolChestConfig.SummonerNames) { var activityInput = (_lolChestConfig.Region, summonerName); accountIdTasks.Add(context.CallActivityAsync <string>("GetAccountId", activityInput)); } var accountIds = await Task.WhenAll(accountIdTasks); logger.LogInformation($"Retrieved account ids. {ObjectDumper.Dump(accountIds)}"); return(accountIds); }
public void Should_return_accurate_move_distance_from_move_reducer() { // stub action var mockLookAction = new Action.Look { inputRotation = Vector2.up, fixedDeltaTime = 1.0f }; // stub state condition var mockCameraState = new CameraState { isLooking = false, localRotation = new Quaternion(1f, 1f, 1f, 1f) }; var sut = container_.Resolve <Reducer>(); var result = sut.Reduce(mockCameraState, mockLookAction); Debug.Log(ObjectDumper.Dump(result)); Assert.IsTrue(result.isLooking); // Assert.Equals(result.localRotation, Quaternion.Euler(1f,1f,1f)); }
public async Task Run( [OrchestrationTrigger] IDurableOrchestrationContext context, ILogger log) { var logger = context.CreateReplaySafeLogger(log); var gameIds = context.GetInput <string[]>(); logger.LogInformation($"Fan out game ids to store them in chest. {ObjectDumper.Dump(gameIds)}"); var addMatchToChestTasks = new List <Task>(); foreach (var gameId in gameIds) { var activityInput = (_lolChestConfig.Region, gameId); addMatchToChestTasks.Add(context.CallActivityAsync("AddMatchToChest", activityInput)); } await Task.WhenAll(addMatchToChestTasks); logger.LogInformation($"Game ids were added to the chest. {ObjectDumper.Dump(gameIds)}"); }
// Translate 2D mouse input into euler angle rotations. public static CameraState Look(CameraState state, Action.Look action) { Quaternion localRotation = state.localRotation; Vector2 rotation = action.inputRotation; float time = action.fixedDeltaTime; int lookSpeed = ReduxityInitializer.Instance.lookSpeed; // editor setting // inputLook.y rotates the camera around the horizontal axis (with + being up) Vector3 vertLook = rotation.y * time * Vector3.left * lookSpeed; Quaternion cameraLookRotation = localRotation * Quaternion.Euler(vertLook); // We have to flip the signs and positions of min/max view angle here because the math // uses the contradictory interpretation of our angles (+/- is down/up). float maxViewAngle = ReduxityInitializer.Instance.maxViewAngle; float minViewAngle = ReduxityInitializer.Instance.minViewAngle; Quaternion clampedRotation = ClampRotationAroundXAxis_(cameraLookRotation, -maxViewAngle, -minViewAngle); state.isLooking = true; state.localRotation = clampedRotation; Debug.Log($"in Look, returning state: {ObjectDumper.Dump(state)}"); return(state); }
private string GetSummaryPlain() { // Collate the data Dictionary <string, PerformancePointCollection> grouped = new Dictionary <string, PerformancePointCollection>(); lock (_dataPoints) { foreach (PerformancePoint datum in _dataPoints) { if (!grouped.ContainsKey(datum.Name)) { grouped.Add(datum.Name, new PerformancePointCollection()); } grouped[datum.Name].Add(datum); } } List <PerformanceSummary> perfSummarys = new List <PerformanceSummary>(); foreach (string key in grouped.Keys) { PerformanceSummary summary = grouped[key].GetSummary(); summary.Name = key; perfSummarys.Add(summary); } perfSummarys.Sort((p1, p2) => p1.TotalTime.CompareTo(p2.TotalTime)); ObjectDumper <PerformanceSummary> tableDump = new ObjectDumper <PerformanceSummary>(PerformanceSummary.GetObjectDump); var summaryString = tableDump.Dump(perfSummarys); if (ResetDataPointsOnRetrieval) { _dataPoints.Clear(); } return(summaryString); }
public static async Task Main() { var clientSettingsReader = new ClientSettingsReader(SerializerOptions.Default); var clientSettingsCollection = await clientSettingsReader.Read(); if (clientSettingsCollection is null) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("No pact.json config found. Nothing to generate."); return; } foreach (var clientSettings in clientSettingsCollection) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Generating API client for given settings."); Console.ResetColor(); Console.WriteLine(ObjectDumper.Dump(clientSettings)); var schemaReader = new SchemaReader(SerializerOptions.Default); var schema = await schemaReader.ReadAsync(clientSettings.SchemaUri, clientSettings.Scopes); if (schema is null) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Could not read schema."); continue; } var fileManager = new FileManager(clientSettings.OutputDirectory); var apiEmitter = new ApiEmitter(clientSettings, schema); var emittedApi = apiEmitter.Emit(); fileManager.Save(emittedApi); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("API client successfully generated."); } }
private static void LoadDebugCommands() { Commands.Add(new Command(new IDependency[] { }, new CommandPart(new string[] { "deb" }), (k, d) => { string msg = ObjectDumper.Dump(k); return(new ExecutionResult(true, new MessageCallback(msg, ECharacter.Admin))); })); Commands.Add(new Command(new IDependency[] { }, new CommandPart(new string[] { "res" }), (k, d) => { Dictionary <string, int> calc = new Dictionary <string, int>(); foreach (var kv in k.Resources) { calc[kv.Key] = k.GetResourcesCount(kv.Key); } string msg = string.Join("\n", calc.Select(r => r.Key + ": " + (r.Value))); return(new ExecutionResult(new MessageCallback(msg, ECharacter.Admin))); })); Commands.Add(new Command(new IDependency[] { }, new CommandPart(new string[] { "tas" }), (k, d) => { string msg = string.Join("\n", k.Humans.Select(h => h.GetName(k.Language) + ": " + h.GetStatus(k.Language))); return(new ExecutionResult(new MessageCallback(msg, ECharacter.Admin))); })); }
public static TInput FDump <TInput>(this TInput input) { var s = ObjectDumper.Dump(input, DumpOptions); s = s.Replace("var", "let"); s = s.Replace(";\r\n", String.Empty); s = s.Replace("new ", String.Empty); s = Regex.Replace(s, @"[\r\n]+\s+{", "("); // replace { with ( s = Regex.Replace(s, @"[\r\n]+ +\},*", ")"); // replace } with ) s = Regex.Replace(s, @"\([\r\n\s]+\)", "()"); // remove gap between ( ) s = s.Replace("\r\n ", "\r\n "); // tab everything over (except first line) s = s.Insert(s.IndexOf('=') + 1, "\r\n "); // new line after first = var listPattern = @"\S*List<\S+>\("; if (Regex.IsMatch(s, listPattern)) // Matches FSharpList<> and List<>, replaces with [] { s = Regex.Replace(s, listPattern, "["); var i = s.LastIndexOf('}'); s = s.Remove(i).Insert(i, " ]"); } Console.WriteLine(s); return(input); }
//public static void Dump(string filename, DumpOptions options = null, params object[] instances) //{ // options ??= GetDefaultDumpOptions(); // using (StreamWriter file = new StreamWriter(filename)) { // foreach (var instance in instances) { // var data = ObjectDumper.Dump(instance, options); // file.Write($@"\n\n// {instance.GetType().Name}\n\n"); // file.Write(data); // } // } //} public static void Dump( string filename, bool setPropertiesOnly = false, int maxLevel = 10, ICollection <string> excludeProperties = null, bool ignoreDefaultValues = false, params object[] instances) { var options = GetDefaultDumpOptions(); options.SetPropertiesOnly = setPropertiesOnly; options.MaxLevel = maxLevel; options.ExcludeProperties = excludeProperties; options.IgnoreDefaultValues = ignoreDefaultValues; using (StreamWriter file = new StreamWriter(filename)) { foreach (var instance in instances) { var data = ObjectDumper.Dump(instance, options); file.Write($"\n\n// {instance.GetType().Name}\n\n"); file.Write(data); } } }
public void ShouldDumpObject_WithDefaultDumpOptions() { // Arrange var person = PersonFactory.GeneratePersons(count: 1).Single(); // Act var dump = ObjectDumper.Dump(person); // Assert this.testOutputHelper.WriteLine(dump); dump.Should().NotBeNull(); dump.Should().Be( "{Person}\r\n" + " Name: \"Person 1\"\r\n" + " Char: ''\r\n" + " Age: 2\r\n" + " GetOnly: 11\r\n" + " Bool: false\r\n" + " Byte: 0\r\n" + " ByteArray: ...\r\n" + " 1\r\n" + " 2\r\n" + " 3\r\n" + " 4\r\n" + " SByte: 0\r\n" + " Float: 0\r\n" + " Uint: 0\r\n" + " Long: 0\r\n" + " ULong: 0\r\n" + " Short: 0\r\n" + " UShort: 0\r\n" + " Decimal: 0\r\n" + " Double: 0\r\n" + " DateTime: DateTime.MinValue\r\n" + " NullableDateTime: null\r\n" + " Enum: DateTimeKind.Unspecified"); }
public void ReadTypes() { var typeProvider = new TypeProvider(); var typeChecker = new TypeChecker(typeProvider); var distinctTypeQueue = new DistinctTypeQueue(); var typeReferenceReader = new TypeReferenceReader(typeChecker, distinctTypeQueue); var distinctTypeReader = new DistinctTypeReader(typeChecker, typeReferenceReader); var types = new[] { // typeof(Registry<>), typeof(Hexarc.Pact.Protocol.Types.Type) }; foreach (var t in types) { Console.WriteLine(ObjectDumper.Dump(typeReferenceReader.Read(t.ToContextualType(), NamingConvention.CamelCase))); } while (distinctTypeQueue.TryDequeue(out var t)) { Console.WriteLine(ObjectDumper.Dump(distinctTypeReader.Read(t.ToContextualType(), default))); } }
public long Func( object[] paramlist = null, string memberName = "", string sourceFilePath = "", int sourceLineNumber = 0) { string message = $"{memberName}( "; if (paramlist?.Length > 0) { var options = new DumpOptions { DumpStyle = DumpStyle.Console, MaxLevel = 3 }; message = $"{message}{ObjectDumper.Dump( paramlist, options )}"; } message = $"{message} )"; Trace(message, _nameSpace, sourceFilePath, sourceLineNumber); return(DateTime.Now.Ticks); }
public void ShouldDumpObject_WithOptions() { // Arrange var person = PersonFactory.GetPersonThomas(); var dumpOptions = new DumpOptions { DumpStyle = DumpStyle.CSharp, ExcludeProperties = new[] { "Name", "Char" }, IndentChar = ' ', IndentSize = 8, MaxLevel = 1, LineBreakChar = "\n", PropertyOrderBy = pi => pi.Name, SetPropertiesOnly = true }; // Act var dump = ObjectDumper.Dump(person, dumpOptions); // Assert this.testOutputHelper.WriteLine(dump); dump.Should().NotBeNull(); dump.Should().Be("var person = new Person\n{\n Age = 30,\n Bool = false,\n Byte = 0,\n ByteArray = new Byte[]\n {\n },\n DateTime = DateTime.MinValue,\n Decimal = 0m,\n Double = 0d,\n Enum = System.DateTimeKind.Unspecified,\n Float = 0f,\n Long = 0L,\n NullableDateTime = null,\n SByte = 0,\n Short = 0,\n Uint = 0,\n ULong = 0L,\n UShort = 0\n};"); }
/// <summary> /// Serializes the given <see cref="element" /> to string. /// </summary> /// <param name="element">Object to be dumped to string using the default dump options.</param> /// <returns></returns> public static string Dump(this object element) { return(ObjectDumper.Dump(element)); }
/// <summary> /// Serializes the given <see cref="element" /> to string with additional options <see cref="dumpOptions" />. /// </summary> /// <param name="element">Object to be dumped to string using the given <paramref name="dumpOptions" />.</param> /// <param name="dumpOptions">Further options to customize the dump output.</param> /// <returns></returns> public static string Dump(this object element, DumpOptions dumpOptions) { return(ObjectDumper.Dump(element, dumpOptions)); }
/// <summary> /// Serializes the given <see cref="element" /> to string. /// </summary> /// <param name="element">Object to be dumped to string using the given <paramref name="dumpStyle" />.</param> /// <param name="dumpStyle">The formatting style.</param> /// <returns></returns> public static string Dump(this object element, DumpStyle dumpStyle) { return(ObjectDumper.Dump(element, dumpStyle)); }
public string PoliciesLMNVSerialization(IEnumerable <PolicyTextInfoPart> policies) { ObjectDumper dumper; StringBuilder sb = new StringBuilder(); XElement dump = null; var realFormat = false; var minified = false; string[] complexBehaviours = null; string outputFormat = _workContext.GetContext().HttpContext.Request.Headers["OutputFormat"]; if (outputFormat != null && outputFormat.Equals("LMNV", StringComparison.OrdinalIgnoreCase)) { complexBehaviours = new string[] { "returnnulls" }; realFormat = true; minified = false; } else { bool.TryParse(_workContext.GetContext().HttpContext.Request["realformat"], out realFormat); bool.TryParse(_workContext.GetContext().HttpContext.Request["minified"], out minified); } sb.Insert(0, "{"); sb.AppendFormat("\"n\": \"{0}\"", "Model"); sb.AppendFormat(", \"v\": \"{0}\"", "VirtualContent"); sb.Append(", \"m\": [{"); sb.AppendFormat("\"n\": \"{0}\"", "VirtualId"); sb.AppendFormat(", \"v\": \"{0}\"", "0"); sb.Append("}]"); sb.Append(", \"l\":["); int i = 0; sb.Append("{"); sb.AppendFormat("\"n\": \"{0}\"", "PendingPolicies"); sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]"); sb.Append(", \"m\": ["); foreach (var item in policies) { if (i > 0) { sb.Append(","); } sb.Append("{"); dumper = new ObjectDumper(10, null, false, true, complexBehaviours); dump = dumper.Dump(item.ContentItem, String.Format("[{0}]", i)); JsonConverter.ConvertToJSon(dump, sb, minified, realFormat); sb.Append("}"); i++; } sb.Append("]"); sb.Append("}"); sb.Append("]"); sb.Append("}"); return(sb.ToString()); }
internal void AddDefaultCommands() { _LoggerSubscriber = (logger, loglevel, indent, str) => { PrintLine(logger.String(loglevel, str, indent: indent), color: _LoggerColors[loglevel]); }; AddCommand("!!", (args, histindex) => { if (histindex - 1 < 0) { throw new Exception("Can't run previous command (history is empty)."); } return(History.Execute(histindex.Value - 1)); }); AddCommand("!'", (args, histindex) => { if (histindex - 1 < 0) { throw new Exception("Can't run previous command (history is empty)."); } return(History.Entries[histindex.Value - 1]); }); AddCommand("echo", (args) => { return(string.Join(" ", args.ToArray())); }).WithSubCommand("hello", (args) => { return("Hello, world!\nHello, world!\nHello, world!\nHello, world!\nHello, world!\nHello, world!"); }); AddGroup("debug") .WithSubCommand("spawn-rand-chest", (args) => { var chest = GameManager.Instance.RewardManager.SpawnTotallyRandomChest(GameManager.Instance.PrimaryPlayer.CurrentRoom.GetRandomAvailableCellDumb()); return(chest.name); }) //.WithSubCommand("force-dual-wield", (args) => { // if (args.Count < 1) throw new Exception("At least 1 argument required."); // var partner_id = int.Parse(args[0]); // var player = GameManager.Instance.PrimaryPlayer; // var gun = player.inventory.CurrentGun; // var partner_gun = PickupObjectDatabase.GetById(partner_id) as Gun; // player.inventory.AddGunToInventory(partner_gun); // var forcer = gun.gameObject.AddComponent<DualWieldForcer>(); // forcer.Gun = gun; // forcer.PartnerGunID = partner_gun.PickupObjectId; // forcer.TargetPlayer = player; // return "Done"; //}) .WithSubCommand("unexclude-all-items", (args) => { foreach (var ent in PickupObjectDatabase.Instance.Objects) { if (ent == null) { continue; } ent.quality = PickupObject.ItemQuality.SPECIAL; } return("Done"); }) .WithSubCommand("activate-all-synergies", (args) => { foreach (var ent in GameManager.Instance.SynergyManager.synergies) { if (ent == null) { continue; } ent.ActivationStatus = SynergyEntry.SynergyActivation.ACTIVE; } return("Done"); }) .WithSubCommand("character", (args) => { if (args.Count < 1) { throw new Exception("At least 1 argument required."); } var player_controller = ModUntitled.Characters[args[0]]; if (player_controller == null) { throw new Exception($"Character '{args[0]}' doesn't exist."); } ModUntitled.Instance.StartCoroutine(_ChangeCharacter(player_controller, args.Count > 1)); return($"Changed character to {args[0]}"); }) .WithSubCommand("parser-bounds-test", (args) => { var text = "echo Hello! \"Hello world!\" This\\ is\\ great \"It\"works\"with\"\\ wacky\" stuff\" \\[\\] \"\\[\\]\" [e[echo c][echo h][echo [echo \"o\"]] \"hel\"[echo lo][echo !]]"; CurrentCommandText = text; return(null); }) .WithSubCommand("giveid", (args) => { if (args.Count < 1) { throw new Exception("Exactly 1 argument required."); } var pickup_obj = PickupObjectDatabase.Instance.InternalGetById(int.Parse(args[0])); if (pickup_obj == null) { return("Item ID {args[0]} doesn't exist!"); } LootEngine.TryGivePrefabToPlayer(pickup_obj.gameObject, GameManager.Instance.PrimaryPlayer, true); return(pickup_obj.EncounterNameOrDisplayName); }); //AddGroup("pool") //.WithSubGroup( // new Group("items") // .WithSubCommand("idof", (args) => { // if (args.Count < 1) throw new Exception("Exactly 1 argument required (numeric ID)."); // var id = int.Parse(args[0]); // foreach (var pair in ModUntitled.Items.Pairs) { // if (pair.Value.PickupObjectId == id) return pair.Key; // } // return "Entry not found."; // }) // .WithSubCommand("nameof", (args) => { // if (args.Count < 1) throw new Exception("Exactly 1 argument required (ID)."); // var id = args[0]; // foreach (var pair in ModUntitled.Items.Pairs) { // if (pair.Key == id) return _GetPickupObjectName(pair.Value); // } // return "Entry not found."; // }) // .WithSubCommand("numericof", (args) => { // if (args.Count < 1) throw new Exception("Exactly 1 argument required (ID)."); // var id = args[0]; // foreach (var pair in ModUntitled.Items.Pairs) { // if (pair.Key == id) return pair.Value.PickupObjectId.ToString(); // } // return "Entry not found."; // }) // .WithSubCommand("list", (args) => { // var s = new StringBuilder(); // var pairs = new List<KeyValuePair<string, PickupObject>>(); // foreach (var pair in ModUntitled.Items.Pairs) { // pairs.Add(pair); // } // foreach (var pair in pairs) { // if (_GetPickupObjectName(pair.Value) == "NO NAME") { // s.AppendLine($"[{pair.Key}] {_GetPickupObjectName(pair.Value)}"); // } // } // pairs.Sort((x, y) => string.Compare(_GetPickupObjectName(x.Value), _GetPickupObjectName(y.Value))); // foreach (var pair in pairs) { // if (_GetPickupObjectName(pair.Value) == "NO NAME") continue; // s.AppendLine($"[{pair.Key}] {_GetPickupObjectName(pair.Value)}"); // } // return s.ToString(); // }) // .WithSubCommand("random", (args) => { // return ModUntitled.Items.RandomKey; // }) //); AddCommand("summon", (args) => { var player = GameManager.Instance.PrimaryPlayer; if (player == null) { throw new Exception("No player"); } var cell = player.CurrentRoom.GetRandomAvailableCellDumb(); var entity = AIActor.Spawn(ModUntitled.Enemies[args[0]], cell, player.CurrentRoom, true, AIActor.AwakenAnimationType.Default, true); if (ModUntitled.Enemies.HasTag(args[0], ModUntitled.EnemyTags.Friendly)) { entity.CompanionOwner = player; entity.CompanionSettings = new ActorCompanionSettings(); entity.CanTargetPlayers = false; var companion = entity.GetComponent <CompanionController>(); if (companion != null) { companion.Initialize(player); if (companion.specRigidbody) { PhysicsEngine.Instance.RegisterOverlappingGhostCollisionExceptions(companion.specRigidbody, null, false); } } } var name = args[0]; if (entity.encounterTrackable?.journalData?.PrimaryDisplayName != null) { name = StringTableManager.GetEnemiesString(entity.encounterTrackable?.journalData?.PrimaryDisplayName); } return(name); }); //AddCommand("listmods", (args) => { // var s = new StringBuilder(); // s.AppendLine("Loaded mods:"); // foreach (var mod in ModUntitled.ModLoader.LoadedMods) { // _GetModInfo(s, mod); // } // return s.ToString(); //}); AddCommand("lua", (args) => { LuaMode = true; return("[entered lua mode]"); }); AddCommand("give", (args) => { LootEngine.TryGivePrefabToPlayer(ModUntitled.Items[args[0]].gameObject, GameManager.Instance.PrimaryPlayer, true); return(args[0]); }); AddGroup("dump") .WithSubCommand("synergy_chest", (args) => { System.Console.WriteLine(ObjectDumper.Dump(GameManager.Instance.RewardManager.Synergy_Chest, depth: 10)); return("Dumped to log"); }) .WithSubCommand("synergies", (args) => { var id = 0; foreach (var synergy in GameManager.Instance.SynergyManager.synergies) { if (synergy.NameKey != null) { var name = StringTableManager.GetSynergyString(synergy.NameKey); System.Console.WriteLine($"== SYNERGY ID {id} NAME {name} =="); } else { System.Console.WriteLine($"== SYNERGY ID {id} =="); } System.Console.WriteLine($" ACTIVATION STATUS: {synergy.ActivationStatus}"); System.Console.WriteLine($" # OF OBJECTS REQUIRED: {synergy.NumberObjectsRequired}"); System.Console.WriteLine($" ACTIVE WHEN GUN UNEQUIPPED?: {synergy.ActiveWhenGunUnequipped}"); System.Console.WriteLine($" REQUIRES AT LEAST ONE GUN AND ONE ITEM?: {synergy.RequiresAtLeastOneGunAndOneItem}"); System.Console.WriteLine($" MANDATORY GUNS:"); foreach (var itemid in synergy.MandatoryGunIDs) { System.Console.WriteLine($" - {_GetPickupObjectName(PickupObjectDatabase.GetById(itemid))}"); } System.Console.WriteLine($" OPTIONAL GUNS:"); foreach (var itemid in synergy.OptionalGunIDs) { System.Console.WriteLine($" - {_GetPickupObjectName(PickupObjectDatabase.GetById(itemid))}"); } System.Console.WriteLine($" MANDATORY ITEMS:"); foreach (var itemid in synergy.MandatoryItemIDs) { System.Console.WriteLine($" - {_GetPickupObjectName(PickupObjectDatabase.GetById(itemid))}"); } System.Console.WriteLine($" OPTIONAL ITEMS:"); foreach (var itemid in synergy.OptionalItemIDs) { System.Console.WriteLine($" - {_GetPickupObjectName(PickupObjectDatabase.GetById(itemid))}"); } System.Console.WriteLine($" BONUS SYNERGIES:"); foreach (var bonus in synergy.bonusSynergies) { System.Console.WriteLine($" - {bonus}"); } System.Console.WriteLine($" STAT MODIFIERS:"); foreach (var statmod in synergy.statModifiers) { System.Console.WriteLine($" - STAT: {statmod.statToBoost}"); System.Console.WriteLine($" AMOUNT: {statmod.amount}"); System.Console.WriteLine($" MODIFY TYPE: {statmod.modifyType}"); System.Console.WriteLine($" PERSISTS ON COOP DEATH?: {statmod.PersistsOnCoopDeath}"); System.Console.WriteLine($" IGNORED FOR SAVE DATA?: {statmod.ignoredForSaveData}"); } id++; } return("Dumped to log"); }) .WithSubCommand("items", (args) => { var b = new StringBuilder(); var db = PickupObjectDatabase.Instance.Objects; for (int i = 0; i < db.Count; i++) { PickupObject obj = null; string nameprefix = ""; string name = null; try { obj = db[i]; } catch { name = "[ERROR: failed getting object by index]"; } if (obj != null) { try { var displayname = obj.encounterTrackable.journalData.PrimaryDisplayName; name = StringTableManager.ItemTable[displayname].GetWeightedString(); } catch { name = "[ERROR: failed getting ammonomicon name]"; } if (name == null) { try { name = obj.EncounterNameOrDisplayName; } catch { name = "[ERROR: failed getting encounter or display name]"; } } } if (name == null && obj != null) { name = "[NULL NAME (but object is not null)]"; } name = $"{nameprefix} {name}"; if (name != null) { b.AppendLine($"{i}: {name}"); _Logger.Info($"{i}: {name}"); } } return(b.ToString()); }); AddGroup("log") .WithSubCommand("sub", (args) => { if (_Subscribed) { return("Already subscribed."); } Logger.Subscribe(_LoggerSubscriber); _Subscribed = true; return("Done."); }) .WithSubCommand("unsub", (args) => { if (!_Subscribed) { return("Not subscribed yet."); } Logger.Unsubscribe(_LoggerSubscriber); _Subscribed = false; return("Done."); }) .WithSubCommand("level", (args) => { if (args.Count == 0) { return(_LogLevel.ToString().ToLowerInvariant()); } else { switch (args[0]) { case "debug": _LogLevel = Logger.LogLevel.Debug; break; case "info": _LogLevel = Logger.LogLevel.Info; break; case "warn": _LogLevel = Logger.LogLevel.Warn; break; case "error": _LogLevel = Logger.LogLevel.Error; break; default: throw new Exception($"Unknown log level '{args[0]}"); } return("Done."); } }); //// test commands to dump collection //AddGroup("texdump") //.WithSubCommand("collection", (args) => //{ // if (args.Count == 0) // { // return "No name specified"; // } // else // { // string collectionName = args[0]; // Animation.Collection.Dump(collectionName); // return "Successfull"; // } //}); }
public static void Print(Customer input) { var result = ObjectDumper <Customer> .Dump(input); Console.WriteLine(result); }
private void UpdateProfileSlim(Profile profile) { profileRepo.Update(profile); logger.LogInformation("profile updated\n" + ObjectDumper.Dump(profile)); }
protected override Task HandleInternalAsync(SharpMTProto.Schema.IMessage responseMessage) { var body = responseMessage.Body; Console.WriteLine("handle Internal async " + ObjectDumper.Dump(responseMessage)); var updatesTooLong = body as UpdatesTooLong; var updateShortMessage = body as UpdateShortMessage; var updateShortChatMessage = body as UpdateShortChatMessage; var updateShort = body as UpdateShort; var updatesCombined = body as UpdatesCombined; var updates = body as Updates; var updateShortSentMessage = body as UpdateShortSentMessage; var updateContactLink = body as UpdateContactLink; if (updatesTooLong != null) { RaiseOnUpdateTooLong(); } var updateList = new List <object>(); var state = new State(); if (updateShort != null) { state.Date = updateShort.Date; updateList.Add(updateShort.Update); } else if (updateShortMessage != null) { state.Date = updateShortMessage.Date; state.Pts = updateShortMessage.Pts; updateList.Add(updateShortMessage); } else if (updateShortChatMessage != null) { state.Date = updateShortChatMessage.Date; state.Pts = updateShortChatMessage.Pts; updateList.Add(updateShortChatMessage); } else if (updatesCombined != null) { state.Date = updatesCombined.Date; state.Seq = updatesCombined.Seq; updateList.AddRange(updatesCombined.Users); updateList.AddRange(updatesCombined.Chats); updateList.AddRange(updatesCombined.Updates); } else if (updates != null) { state.Date = updates.Date; state.Seq = updates.Seq; updateList.AddRange(updates.Users); updateList.AddRange(updates.Chats); updateList.AddRange(updates.UpdatesProperty); } else if (updateShortSentMessage != null) { state.Date = updateShortSentMessage.Date; state.Pts = updateShortSentMessage.Pts; updateList.Add(updateShortSentMessage); } foreach (var update in updateList) { var newMessage = update as UpdateNewMessage; var deleteMessages = update as UpdateDeleteMessages; var encryptedMessages = update as UpdateNewEncryptedMessage; var readHistoryInbox = update as UpdateReadHistoryInbox; var readHistoryOutBox = update as UpdateReadHistoryOutbox; var updateWebPage = update as UpdateWebPage; var updateReadMessagesContents = update as UpdateReadMessagesContents; var updateEditMessage = update as UpdateEditMessage; var updateChannelTooLong = update as UpdateChannelTooLong; var updateNewChannelMessage = update as UpdateNewChannelMessage; var updateDeleteChannelMessage = update as UpdateDeleteChannelMessages; var updateEditChannelMessage = update as UpdateEditChannelMessage; if (newMessage != null) { state.Pts = newMessage.Pts; } else if (deleteMessages != null) { state.Pts = deleteMessages.Pts; } else if (encryptedMessages != null) { state.Qts = encryptedMessages.Qts; } else if (readHistoryInbox != null) { state.Pts = readHistoryInbox.Pts; } else if (readHistoryOutBox != null) { state.Pts = readHistoryOutBox.Pts; } else if (updateWebPage != null) { state.Pts = updateWebPage.Pts; } else if (updateReadMessagesContents != null) { state.Pts = updateReadMessagesContents.Pts; } else if (updateEditMessage != null) { state.Pts = updateEditMessage.Pts; } else if (updateChannelTooLong != null) { //state.Pts = updateChannelTooLong.Pts; } else if (updateNewChannelMessage != null) { //for some wierd reason the PTS is a very small value //state.Pts = updateNewChannelMessage.Pts; } else if (updateDeleteChannelMessage != null) { //state.Pts = updateDeleteChannelMessage.Pts; } else if (updateEditChannelMessage != null) { //state.Pts = updateEditChannelMessage.Pts; } } RaiseOnUpdateState(state); //TODO: GZIP //TODO: remove //Console.WriteLine(ObjectDumper.Dump(body)); RaiseOnUpdate(updateList); return(TaskConstants.Completed); }
static void Main(string[] args) { FatturaElettronica.Ordinaria.FatturaOrdinaria fattura = new FatturaElettronica.Ordinaria.FatturaOrdinaria(); var s = new XmlReaderSettings { IgnoreWhitespace = true }; var r = XmlReader.Create(@"C:\temp\IT01641790702_ag2mJ.xml", s); fattura.ReadXml(r); var a = fattura.FatturaElettronicaHeader.CedentePrestatore; var personsDump = ObjectDumper.Dump(a, DumpStyle.Console); Console.WriteLine(personsDump); string sNumFattura = ""; foreach (var doc in fattura.FatturaElettronicaBody) { var datiDocumento = doc.DatiGenerali.DatiGeneraliDocumento; sNumFattura += $"Numero Fattura: {datiDocumento.Numero}" + " " + $"Data: {datiDocumento.Data.ToShortDateString()}" + System.Environment.NewLine; } sNumFattura = sNumFattura.Substring(0, sNumFattura.Length - 2); Console.WriteLine(sNumFattura); string[] stringSeparators = new string[] { "\r\n" }; string[] lines = personsDump.Split(stringSeparators, StringSplitOptions.None); foreach (string aaa in lines) { if (aaa.IndexOf(" null") == -1 && (aaa.IndexOf("{") == -1 && aaa.IndexOf("}") == -1)) { Console.WriteLine(aaa.Trim()); //But will print 3 lines in total. } } // Creating XSLCompiled object XslCompiledTransform objXSLTransform = new XslCompiledTransform(); objXSLTransform.Load(@"c:\temp\FoglioStileAssoSoftware.xsl"); // Creating StringBuilder object to hold html data and creates TextWriter object to hold data from XslCompiled.Transform method StringBuilder htmlOutput = new StringBuilder(); TextWriter htmlWriter = new StringWriter(htmlOutput); // Call Transform() method to create html string and write in TextWriter object. objXSLTransform.Transform(r, null, htmlWriter); System.IO.File.WriteAllText(@"C:\temp\fattura.html", htmlOutput.ToString()); XslTransform myXslTransform; myXslTransform = new XslTransform(); myXslTransform.Load(@"c:\temp\FoglioStileAssoSoftware.xsl"); myXslTransform.Transform(@"C:\temp\IT01641790702_ag2mJ.xml", @"C:\temp\ISBNBookList.xml"); r.Close(); string sQuery = ""; if (args.Length > 0) { foreach (Object obj in args) { sQuery += obj; } Siav.APFlibrary.Flux oFlux = new Siav.APFlibrary.Flux(); oFlux.SetCardDefaultVisibility(sQuery); // "select progressivo from archivio where progressivo = 280929 OR progressivo = 280923"); } else { Console.WriteLine("Nessuna query individuata come argomento."); } }