public async Task <JsonDocument> GetSubmissions(JsonElement filter) { var documentFilter = BsonDocument.Parse(filter.ToString()); var documentSubmissions = await _mongoRepository.GetSubmissions(documentFilter); var jsonWriterSettings = new JsonWriterSettings() { OutputMode = JsonOutputMode.Strict }; return(JsonDocument.Parse(documentSubmissions.ToJson(jsonWriterSettings))); }
public static string write <T>(T obj) { JsonWriterSettings settings = new JsonWriterSettings(); settings.PrettyPrint = false; settings.AddTypeConverter(new JsonData.AffixConverter()); StringBuilder output = new StringBuilder(); JsonWriter writer = new JsonWriter(output, settings); writer.Write(obj); return(output.ToString()); }
private static JObject GetData(int productId) { MongoClient client = new MongoClient("mongodb://*****:*****@ds020168.mlab.com:20168/asospravah"); MongoServer server = client.GetServer(); MongoDatabase database = server.GetDatabase("asospravah"); var query = Query.EQ("productID", productId); var data = database.GetCollection <BsonDocument>("ProductData").FindOne(query); var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; return(JObject.Parse(data.ToJson <MongoDB.Bson.BsonDocument>(jsonWriterSettings))); }
/// <summary> /// Addresses to classes. /// </summary> static public string ClassesToString <T>(T txtContent) where T : class { // TextAsset jsonData = Resources.Load(txtContent) as TextAsset; StringBuilder sb = new StringBuilder(); JsonWriterSettings settings = new JsonWriterSettings(); settings.PrettyPrint = true; using (JsonWriter writer = new JsonWriter(sb, settings)) { writer.Write(txtContent); } return(Regex.Unescape(sb.ToString())); }
// GET: api/ThreadProfiles public async Task <HttpResponseMessage> Get( [FromUri] string repository, [FromUri] int page, [FromUri] int length, [FromUri] DateTime?start, [FromUri] DateTime?end, [FromUri] string tags) { EasyAnalysis.Framework.ConnectionStringProviders.IConnectionStringProvider mongoDBCSProvider = EasyAnalysis.Framework.ConnectionStringProviders.ConnectionStringProvider.CreateConnectionStringProvider(EasyAnalysis.Framework.ConnectionStringProviders.ConnectionStringProvider.ConnectionStringProviderType.MongoDBConnectionStringProvider); var client = new MongoClient(mongoDBCSProvider.GetConnectionString(repository));//"mongodb://app-svr.cloudapp.net:27017/" + repository); var database = client.GetDatabase(repository); var threadProfiles = database.GetCollection <BsonDocument>("thread_profiles"); var builder = Builders <BsonDocument> .Filter; FilterDefinition <BsonDocument> filter = "{}"; if (start.HasValue && end.HasValue) { filter = filter & builder.Gte("create_on", start) & builder.Lt("create_on", end); } if (!string.IsNullOrWhiteSpace(tags)) { var array = tags.Split('|'); filter = filter & builder.All("tags", array); } var result = await threadProfiles .Find(filter) .Sort("{create_on: -1}") .Skip((page - 1) * length) .Limit(length) .ToListAsync(); var response = Request.CreateResponse(); response.StatusCode = HttpStatusCode.OK; var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; response.Content = new StringContent(result.ToJson(jsonWriterSettings), Encoding.UTF8, "application/json"); return(response); }
public void TestObjectIdStrict() { var objectId = new ObjectId("4d0ce088e447ad08b4721a37"); #pragma warning disable 618 var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; #pragma warning restore 618 var json = objectId.ToJson(jsonSettings); var expected = "{ \"$oid\" : \"4d0ce088e447ad08b4721a37\" }"; Assert.Equal(expected, json); Assert.Equal(objectId, BsonSerializer.Deserialize <ObjectId>(json)); }
private string SerializeBsonDocument(BsonDocument value) { var jsonWriterSettings = new JsonWriterSettings { GuidRepresentation = GuidRepresentation.Unspecified }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonWriter(stringWriter, jsonWriterSettings)) { var context = BsonSerializationContext.CreateRoot(jsonWriter); BsonDocumentSerializer.Instance.Serialize(context, value); return(stringWriter.ToString()); } }
public void TestNotNinIEnumerableBsonValue() { var enumerable = new List <BsonValue> { 1, 2, null, 3 }; // null will be skipped due to functional construction semantics var query = Query.Not(Query.NotIn("name", enumerable)); var expected = "{ \"name\" : { \"$not\" : { \"$nin\" : [1, 2, 3] } } }"; JsonWriterSettings settings = new JsonWriterSettings { OutputMode = JsonOutputMode.JavaScript }; var actual = query.ToJson(settings); Assert.AreEqual(expected, actual); }
public string GetDocumentByIdWithObjectIdInArray(string collectionName, string key, string value) { var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; var collection = mongoDB.GetCollection(collectionName); var array = new List <string>() { value }; var query = Query.In("Tags", new BsonArray(array)); return(collection.FindAs <BsonDocument>(query).ToJson(jsonSettings)); }
public void TestIndentedTwoElements() { BsonDocument document = new BsonDocument() { { "a", "x" }, { "b", "y" } }; var settings = new JsonWriterSettings { Indent = true }; string json = document.ToJson(settings); string expected = "{\r\n \"a\" : \"x\",\r\n \"b\" : \"y\"\r\n}"; Assert.Equal(expected, json); }
public Packet() { type = 0; operation = 0; output = new StringBuilder(); JsonWriterSettings settings = new JsonWriterSettings(); settings.PrettyPrint = false; settings.AddTypeConverter(new VectorConverter()); settings.AddTypeConverter(new QuaternionConverter()); // TODO: Add any other TypeConverters here writer = new JsonWriter(output, settings); }
public void TestDateTimeShell(string json, long expectedResult, string canonicalJson) { using (_bsonReader = new JsonReader(json)) { Assert.Equal(BsonType.DateTime, _bsonReader.ReadBsonType()); Assert.Equal(expectedResult, _bsonReader.ReadDateTime()); Assert.Equal(BsonReaderState.Initial, _bsonReader.State); } var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Shell }; Assert.Equal(canonicalJson, BsonSerializer.Deserialize <DateTime>(json).ToJson(jsonSettings)); }
public void TestIndentedOneElement() { BsonDocument document = new BsonDocument() { { "name", "value" } }; var settings = new JsonWriterSettings { Indent = true }; string json = document.ToJson(settings); string expected = "{\r\n \"name\" : \"value\"\r\n}"; Assert.Equal(expected, json); }
public void TestNotInBsonArray() { var array = new BsonArray { 1, 2, null, 3 }; // null will be skipped due to functional construction semantics var query = Query.Not(Query.In("name", array)); var expected = "{ \"name\" : { \"$nin\" : [1, 2, 3] } }"; JsonWriterSettings settings = new JsonWriterSettings { OutputMode = JsonOutputMode.JavaScript }; var actual = query.ToJson(settings); Assert.AreEqual(expected, actual); }
/// <summary> /// Converts an object to a JSON string. /// </summary> /// <param name="obj">The object.</param> /// <param name="nominalType">The nominal type of the object.</param> /// <param name="options">The serialization options.</param> /// <param name="settings">The JsonWriter settings.</param> /// <returns>A JSON string.</returns> public static string ToJson( this object obj, Type nominalType, IBsonSerializationOptions options, JsonWriterSettings settings ) { using (var stringWriter = new StringWriter()) { using (var bsonWriter = BsonWriter.Create(stringWriter, settings)) { BsonSerializer.Serialize(bsonWriter, nominalType, obj, options); } return(stringWriter.ToString()); } }
public void TestBinaryStrict( [ClassValues(typeof(GuidModeValues))] GuidMode mode) { mode.Set(); #pragma warning disable 618 var guid = Guid.Parse("00112233-4455-6677-8899-aabbccddeeff"); var tests = new List <TestData <BsonBinaryData> > { new TestData <BsonBinaryData>(new byte[] { }, "{ \"$binary\" : \"\", \"$type\" : \"00\" }"), new TestData <BsonBinaryData>(new byte[] { 1 }, "{ \"$binary\" : \"AQ==\", \"$type\" : \"00\" }"), new TestData <BsonBinaryData>(new byte[] { 1, 2 }, "{ \"$binary\" : \"AQI=\", \"$type\" : \"00\" }"), new TestData <BsonBinaryData>(new byte[] { 1, 2, 3 }, "{ \"$binary\" : \"AQID\", \"$type\" : \"00\" }") }; if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2 && BsonDefaults.GuidRepresentation != GuidRepresentation.Unspecified) { byte[] expectedBytes; string expectedSubType; switch (BsonDefaults.GuidRepresentation) { case GuidRepresentation.CSharpLegacy: case GuidRepresentation.JavaLegacy: case GuidRepresentation.PythonLegacy: expectedBytes = GuidConverter.ToBytes(guid, BsonDefaults.GuidRepresentation); expectedSubType = "03"; break; case GuidRepresentation.Standard: expectedBytes = GuidConverter.ToBytes(guid, GuidRepresentation.Standard); expectedSubType = "04"; break; default: throw new Exception("Invalid GuidRepresentation."); } var expectedBase64 = Convert.ToBase64String(expectedBytes); var expectedGuidJson = $"{{ \"$binary\" : \"{expectedBase64}\", \"$type\" : \"{expectedSubType}\" }}"; tests.Add(new TestData <BsonBinaryData>(guid, expectedGuidJson)); } var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; foreach (var test in tests) { var json = test.Value.ToJson(jsonSettings); Assert.Equal(test.Expected, json); Assert.Equal(test.Value, BsonSerializer.Deserialize <BsonBinaryData>(new JsonReader(json, new JsonReaderSettings()))); } #pragma warning restore 618 }
public static void Equal(object expected, BsonDocument actual) { // Assert => EventData matches var settings = new JsonWriterSettings { OutputMode = JsonOutputMode.Shell, Indent = false }; var docAsJson = actual.ToJson(settings); var actualCleaned = Regex.Replace(docAsJson, "(\"(?:[^\"\\\\]|\\\\.)*\")|\\s+", "$1"); Assert.Equal(Newtonsoft.Json.JsonConvert.SerializeObject(expected), actualCleaned); }
public string GetFieldStructure(string fieldName) { var array = fieldName.Split('.'); var exampleStructure = _mongoClient.GetDatabase(JsonAccessControlSetting.UserDefaultDatabaseName) .GetCollection <BsonDocument>(array[0]) .Find(_ => true) .First(); var jsonSetting = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; var json = exampleStructure.ToJson(jsonSetting); string result = JObject.Parse(json).SelectToken("projects").ToString(); return(result); }
/// <summary> /// Ctor /// </summary> /// <param name="output">TextWriter for writing</param> /// <param name="settings">JsonWriterSettings</param> public JsonWriter(TextWriter output, JsonWriterSettings settings) { if (output == null) { throw new ArgumentNullException("output"); } if (settings == null) { throw new ArgumentNullException("settings"); } this.Writer = output; this.settings = settings; this.Writer.NewLine = this.settings.NewLine; }
/// <summary> /// Ctor /// </summary> /// <param name="output">StringBuilder for appending</param> /// <param name="settings">JsonWriterSettings</param> public JsonWriter(StringBuilder output, JsonWriterSettings settings) { if (output == null) { throw new ArgumentNullException("output"); } if (settings == null) { throw new ArgumentNullException("settings"); } this.Writer = new StringWriter(output, System.Globalization.CultureInfo.InvariantCulture); this.settings = settings; this.Writer.NewLine = this.settings.NewLine; }
/// <summary> /// Ctor /// </summary> /// <param name="output">Stream for writing</param> /// <param name="settings">JsonWriterSettings</param> public JsonWriter(Stream output, JsonWriterSettings settings) { if (output == null) { throw new ArgumentNullException("output"); } if (settings == null) { throw new ArgumentNullException("settings"); } this.Writer = new StreamWriter(output, Encoding.UTF8); this.settings = settings; this.Writer.NewLine = this.settings.NewLine; }
public void TestDateTimeTengen() { var json = "new Date(0)"; using (bsonReader = BsonReader.Create(json)) { Assert.AreEqual(BsonType.DateTime, bsonReader.ReadBsonType()); Assert.AreEqual(0, bsonReader.ReadDateTime()); Assert.AreEqual(BsonReaderState.Done, bsonReader.State); } var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.TenGen }; Assert.AreEqual(json, BsonSerializer.Deserialize <DateTime>(new StringReader(json)).ToJson(jsonSettings)); }
public void TestDateTimeShell() { var json = "ISODate(\"1970-01-01T00:00:00Z\")"; using (bsonReader = BsonReader.Create(json)) { Assert.AreEqual(BsonType.DateTime, bsonReader.ReadBsonType()); Assert.AreEqual(0, bsonReader.ReadDateTime()); Assert.AreEqual(BsonReaderState.Done, bsonReader.State); } var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Shell }; Assert.AreEqual(json, BsonSerializer.Deserialize <DateTime>(new StringReader(json)).ToJson(jsonSettings)); }
public static string WritePretty(object obj) { JsonWriterSettings settings = new JsonWriterSettings(); settings.PrettyPrint = true; JsonFx.Json.JsonDataWriter writer = new JsonDataWriter(settings); StringWriter wr = new StringWriter(); writer.Serialize(wr, obj); string json = wr.ToString(); return(json); }
public void TestInt64NumberLong() { var json = "NumberLong(123)"; using (bsonReader = BsonReader.Create(json)) { Assert.AreEqual(BsonType.Int64, bsonReader.ReadBsonType()); Assert.AreEqual(123, bsonReader.ReadInt64()); Assert.AreEqual(BsonReaderState.Done, bsonReader.State); } var settings = new JsonWriterSettings { OutputMode = JsonOutputMode.TenGen }; Assert.AreEqual(json, BsonSerializer.Deserialize <long>(new StringReader(json)).ToJson(settings)); }
public void OpenSerialize() { this.zip = new ZipFile(); this.zip.AlternateEncoding = Encoding.UTF8; this.zip.AlternateEncodingUsage = ZipOption.Always; this.writerSettings = new JsonWriterSettings(); this.writerSettings.AddTypeConverter(new VectorConverter()); this.writerSettings.AddTypeConverter(new BoundsConverter()); this.writerSettings.AddTypeConverter(new LayerMaskConverter()); this.writerSettings.AddTypeConverter(new MatrixConverter()); this.writerSettings.AddTypeConverter(new GuidConverter()); this.writerSettings.AddTypeConverter(new UnityObjectConverter()); this.writerSettings.PrettyPrint = this.settings.prettyPrint; this.meta = new GraphMeta(); }
public string GetAllCollections(string databaseName) { var database = client.GetDatabase(databaseName); var collections = database.ListCollectionNames().ToList(); if (!collections.Any()) { throw new ArgumentException(); } var jsonWriteSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.CanonicalExtendedJson }; return(collections.ToJson()); }
internal static string PrintBsonDocument(BsonDocument value) { var stringWriter = new StringWriter(); var args = new JsonWriterSettings() { Indent = true }; using (var jsonWriter = new JsonWriter(stringWriter, args)) { var context = BsonSerializationContext.CreateRoot(jsonWriter); BsonDocumentSerializer.Instance.Serialize(context, value); } return(stringWriter.ToString()); }
public string GetAllProducts() { var db = _client.GetDatabase("ProductsDataBase"); var collection = db.GetCollection <BsonDocument>("Products"); var filter = new BsonDocument(); var products = collection.Find(filter).ToList(); var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; var jsonResult = products.ToJson <List <BsonDocument> >(jsonWriterSettings); return(jsonResult); }
public void TestNotAllBsonArrayCastToIEnumerableBsonValue() { var array = new BsonArray { 1, 2, null, 3 }; // null will be skipped due to functional construction semantics var enumerable = (IEnumerable <BsonValue>)array; var query = Query.Not(Query.All("name", enumerable)); var expected = "{ \"name\" : { \"$not\" : { \"$all\" : [1, 2, 3] } } }"; JsonWriterSettings settings = new JsonWriterSettings { OutputMode = JsonOutputMode.JavaScript }; var actual = query.ToJson(settings); Assert.AreEqual(expected, actual); }