public void Randomize() { if (model.RandomizeCampingSkills) { var file = JsonNode.Parse(File.ReadAllText(model.GetGameDataPath(Path.Combine("raid", "camping", "default.camping_skills.json")))) ?.AsObject(); if (file == null || file["skills"] is not JsonArray skills || skills.Count < 7) { throw new Exception("default.camping_skills.json could not be parsed properly."); } // Make in-game layout look prettier :) file["configuration"] !.AsObject()["class_specific_number_of_classes_threshold"] = JsonValue.Create(100); var layoutFile = Darkest.LoadFromFile(model.GetGameDataPath(Path.Combine("campaign", "town", "buildings", "camping_trainer", "camping_trainer.layout.darkest"))); layoutFile.Replace("camping_trainer_class_specific_skill_grid_layout", "skill_spacing", (x, _, i) => i == 1 ? "170" : x) .WriteToFile(Path.Combine( model.ModDirectory .CreateSubdirectory("campaign") .CreateSubdirectory("town") .CreateSubdirectory("buildings") .CreateSubdirectory("camping_trainer") .FullName, "camping_trainer.layout.darkest")); foreach (var skill in skills) { skill !.AsObject()["hero_classes"] = new JsonArray(); } foreach (var hero in model.HeroNames) { HashSet <int> skillIndicies = new HashSet <int>(); while (skillIndicies.Count < 7) { skillIndicies.Add(random.Next(0, skills.Count)); } foreach (var skillIndex in skillIndicies) { skills[skillIndex]?.AsObject()["hero_classes"]?.AsArray().Add(hero); } } File.WriteAllText(Path.Combine( model.ModDirectory .CreateSubdirectory("raid") .CreateSubdirectory("camping") .FullName, "default.camping_skills.json"), file.ToJsonString(new() { WriteIndented = true })); } }
public async Task Should_throw_exception_if_nested_not_an_object() { await sut.SetAsync("root.nested", JsonValue.Create(123).AsJ()); await Assert.ThrowsAsync <InvalidOperationException>(() => sut.SetAsync("root.nested.value", JsonValue.Create(123).AsJ())); }
public IJsonValue Visit(IField <StringFieldProperties> field) { var value = GetDefaultValue(field.Properties.DefaultValue, field.Properties.DefaultValues); return(JsonValue.Create(value)); }
private static IJsonValue ReadJson(JsonReader reader) { switch (reader.TokenType) { case JsonToken.Comment: reader.Read(); break; case JsonToken.StartObject: { var result = JsonValue.Object(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: var propertyName = reader.Value !.ToString() !; if (!reader.Read()) { throw new JsonSerializationException("Unexpected end when reading Object."); } var value = ReadJson(reader); result[propertyName] = value; break; case JsonToken.EndObject: return(result); } } throw new JsonSerializationException("Unexpected end when reading Object."); } case JsonToken.StartArray: { var result = JsonValue.Array(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.Comment: continue; case JsonToken.EndArray: return(result); default: var value = ReadJson(reader); result.Add(value); break; } } throw new JsonSerializationException("Unexpected end when reading Object."); } case JsonToken.Integer when reader.Value is int i: return(JsonValue.Create(i)); case JsonToken.Integer when reader.Value is long l: return(JsonValue.Create(l)); case JsonToken.Float when reader.Value is float f: return(JsonValue.Create(f)); case JsonToken.Float when reader.Value is double d: return(JsonValue.Create(d)); case JsonToken.Boolean when reader.Value is bool b: return(JsonValue.Create(b)); case JsonToken.Date when reader.Value is DateTime d: return(JsonValue.Create(d.ToIso8601())); case JsonToken.String when reader.Value is string s: return(JsonValue.Create(s)); case JsonToken.Null: case JsonToken.Undefined: return(JsonValue.Null); } throw new NotSupportedException(); }
public IJsonValue Visit(IField <StringFieldProperties> field) { return(JsonValue.Create(field.Properties.DefaultValue)); }
public static IJsonValue Map(JsValue?value) { if (value == null || value.IsNull() || value.IsUndefined()) { return(JsonValue.Null); } if (value.IsString()) { return(JsonValue.Create(value.AsString())); } if (value.IsBoolean()) { return(JsonValue.Create(value.AsBoolean())); } if (value.IsNumber()) { return(JsonValue.Create(value.AsNumber())); } if (value.IsDate()) { return(JsonValue.Create(value.AsDate().ToString())); } if (value.IsRegExp()) { return(JsonValue.Create(value.AsRegExp().Value?.ToString())); } if (value.IsArray()) { var arr = value.AsArray(); var result = JsonValue.Array(); for (var i = 0; i < arr.Length; i++) { result.Add(Map(arr.Get(i.ToString(CultureInfo.InvariantCulture)))); } return(result); } if (value.IsObject()) { var obj = value.AsObject(); var result = JsonValue.Object(); foreach (var(key, propertyDescriptor) in obj.GetOwnProperties()) { result[key.AsString()] = Map(propertyDescriptor.Value); } return(result); } throw new ArgumentException("Invalid json type.", nameof(value)); }
public async Task Should_write_and_read_events_to_backup(BackupVersion version) { var randomGenerator = new Random(); var randomDomainIds = new List <DomainId>(); for (var i = 0; i < 100; i++) { randomDomainIds.Add(DomainId.NewGuid()); } DomainId RandomDomainId() { return(randomDomainIds[randomGenerator.Next(randomDomainIds.Count)]); } var sourceEvents = new List <(string Stream, Envelope <MyEvent> Event)>(); for (var i = 0; i < 200; i++) { var @event = new MyEvent(); var envelope = Envelope.Create(@event); envelope.Headers.Add("Id", JsonValue.Create(@event.Id)); envelope.Headers.Add("Index", JsonValue.Create(i)); sourceEvents.Add(($"My-{RandomDomainId()}", envelope)); } await TestReaderWriterAsync(version, async writer => { foreach (var(stream, envelope) in sourceEvents) { var eventData = formatter.ToEventData(envelope, Guid.NewGuid(), true); var eventStored = new StoredEvent(stream, "1", 2, eventData); var index = int.Parse(envelope.Headers["Index"].ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture); if (index % 17 == 0) { await WriteGuidAsync(writer, index.ToString(CultureInfo.InvariantCulture), envelope.Payload.Id); } else if (index % 37 == 0) { await WriteJsonGuidAsync(writer, index.ToString(CultureInfo.InvariantCulture), envelope.Payload.Id); } writer.WriteEvent(eventStored); } }, async reader => { var targetEvents = new List <(string Stream, Envelope <IEvent> Event)>(); await foreach (var @event in reader.ReadEventsAsync(streamNameResolver, formatter)) { var index = int.Parse(@event.Event.Headers["Index"].ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture); var id = Guid.Parse(@event.Event.Headers["Id"].ToString()); if (index % 17 == 0) { var guid = await ReadGuidAsync(reader, index.ToString(CultureInfo.InvariantCulture)); Assert.Equal(id, guid); } else if (index % 37 == 0) { var guid = await ReadJsonGuidAsync(reader, index.ToString(CultureInfo.InvariantCulture)); Assert.Equal(id, guid); } targetEvents.Add(@event); } for (var i = 0; i < targetEvents.Count; i++) { var targetEvent = targetEvents[i].Event.To <MyEvent>(); var targetStream = targetEvents[i].Stream; var sourceEvent = sourceEvents[i].Event.To <MyEvent>(); var sourceStream = sourceEvents[i].Stream; Assert.Equal(sourceEvent.Payload.Id, targetEvent.Payload.Id); Assert.Equal(sourceStream, targetStream); } }); }
private static IJsonValue CreateValue(Instant v) { return(JsonValue.Create(v.ToString())); }
private static IJsonValue CreateValue(bool?v) { return(JsonValue.Create(v)); }
private static IJsonValue CreateValue(Instant v) { return(JsonValue.Create(v)); }
public AssetsQueryFixture() { mongoDatabase = mongoClient.GetDatabase("QueryTests"); SetupJson(); var assetRepository = new MongoAssetRepository(mongoDatabase); Task.Run(async() => { await assetRepository.InitializeAsync(); await mongoDatabase.RunCommandAsync <BsonDocument>("{ profile : 0 }"); await mongoDatabase.DropCollectionAsync("system.profile"); var collection = assetRepository.GetInternalCollection(); var assetCount = await collection.Find(new BsonDocument()).CountDocumentsAsync(); if (assetCount == 0) { var batch = new List <MongoAssetEntity>(); async Task ExecuteBatchAsync(MongoAssetEntity? entity) { if (entity != null) { batch.Add(entity); } if ((entity == null || batch.Count >= 1000) && batch.Count > 0) { await collection.InsertManyAsync(batch); batch.Clear(); } } foreach (var appId in AppIds) { for (var i = 0; i < numValues; i++) { var fileName = i.ToString(); for (var j = 0; j < numValues; j++) { var tag = j.ToString(); var asset = new MongoAssetEntity { Id = Guid.NewGuid(), AppId = appId, Tags = new HashSet <string> { tag }, FileHash = fileName, FileName = fileName, FileSize = 1024, IndexedAppId = appId.Id, IsDeleted = false, IsProtected = false, Metadata = new AssetMetadata { ["value"] = JsonValue.Create(tag) }, Slug = fileName, }; await ExecuteBatchAsync(asset); } } } await ExecuteBatchAsync(null); } await mongoDatabase.RunCommandAsync <BsonDocument>("{ profile : 2 }"); }).Wait(); AssetRepository = assetRepository; }
public AssetMetadata SetPixelHeight(int value) { this["pixelHeight"] = JsonValue.Create(value); return(this); }
public AssetMetadata SetPixelWidth(int value) { this["pixelWidth"] = JsonValue.Create(value); return(this); }
(_, var shuffled) => new JsonArray(shuffled.Select(s => JsonValue.Create(s)).ToArray())
protected override bool VisitPart(ConfigurationKeyPart keyPart) { var isLast = keyPart.PartIndex == (Parts.Length - 1); var name = Parts[keyPart.PartIndex]; if (origin is JsonObject) { if (isLast) { origin[name] = Value; } else { var objTk = origin[name]; if (objTk is null) { if (!IgnoreAdd) { var next = Parts[keyPart.PartIndex + 1]; JsonNode ctk = null; if (int.TryParse(next, out _)) { ctk = new JsonArray(); } else { ctk = new JsonObject(); } origin[name] = ctk; origin = ctk; } else { origin = JsonValue.Create((object)null); } } else { origin = origin[name]; } } } else if (origin is JsonArray) { var arr = (JsonArray)origin; if (!int.TryParse(name, out var index)) { return(false); } for (int j = arr.Count; j < index + 1; j++) { arr.Add(null); } if (isLast) { arr[index] = Value; } else { var val = arr[index]; if (val is null || val.GetValue <string>() == null) { if (!IgnoreAdd) { var next = Parts[keyPart.PartIndex + 1]; if (int.TryParse(next, out _)) { origin = new JsonArray(); } else { origin = new JsonObject(); } arr[index] = origin; } else { origin = JsonValue.Create <string>(null); } } else { origin = val; } }
private static IJsonValue CreateValue(string?v) { return(JsonValue.Create(v)); }
/// <summary> /// Tests serialization of a given value within the context of multiple types: /// root values, object properties, collection elements, dictionary values, etc. /// </summary> protected async Task TestMultiContextSerialization <TValue>( TValue value, string expectedJson, Type?expectedExceptionType = null, SerializedValueContext contexts = SerializedValueContext.All, JsonSerializerOptions?options = null) { Assert.True((contexts & SerializedValueContext.All) != SerializedValueContext.None); string actualJson; if (contexts.HasFlag(SerializedValueContext.RootValue)) { if (expectedExceptionType != null) { await Assert.ThrowsAsync(expectedExceptionType, () => Serializer.SerializeWrapper(value, options)); } else { actualJson = await Serializer.SerializeWrapper(value, options); JsonTestHelper.AssertJsonEqual(expectedJson, actualJson); } } if (contexts.HasFlag(SerializedValueContext.ObjectProperty)) { var poco = new GenericPoco <TValue> { Property = value }; if (expectedExceptionType != null) { await Assert.ThrowsAsync(expectedExceptionType, () => Serializer.SerializeWrapper(poco, options)); } else { string propertyName = options?.PropertyNamingPolicy is JsonNamingPolicy policy ? policy.ConvertName(nameof(GenericPoco <TValue> .Property)) : nameof(GenericPoco <TValue> .Property); actualJson = await Serializer.SerializeWrapper(poco, options); JsonTestHelper.AssertJsonEqual($@"{{ ""{propertyName}"" : {expectedJson} }}", actualJson); } } if (contexts.HasFlag(SerializedValueContext.CollectionElement)) { var list = new List <TValue> { value }; if (expectedExceptionType != null) { await Assert.ThrowsAsync(expectedExceptionType, () => Serializer.SerializeWrapper(list, options)); } else { actualJson = await Serializer.SerializeWrapper(list, options); JsonTestHelper.AssertJsonEqual($"[{expectedJson}]", actualJson); } } if (contexts.HasFlag(SerializedValueContext.DictionaryValue)) { const string key = "key"; var dictionary = new Dictionary <string, TValue> { [key] = value }; if (expectedExceptionType != null) { await Assert.ThrowsAsync(expectedExceptionType, () => Serializer.SerializeWrapper(dictionary, options)); } else { string jsonKey = options?.DictionaryKeyPolicy is JsonNamingPolicy policy ? policy.ConvertName(key) : key; actualJson = await Serializer.SerializeWrapper(dictionary, options); JsonTestHelper.AssertJsonEqual($@"{{ ""{jsonKey}"" : {expectedJson} }}", actualJson); } } if (contexts.HasFlag(SerializedValueContext.JsonNode)) { const string key = "key"; var jsonObject = new JsonObject { [key] = JsonValue.Create <TValue>(value) }; if (expectedExceptionType != null) { await Assert.ThrowsAsync(expectedExceptionType, () => Serializer.SerializeWrapper(jsonObject, options)); } else { actualJson = await Serializer.SerializeWrapper(jsonObject, options); JsonTestHelper.AssertJsonEqual($@"{{ ""{key}"" : {expectedJson} }}", actualJson); } } }
public static Envelope <T> SetEventPosition <T>(this Envelope <T> envelope, string value) where T : class, IEvent { envelope.Headers[CommonHeaders.EventNumber] = JsonValue.Create(value); return(envelope); }
private static IJsonValue CreateValue(double v) { return(JsonValue.Create(v)); }
public static Envelope <T> SetEventStreamNumber <T>(this Envelope <T> envelope, long value) where T : class, IEvent { envelope.Headers[CommonHeaders.EventStreamNumber] = JsonValue.Create(value); return(envelope); }
public static FieldConverter ResolveAssetUrls(IReadOnlyCollection <string>?fields, IUrlGenerator urlGenerator) { if (fields?.Any() != true) { return((data, field) => data); } bool ShouldHandle(IField field, IField?parent = null) { if (field is IField <AssetsFieldProperties> ) { if (fields.Contains("*")) { return(true); } if (parent == null) { return(fields.Contains(field.Name)); } else { return(fields.Contains($"{parent.Name}.{field.Name}")); } } return(false); } void Resolve(IJsonValue value) { if (value is JsonArray array) { for (var i = 0; i < array.Count; i++) { var id = array[i].ToString(); array[i] = JsonValue.Create(urlGenerator.AssetContent(Guid.Parse(id))); } } } return((data, field) => { if (ShouldHandle(field)) { foreach (var partition in data) { Resolve(partition.Value); } } else if (field is IArrayField arrayField) { foreach (var partition in data) { if (partition.Value is JsonArray array) { for (var i = 0; i < array.Count; i++) { if (array[i] is JsonObject arrayItem) { foreach (var(key, value) in arrayItem) { if (arrayField.FieldsByName.TryGetValue(key, out var nestedField) && ShouldHandle(nestedField, field)) { Resolve(value); } } } } } } } return data; }); }
public static Envelope <T> SetAggregateId <T>(this Envelope <T> envelope, DomainId value) where T : class, IEvent { envelope.Headers[CommonHeaders.AggregateId] = JsonValue.Create(value); return(envelope); }
public async Task Should_convert_json_query_and_enrich_with_defaults() { var query = Q.Empty.WithJsonQuery( new Query <IJsonValue> { Filter = new CompareFilter <IJsonValue>("data.firstName.iv", CompareOperator.Equals, JsonValue.Create("ABC")) }); var q = await sut.ParseAsync(requestContext, query, schema); Assert.Equal("Filter: data.firstName.iv == 'ABC'; Take: 30; Sort: lastModified Descending, id Ascending", q.Query.ToString()); }
public static Envelope <T> SetEventId <T>(this Envelope <T> envelope, Guid value) where T : class, IEvent { envelope.Headers[CommonHeaders.EventId] = JsonValue.Create(value); return(envelope); }
private static IJsonValue ReadJson(JsonReader reader) { switch (reader.TokenType) { case JsonToken.Comment: reader.Read(); break; case JsonToken.StartObject: { var result = JsonValue.Object(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: var propertyName = reader.Value.ToString() !; if (!reader.Read()) { throw new JsonSerializationException("Unexpected end when reading Object."); } var value = ReadJson(reader); result[propertyName] = value; break; case JsonToken.EndObject: return(result); } } throw new JsonSerializationException("Unexpected end when reading Object."); } case JsonToken.StartArray: { var result = JsonValue.Array(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.Comment: break; default: var value = ReadJson(reader); result.Add(value); break; case JsonToken.EndArray: return(result); } } throw new JsonSerializationException("Unexpected end when reading Object."); } case JsonToken.Integer: return(JsonValue.Create((long)reader.Value)); case JsonToken.Float: return(JsonValue.Create((double)reader.Value)); case JsonToken.Boolean: return(JsonValue.Create((bool)reader.Value)); case JsonToken.Date: return(JsonValue.Create(((DateTime)reader.Value).ToString("yyyy-MM-ddTHH:mm:ssK", CultureInfo.InvariantCulture))); case JsonToken.String: return(JsonValue.Create(reader.Value.ToString())); case JsonToken.Null: case JsonToken.Undefined: return(JsonValue.Null); } throw new NotSupportedException(); }
public static Envelope <T> SetTimestamp <T>(this Envelope <T> envelope, Instant value) where T : class, IEvent { envelope.Headers[CommonHeaders.Timestamp] = JsonValue.Create(value); return(envelope); }
private async Task SetupAsync(MongoContentRepository contentRepository, IMongoDatabase database) { await contentRepository.InitializeAsync(); await database.RunCommandAsync <BsonDocument>("{ profile : 0 }"); await database.DropCollectionAsync("system.profile"); var collections = contentRepository.GetInternalCollections(); foreach (var collection in collections) { var contentCount = await collection.Find(new BsonDocument()).CountDocumentsAsync(); if (contentCount == 0) { var batch = new List <MongoContentEntity>(); async Task ExecuteBatchAsync(MongoContentEntity?entity) { if (entity != null) { batch.Add(entity); } if ((entity == null || batch.Count >= 1000) && batch.Count > 0) { await collection.InsertManyAsync(batch); batch.Clear(); } } foreach (var appId in AppIds) { foreach (var schemaId in SchemaIds) { for (var i = 0; i < numValues; i++) { var data = new ContentData() .AddField("field1", new ContentFieldData() .AddInvariant(JsonValue.Create(i))) .AddField("field2", new ContentFieldData() .AddInvariant(JsonValue.Create(Lorem.Paragraph(200, 20)))); var content = new MongoContentEntity { DocumentId = DomainId.NewGuid(), AppId = appId, Data = data, IndexedAppId = appId.Id, IndexedSchemaId = schemaId.Id, IsDeleted = false, SchemaId = schemaId, Status = Status.Published }; await ExecuteBatchAsync(content); } } } await ExecuteBatchAsync(null); } } await database.RunCommandAsync <BsonDocument>("{ profile : 2 }"); }
public static Envelope <T> SetRestored <T>(this Envelope <T> envelope, bool value = true) where T : class, IEvent { envelope.Headers[CommonHeaders.Restored] = JsonValue.Create(value); return(envelope); }
public AssetMetadata SetFocusY(float value) { this[FocusY] = JsonValue.Create(value); return(this); }
public ContentsQueryFixture() { mongoDatabase = mongoClient.GetDatabase("QueryTests"); SetupJson(); var contentRepository = new MongoContentRepository( mongoDatabase, CreateAppProvider(), CreateTextIndexer(), JsonHelper.DefaultSerializer); Task.Run(async() => { await contentRepository.InitializeAsync(); await mongoDatabase.RunCommandAsync <BsonDocument>("{ profile : 0 }"); await mongoDatabase.DropCollectionAsync("system.profile"); var collections = contentRepository.GetInternalCollections(); foreach (var collection in collections) { var contentCount = await collection.Find(new BsonDocument()).CountDocumentsAsync(); if (contentCount == 0) { var batch = new List <MongoContentEntity>(); async Task ExecuteBatchAsync(MongoContentEntity? entity) { if (entity != null) { batch.Add(entity); } if ((entity == null || batch.Count >= 1000) && batch.Count > 0) { await collection.InsertManyAsync(batch); batch.Clear(); } } foreach (var appId in AppIds) { foreach (var schemaId in SchemaIds) { for (var i = 0; i < numValues; i++) { var data = new IdContentData() .AddField(1, new ContentFieldData() .AddJsonValue(JsonValue.Create(i))) .AddField(2, new ContentFieldData() .AddJsonValue(JsonValue.Create(Lorem.Paragraph(200, 20)))); var content = new MongoContentEntity { DocumentId = DomainId.NewGuid(), AppId = appId, DataByIds = data, IndexedAppId = appId.Id, IndexedSchemaId = schemaId.Id, IsDeleted = false, SchemaId = schemaId, Status = Status.Published }; await ExecuteBatchAsync(content); } } } await ExecuteBatchAsync(null); } } await mongoDatabase.RunCommandAsync <BsonDocument>("{ profile : 2 }"); }).Wait(); ContentRepository = contentRepository; }