public GenericDataContainer Reassemble(GenericDataContainer containerWithoutBinaryData, byte[] binaryData) { var containerWithData = CloneGenericDataContainer(containerWithoutBinaryData); containerWithData.Data.Set(binaryDataPath, BsonString.Create(Convert.ToBase64String(binaryData))); return(containerWithData); }
public void InsertOne_BsonDocument_ExpectedDocumentInserted() { /// Arrange // Get an id for the document. var id = Guid.NewGuid().ToString(); // Get some expected bson document with the id. var expected = new BsonDocument() .Add(new BsonElement("_id", BsonString.Create(id))) .Add(new BsonElement("hello", BsonString.Create("world"))); // Get a collection. var collection = new MongoClient("mongodb://localhost:27017") .GetDatabase("jcs") .GetCollection <BsonDocument>("events"); /// Act // Insert the document into the collection. collection.InsertOne(expected); // Get the document back. var actual = collection.Find( new FilterDefinitionBuilder <BsonDocument>().Eq <string>( new StringFieldDefinition <BsonDocument, string>("_id"), id)) .Single(); /// Assert // Verify that the actual document matches the expected document. Assert.Equal(expected, actual); }
private void CollectionView_AfterSelect(object sender, TreeViewEventArgs e) { editPanel.Enabled = true; addButton.Enabled = false; removeButton.Enabled = true; button1.Enabled = true; if (e.Node.Tag is BsonDocument) { changeTypeComboBox.Enabled = false; NameEditTextBox.Enabled = false; ValueEditTextBox.Enabled = false; ValueEditTextBox.Text = ""; NameEditTextBox.Text = ""; changeTypeComboBox.Text = ""; addButton.Enabled = true; } else if (e.Node.Tag is BsonElement) { BsonElement element = (BsonElement)e.Node.Tag; changeTypeComboBox.Enabled = true; changeTypeComboBox.Text = element.Value.BsonType.ToString(); NameEditTextBox.Enabled = true; NameEditTextBox.Text = element.Name; if (element.Value.BsonType != BsonType.Array && element.Value.BsonType != BsonType.Document) { ValueEditTextBox.Enabled = true; ValueEditTextBox.Text = element.Value.ToString(); } else { ValueEditTextBox.Enabled = false; ValueEditTextBox.Text = ""; addButton.Enabled = true; } } else if (e.Node.Tag is BsonString) { removeButton.Enabled = true; button1.Enabled = true; BsonString element = (BsonString)e.Node.Tag; changeTypeComboBox.Enabled = true; changeTypeComboBox.Text = element.BsonType.ToString(); NameEditTextBox.Enabled = false; NameEditTextBox.Text = ""; ValueEditTextBox.Enabled = true; ValueEditTextBox.Text = element.Value; } if (LastSelectedNode != null) { LastSelectedNode.BackColor = LastSelectedColor; } PanelSelectedElement = e.Node; LastSelectedColor = CollectionView.SelectedNode.BackColor; LastSelectedNode = CollectionView.SelectedNode; CollectionView.SelectedNode.BackColor = Color.MediumSeaGreen; }
/// <summary> /// 还原BsonValue /// </summary> /// <returns></returns> public BsonValue GetBsonValue() { BsonValue Value = new BsonString(String.Empty); switch (mBsonType) { case "BsonString": Value = new BsonString(mBsonString); break; case "BsonInt32": Value = new BsonInt32(mBsonInt32); break; case "BsonDateTime": Value = new BsonDateTime(mBsonDateTime); break; case "BsonBoolean": if (mBsonBoolean) { Value = BsonBoolean.True; } else { Value = BsonBoolean.False; } break; default: break; } return(Value); }
public void TestBsonStringEquals() { var a = new BsonString("string 1"); var b = new BsonString("string 1"); var c = new BsonString("string 2"); var n = (BsonString)null; Assert.IsTrue(object.Equals(a, b)); Assert.IsFalse(object.Equals(a, c)); Assert.IsFalse(object.Equals(a, BsonNull.Value)); Assert.IsFalse(a.Equals(n)); Assert.IsFalse(a.Equals(null)); Assert.IsTrue(a == b); Assert.IsFalse(a == c); Assert.IsFalse(a == BsonNull.Value); Assert.IsFalse(a == null); Assert.IsFalse(null == a); Assert.IsTrue(n == null); Assert.IsTrue(null == n); Assert.IsFalse(a != b); Assert.IsTrue(a != c); Assert.IsTrue(a != BsonNull.Value); Assert.IsTrue(a != null); Assert.IsTrue(null != a); Assert.IsFalse(n != null); Assert.IsFalse(null != n); }
/// <summary> /// Gets a list of file attachment identifiers for an application. /// </summary> /// <param name="applicationId">The application id.</param> /// <param name="controlName">The name of the file upload control.</param> /// <returns>A list of file attachment identifiers for an application.</returns> protected override QueryResult<List<string>> DoGetAttachmentList(string applicationId, string controlName) { var attachmentCollection = this.database.GetCollection(iApplyDb.ApplicationAttachments._COLLECTION_NAME); List<string> returnDataList = new List<string>(); BsonValue bsonApplicationId = new BsonString(applicationId); BsonValue bsonControlName = new BsonString(controlName); var query = Query.And( Query.EQ(iApplyDb.ApplicationAttachments.APPLICATION_ID, bsonApplicationId), Query.EQ(iApplyDb.ApplicationAttachments.CONTROL_NAME, bsonControlName)); BsonDocument document = attachmentCollection.FindOne(query); if (document == null) { return new QueryResult<List<string>>(returnDataList); } BsonArray array = document.GetValue(iApplyDb.ApplicationAttachments.FILES).AsBsonArray; foreach (BsonDocument fileDocument in array) { string fileIdentifier = fileDocument.GetValue(iApplyDb.ApplicationAttachments.Files.FILE_IDENTIFIER).AsString; returnDataList.Add(fileIdentifier); } return new QueryResult<List<string>>(returnDataList); }
public void TestLocalizedRevision() { DbTest(database => { // Update object var cmsHandler = new cms_handler(database); var id = Mocks.BsonDocumentMock["_id"].AsObjectId; var cmsParameter = new cms_update_parameter { id = id, collection = "entities", field = "Biography", language = "DE", value = new BsonString("Eine neue Biography!") }; var cmsResponse = cmsHandler.revise(cmsParameter); // Check that the update was successful Assert.IsTrue(cmsResponse.success); // Check that reduced entity has the expected value var actual = cmsHandler.getCurrent("entities", id, "DE"); actual.OrderFields(); var expected = Mocks.BsonDocumentMock.DeepClone().AsBsonDocument; expected = expected.Current().AsBsonDocument; expected["Biography"] = new BsonString("Eine neue Biography!"); expected.OrderFields(); Assert.AreEqual(expected, actual); }); }
/// <summary> /// 还原BsonValue /// </summary> /// <returns></returns> public BsonValue GetBsonValue() { BsonValue value = new BsonString(string.Empty); switch (MBsonType) { case "BsonString": value = new BsonString(MBsonString); break; case "BsonInt32": value = new BsonInt32(MBsonInt32); break; case "BsonInt64": value = new BsonInt64(MBsonInt64); break; case "BsonDecimal128": value = new BsonDecimal128(MBSonDecimal128); break; case "BsonDateTime": value = new BsonDateTime(MBsonDateTime); break; case "BsonBoolean": value = MBsonBoolean ? BsonBoolean.True : BsonBoolean.False; break; } return(value); }
public JsonResult Save(SceneCategorySaveModel model) { if (string.IsNullOrEmpty(model.Name.Trim())) { return(Json(new { Code = 300, Msg = "场景类别名称不允许为空!" })); } var mongo = new MongoHelper(); if (string.IsNullOrEmpty(model.ID)) { var doc = new BsonDocument(); doc["Name"] = model.Name; mongo.InsertOne(Constant.SceneCategoryCollectionName, doc); } else { var filter = Builders <BsonDocument> .Filter.Eq("_id", ObjectId.Parse(model.ID)); var update = Builders <BsonDocument> .Update.Set("Name", BsonString.Create(model.Name)); mongo.UpdateOne(Constant.SceneCategoryCollectionName, filter, update); } return(Json(new { Code = 200, Msg = "保存成功!" })); }
/// <summary> /// 使用属性会发生一些MONO上的移植问题 /// </summary> /// <returns></returns> public BsonValue getValue() { BsonValue mValue = null; switch (cmbDataType.SelectedIndex) { case 0: mValue = new BsonString(txtBsonValue.Text); break; case 1: mValue = new BsonInt32(Convert.ToInt32(NumberPick.Value)); break; case 2: mValue = new BsonDateTime(dateTimePicker.Value); break; case 3: if (radTrue.Checked) { mValue = BsonBoolean.True; } else { mValue = BsonBoolean.False; } break; case 4: mValue = mBsonArray; break; case 5: mValue = mBsonDocument; break; } return mValue; }
/// <summary> /// The write workload writes a set of documents /// </summary> private static async Task ExecuteWriteWorkloadAsync(MongoClient mongoClient, Guid runGuid) { IMongoDatabase mongoDatabase = mongoClient.GetDatabase(ConfigurationManager.AppSettings["database"]); IMongoCollection <BsonDocument> mongoCollection = mongoDatabase.GetCollection <BsonDocument>(ConfigurationManager.AppSettings["collection"]); ServerDescription primaryServerDescription = mongoClient.Cluster.Description.Servers.First(x => x.Type == ServerType.ReplicaSetPrimary); string region = Helpers.TryGetRegionFromTags(primaryServerDescription.Tags) ?? string.Empty; BsonDocument template = new BsonDocument(new BsonElement("writtenFrom", new BsonString(region))); const int NumToWrite = 100; Console.WriteLine($"Writing {NumToWrite} documents to {region}..."); Stopwatch stopWatch = Stopwatch.StartNew(); for (int i = 0; i < NumToWrite; ++i) { BsonDocument toInsert = (BsonDocument)template.DeepClone(); toInsert["_id"] = new BsonString($"{runGuid}:{i}"); await mongoCollection.InsertOneAsync(toInsert); } Console.WriteLine($"Complete ({stopWatch.ElapsedMilliseconds} milliseconds)."); Console.WriteLine(); }
/// <summary> /// 使用属性会发生一些MONO上的移植问题 /// </summary> /// <returns></returns> public BsonValue GetValue() { BsonValue mValue = null; switch (cmbDataType.SelectedIndex) { case 0: mValue = new BsonString(txtBsonValue.Text); break; case 1: mValue = new BsonInt32(Convert.ToInt32(NumberPick.Value)); break; case 2: mValue = new BsonDateTime(dateTimePicker.Value); break; case 3: mValue = radTrue.Checked ? BsonBoolean.True : BsonBoolean.False; break; case 4: mValue = _mBsonArray; break; case 5: mValue = _mBsonDocument; break; } return(mValue); }
public SearchResults GetReverseIncludes(IList <IKey> keys, IList <string> revIncludes) { BsonValue[] internal_ids = keys.Select(k => BsonString.Create(String.Format("{0}/{1}", k.TypeName, k.ResourceId))).ToArray(); SearchResults results = new SearchResults(); if (keys != null && revIncludes != null) { var riQueries = new List <FilterDefinition <BsonDocument> >(); foreach (var revInclude in revIncludes) { var ri = SM.ReverseInclude.Parse(revInclude); if (!ri.SearchPath.Contains(".")) //for now, leave out support for chained revIncludes. There aren't that many anyway. { riQueries.Add( Builders <BsonDocument> .Filter.And( Builders <BsonDocument> .Filter.Eq(InternalField.RESOURCE, ri.ResourceType) , Builders <BsonDocument> .Filter.In(ri.SearchPath, internal_ids))); } } if (riQueries.Count > 0) { var revIncludeQuery = Builders <BsonDocument> .Filter.Or(riQueries); var resultKeys = CollectKeys(revIncludeQuery); results = KeysToSearchResults(resultKeys); } } return(results); }
public JsonResult Save(CategorySaveModel model) { if (string.IsNullOrEmpty(model.Name)) { return(Json(new { Code = 300, Msg = "Name is not allowed to be empty." })); } if (model.Type == null) { return(Json(new { Code = 300, Msg = "Type is not allowed to be empty!" })); } var mongo = new MongoHelper(); if (string.IsNullOrEmpty(model.ID)) { var doc = new BsonDocument(); doc["Name"] = model.Name; doc["Type"] = model.Type.Value.ToString(); if (ConfigHelper.EnableAuthority) { var user = UserHelper.GetCurrentUser(); if (user != null) { doc["UserID"] = user.ID; } } mongo.InsertOne(Constant.CategoryCollectionName, doc); } else { var filter = Builders <BsonDocument> .Filter.Eq("_id", ObjectId.Parse(model.ID)); var update1 = Builders <BsonDocument> .Update.Set("Name", BsonString.Create(model.Name)); var update2 = Builders <BsonDocument> .Update.Set("Type", BsonString.Create(model.Type.Value.ToString())); var update = Builders <BsonDocument> .Update.Combine(update1, update2); mongo.UpdateOne(Constant.CategoryCollectionName, filter, update); } return(Json(new { Code = 200, Msg = "Saved successfully!" })); }
public void ToDecimal128_should_return_expected_result(string stringValue) { var subject = new BsonString(stringValue); var result = subject.ToDecimal128(); result.Should().Be(Decimal128.Parse(stringValue)); }
/// <summary> /// Returns a basic string query with equal operators /// </summary> /// <param name="_name"></param> /// <param name="_value"></param> /// <returns></returns> public static IMongoQuery GetQuery(string _name, string _value) { BsonValue bsonValue = new BsonString(_value); IMongoQuery query = new QueryDocument(_name, bsonValue); return(query); }
public void TestIsDecimal128() { BsonValue v = new BsonDecimal128(1.0M); BsonValue s = new BsonString(""); Assert.True(v.IsDecimal128); Assert.False(s.IsDecimal128); }
public IMongoQuery QueryDuplicatedName(Identity?groupId, string topicName, Identity?excludeId = null) { var query = excludeId.HasValue ? Query.And(Query.EQ("Name", BsonString.Create(topicName)), Query.NE("_id", excludeId.Value.ToBson())) : Query.EQ("Name", BsonString.Create(topicName)); return(Query.And(query, Query.EQ("GroupId", groupId.ToBson()))); }
/// <summary> /// 使用属性会发生一些MONO上的移植问题 /// </summary> /// <returns></returns> public BsonValue GetValue(BsonValueEx.BasicType DataType) { BsonValue mValue = null; switch (DataType) { case BsonValueEx.BasicType.BsonString: mValue = new BsonString(txtBsonValue.Text); break; case BsonValueEx.BasicType.BsonInt32: mValue = new BsonInt32(Convert.ToInt32(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonInt64: mValue = new BsonInt64(Convert.ToInt64(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonDecimal128: mValue = new BsonDecimal128(Convert.ToDecimal(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonDouble: mValue = new BsonDouble(Convert.ToDouble(txtBsonValue.Text)); break; case BsonValueEx.BasicType.BsonDateTime: mValue = new BsonDateTime(dateTimePicker.Value); break; case BsonValueEx.BasicType.BsonBoolean: mValue = radTrue.Checked ? BsonBoolean.True : BsonBoolean.False; break; case BsonValueEx.BasicType.BsonArray: case BsonValueEx.BasicType.BsonLegacyPoint: mValue = _mBsonArray; break; case BsonValueEx.BasicType.BsonGeoJSON: case BsonValueEx.BasicType.BsonDocument: mValue = _mBsonDocument; break; case BsonValueEx.BasicType.BsonMaxKey: mValue = BsonMaxKey.Value; break; case BsonValueEx.BasicType.BsonMinKey: mValue = BsonMinKey.Value; break; case BsonValueEx.BasicType.BsonBinary: mValue = new BsonBinaryData(Encoding.Default.GetBytes(txtBsonValue.Text)); break; } return(mValue); }
private BsonValue RenderOutput() { return (_outputDatabase == null? BsonString.Create(_outputCollection) : new BsonDocument { { "db", _outputDatabase }, { "coll", _outputCollection } }); }
/// <summary> /// /// </summary> /// <param name="value"></param> /// <returns></returns> public static BsonValue String(object value) { string val = (string)value; if (value == null) { return(BsonNull.Value); } return(BsonString.Create(value)); }
public void Comment_get_and_set_should_work() { var subject = new EstimatedDocumentCountOperation(_collectionNamespace, _messageEncoderSettings); var value = new BsonString("comment"); subject.Comment = value; var result = subject.Comment; result.Should().Be(value); }
public void TestMapBsonString() { var value = new BsonString("hello"); var bsonValue = (BsonString)BsonTypeMapper.MapToBsonValue(value); Assert.AreSame(value, bsonValue); var bsonString = (BsonString)BsonTypeMapper.MapToBsonValue(value, BsonType.String); Assert.AreSame(value, bsonString); }
public void QueryValue_AccessingSimpleData(string input) { var stringValue = new BsonString("bar"); var doc = new BsonDocument(new Element("foo", stringValue)); var value = doc.QueryValue(input); Assert.Equal("bar", stringValue.Value); Assert.Same(stringValue, value); }
public bool TryMapToBsonValue(object value, out BsonValue bsonValue) { var uri = value as Uri; if (uri != null) { bsonValue = new BsonString(uri.AbsoluteUri); return true; } bsonValue = new BsonString(string.Empty); return false; }
public bool TryMapToBsonValue(object value, out BsonValue bsonValue) { if (value is EventStoreIdentity) { bsonValue = new BsonString((EventStoreIdentity)value); return(true); } bsonValue = null; return(false); }
public bool TryMapToBsonValue(object value, out BsonValue bsonValue) { if (value is StringValue) { bsonValue = new BsonString((StringValue)value); return(true); } bsonValue = null; return(false); }
public void TestDoesNotThrowStackOverflowExceptionWhenConvertingToBsonString() { BsonObjectId id1 = new BsonObjectId(ObjectId.GenerateNewId()); BsonString id2 = null; Assert.DoesNotThrow(() => { id2 = (BsonString)((IConvertible)id1).ToType(typeof(BsonString), null); }); Assert.AreEqual(id1.ToString(), id2.AsString); }
public bool TryMapToBsonValue(object value, out BsonValue bsonValue) { if (value != null) { bsonValue = new BsonString(value.ToString()); } else { bsonValue = new BsonString(string.Empty); } return true; }
private BsonValue ParseSymbol() { VerifyToken(":"); var nameToken = PopToken(); if (nameToken.Type != JsonTokenType.String) { var message = string.Format("JSON reader expected a string but found: '{0}'", nameToken.Lexeme); throw new FileFormatException(message); } VerifyToken("}"); return(BsonString.Create(nameToken.StringValue)); // will be converted to a BsonSymbol at a higher level }
public Recipe(string submittedBy, DateTime creationDate, string description, Array ingredients, TimeSpan cooktime, string[] instructions, BsonString backgroundTag, BsonArray tags, float rating) { this.submittedBy = submittedBy; this.creationDate = creationDate; this.description = description; this.ingredients = ingredients.ToBsonDocument(); this.cooktime = cooktime.Minutes; this.instructions = instructions.ToBsonDocument(); this.backgroundTag = backgroundTag; this.tags = tags; this.rating = rating; this.ofTheDay = 0; }
public String UpdateRow(String field, String data, String id) { BsonDocument updatedData = new BsonDocument(); try { id = id.Trim(); UpdateBuilder update = new UpdateBuilder(); try { updatedData = BsonDocument.Parse(data); update = Update.Set(field, updatedData); } catch (Exception e) { try { JArray jArray = JsonConvert.DeserializeObject <JArray>(data); var updatedArray = new BsonArray(); foreach (JObject jO in jArray) { updatedArray.Add(BsonDocument.Parse(jO.ToString())); } update = Update.Set(field, updatedArray); } catch (Exception ex) { var updated = new BsonString(data); update = Update.Set(field, updated); } } if (id != null && id != "") { var query = Query.EQ("_id", new ObjectId(id)); var lastMod = Update.Set( "LastmodDate", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") ); //Update data collection.Update(query, update); collection.Update(query, lastMod); } } catch (Exception e) { Error.Error.Log(e, "Updating data"); } return(""); }
private void AddProperties(BsonDocument document, LogEventInfo logEvent) { var propertiesDocument = new BsonDocument(); foreach (var field in Properties) { string key = field.Name; var value = GetValue(field, logEvent); if (value != null) { propertiesDocument[key] = value; } } var properties = logEvent.Properties ?? Enumerable.Empty <KeyValuePair <object, object> >(); foreach (var property in properties) { if (property.Key == null || property.Value == null) { continue; } string key = Convert.ToString(property.Key, CultureInfo.InvariantCulture); string value = Convert.ToString(property.Value, CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(value)) { var field = Fields.SingleOrDefault(e => e.Name.Equals(key, StringComparison.CurrentCultureIgnoreCase)); if (field != null) { var bsonValue = ConvertBsonValue(field, value); document.Add(key, new BsonString(key)); document[key] = bsonValue; } else { propertiesDocument[key] = new BsonString(value); } } } if (propertiesDocument.ElementCount > 0) { document.Add("Properties", propertiesDocument); } }
public void unesiVijest(Result newArticle) { var collection = _database.GetCollection <BsonDocument>("articles"); var id = (int)collection.Count(new BsonDocument()); var vijest = new BsonDocument { { "_id", BsonInt32.Create(id + 1) }, { "headline", BsonString.Create(newArticle.headline) }, { "text", BsonString.Create(newArticle.text) }, { "author", BsonString.Create(newArticle.author) }, { "comment", new BsonArray() }, { "picture", new BsonBinaryData(newArticle.picture) } }; collection.InsertOneAsync(vijest); }
public void TestIsNumeric() { BsonValue d128 = new BsonDecimal128(1.0M); BsonValue d = new BsonDouble(1.0); BsonValue i32 = new BsonInt32(1); BsonValue i64 = new BsonInt64(1L); BsonValue s = new BsonString(""); Assert.True(d128.IsNumeric); Assert.True(d.IsNumeric); Assert.True(i32.IsNumeric); Assert.True(i64.IsNumeric); Assert.False(s.IsDecimal128); }
public User CreateUser(int id = 1, int registartionId = 20, string name = "Ivan") { var currentTime = DateTime.Now; var currentTimeUtc = DateTime.UtcNow; var userBson = new BsonDocument() { { "_id", id }, { "RegistartionId", registartionId //BsonInt32.Create(registartionId) }, { "Name", BsonString.Create(name) }, { "Birthday", new DateTime(1990, 10, 22) }, //Driver will automatically convert your datetime to mongodb //format and store in as UTC date, and will convert back to your //local timezone back when you will read it //(actually you can change this behavior via driver settings). //So, take it in the mind that dates in mongodb always in UTC format. { "RegistrationLocal", currentTime }, { "RegistrationUtc", currentTimeUtc } }; _helper.WriteLine("Current time"); _helper.WriteLine(currentTime.ToString("O")); _helper.WriteLine("Current time ToJson"); _helper.WriteLine(currentTime.ToJson()); _helper.WriteLine("Current UtcTime"); _helper.WriteLine(currentTimeUtc.ToString("O")); _helper.WriteLine("Current UtcTime ToJson"); _helper.WriteLine(currentTimeUtc.ToJson()); _helper.WriteLine("User in bson"); _helper.WriteLine(userBson.ToJson()); _helper.WriteLine("User to poco"); var userPoco = BsonSerializer.Deserialize <User>(userBson); _helper.WriteLine(userPoco.ToJson()); userPoco.RegistrationLocal = currentTime; return(userPoco); }
public void TestConvertMultipleToObjectViaJson() { BsonDocument person1 = new BsonDocument(); BsonDocument person2 = new BsonDocument(); List<BsonDocument> people = new List<BsonDocument>(); const string id1 = "51ca5da43d1b18cc15000000"; const string name1 = "Luke Skywalker"; const string gender1 = "Male"; DateTime dateOfBirth1 = new DateTime(1977, 5, 25); person1["_id"] = new BsonObjectId(new ObjectId(id1)); person1["Name"] = new BsonString(name1); person1["Gender"] = new BsonString(gender1); person1["DateOfBirth"] = new BsonDateTime(dateOfBirth1); people.Add(person1); const string id2 = "52cb5da43d1f17cc15000000"; const string name2 = "Princess Leia"; const string gender2 = "Female"; DateTime dateOfBirth2 = new DateTime(1973, 5, 25); person2["_id"] = new BsonObjectId(new ObjectId(id2)); person2["Name"] = new BsonString(name2); person2["Gender"] = new BsonString(gender2); person2["DateOfBirth"] = new BsonDateTime(dateOfBirth2); people.Add(person2); List<Person> personList = BsonConverter.ConvertToObjectViaJson<List<Person>>(people); for (var i = 0; i < personList.Count; i++) { var person = personList[i]; var personToUse = i == 0 ? person1 : person2; Assert.AreEqual(person.Id, personToUse["_id"].ToString()); Assert.AreEqual(person.Name, personToUse["Name"]); Assert.AreEqual(person.Gender, personToUse["Gender"]); Assert.AreEqual(person.DateOfBirth.ToUniversalTime(), personToUse["DateOfBirth"].ToUniversalTime()); Assert.IsNull(person.DateOfDeath); } }
/// <summary> /// Gets an attachment with matching <paramref name="fileIdentifier"/>. /// </summary> /// <param name="applicationId">The application id.</param> /// <param name="controlName">The name of the attachment control.</param> /// <param name="fileIdentifier">The file identifier.</param> /// <returns>The attachment as a byte array.</returns> protected override QueryResult<byte[]> DoGetAttachment(string applicationId, string controlName, string fileIdentifier) { var attachmentCollection = this.database.GetCollection(iApplyDb.ApplicationAttachments._COLLECTION_NAME); BsonValue bsonApplicationId = new BsonString(applicationId); BsonValue bsonControlName = new BsonString(controlName); BsonValue bsonFileIdentifier = new BsonString(fileIdentifier); var query = Query.And( Query.EQ(iApplyDb.ApplicationAttachments.APPLICATION_ID, bsonApplicationId), Query.EQ(iApplyDb.ApplicationAttachments.CONTROL_NAME, bsonControlName), Query.EQ(iApplyDb.ApplicationAttachments.Files.FILE_IDENTIFIER_ABSOLUTE_PATH, bsonFileIdentifier)); MongoCursor<BsonDocument> documents = attachmentCollection.Find(query).SetFields(iApplyDb.ApplicationAttachments.FILES + ".$").SetLimit(1); if (!documents.Any()) { return new QueryResult<byte[]>(null); } byte[] bytes = documents.First()[iApplyDb.ApplicationAttachments.FILES].AsBsonArray.First().AsBsonDocument[iApplyDb.ApplicationAttachments.Files.FILE].AsByteArray; return new QueryResult<byte[]>(bytes); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { throw new ArgumentNullException("value"); } var bsonString = new BsonString(value.ToString()); bsonWriter.WriteString(bsonString.Value); }
/// <summary> /// Saves a file attachment for an application. /// </summary> /// <param name="applicationId">The application id.</param> /// <param name="controlName">The name of the file upload control.</param> /// <param name="fileIdentifier">The file identifier.</param> /// <param name="data">The file to save as a byte array.</param> /// <returns>A <see cref="DataAccessResult"/>.</returns> protected override DataAccessResult DoSaveAttachment(string applicationId, string controlName, string fileIdentifier, byte[] data) { var attachmentCollection = this.database.GetCollection(iApplyDb.ApplicationAttachments._COLLECTION_NAME); BsonValue bsonApplicationId = new BsonString(applicationId); BsonValue bsonControlName = new BsonString(controlName); BsonValue bsonFileIdentifier = new BsonString(fileIdentifier); var query = Query.And( Query.EQ(iApplyDb.ApplicationAttachments.APPLICATION_ID, bsonApplicationId), Query.EQ(iApplyDb.ApplicationAttachments.CONTROL_NAME, bsonControlName)); BsonDocument document = attachmentCollection.FindOne(query) ?? new BsonDocument { { iApplyDb.ApplicationAttachments.APPLICATION_ID, bsonApplicationId }, { iApplyDb.ApplicationAttachments.CONTROL_NAME, bsonControlName }, { iApplyDb.ApplicationAttachments.FILES, new BsonArray() } }; BsonArray array = document.GetValue(iApplyDb.ApplicationAttachments.FILES).AsBsonArray; BsonValue fileDocument = array.FirstOrDefault(d => ((BsonDocument)d).GetValue(iApplyDb.ApplicationAttachments.Files.FILE_IDENTIFIER).AsString == fileIdentifier); if (fileDocument == null) { fileDocument = new BsonDocument(); fileDocument.AsBsonDocument.Add(iApplyDb.ApplicationAttachments.Files.FILE_IDENTIFIER, bsonFileIdentifier); array.Add(fileDocument); } fileDocument.AsBsonDocument[iApplyDb.ApplicationAttachments.Files.FILE] = new BsonBinaryData(data); attachmentCollection.Save(document); DataAccessResult result = new DataAccessResult { ApplicationId = applicationId, Id = document[iApplyDb.ApplicationAttachments._ID].AsObjectId.ToString() }; return result; }
private void AddProperties(BsonDocument document, LogEventInfo logEvent) { var propertiesDocument = new BsonDocument(); foreach (var field in Properties) { string key = field.Name; var value = GetValue(field, logEvent); if (value != null) propertiesDocument[key] = value; } var properties = logEvent.Properties ?? Enumerable.Empty<KeyValuePair<object, object>>(); foreach (var property in properties) { if (property.Key == null || property.Value == null) continue; string key = Convert.ToString(property.Key, CultureInfo.InvariantCulture); string value = Convert.ToString(property.Value, CultureInfo.InvariantCulture); if (!string.IsNullOrEmpty(value)) propertiesDocument[key] = new BsonString(value); } if (propertiesDocument.ElementCount > 0) document.Add("Properties", propertiesDocument); }
public TestClass( BsonString value ) { this.B = value; this.V = value; }
/// <summary> /// Removes an attachment with matching <paramref name="fileIdentifier"/>. /// </summary> /// <param name="applicationId">The application id.</param> /// <param name="controlName">The name of the attachment control.</param> /// <param name="fileIdentifier">The file identifier.</param> protected override void DoRemoveAttachment(string applicationId, string controlName, string fileIdentifier) { MongoCollection attachmentCollection = this.database.GetCollection(iApplyDb.ApplicationAttachments._COLLECTION_NAME); BsonValue bsonApplicationId = new BsonString(applicationId); BsonValue bsonControlName = new BsonString(controlName); BsonValue bsonFileIdentifier = new BsonString(fileIdentifier); IMongoQuery query = Query.And( Query.EQ(iApplyDb.ApplicationAttachments.APPLICATION_ID, bsonApplicationId), Query.EQ(iApplyDb.ApplicationAttachments.CONTROL_NAME, bsonControlName)); IMongoUpdate update = Update.Pull(iApplyDb.ApplicationAttachments.FILES, Query.EQ(iApplyDb.ApplicationAttachments.Files.FILE_IDENTIFIER, bsonFileIdentifier)); attachmentCollection.Update(query, update); }
/// <summary> /// 还原BsonValue /// </summary> /// <returns></returns> public BsonValue GetBsonValue() { BsonValue Value = new BsonString(""); switch (mBsonType) { case "BsonString": Value = new BsonString(mBsonString); break; case "BsonInt32": Value = new BsonInt32(mBsonInt32); break; case "BsonDateTime": Value = new BsonDateTime(mBsonDateTime); break; case "BsonBoolean": if (mBsonBoolean) { Value = BsonBoolean.True; } else { Value = BsonBoolean.False; } break; default: break; } return Value; }
private MongoCursor<BsonDocument> LoadData() { try { var db = MongoUtilities.Create(_cnn).GetDatabase(_databaseName); var col = db.GetCollection(_collectionName); _pager.TotalItems = (int)col.Count(); if (_pager.TotalItems == 0) { return null; } var queries = new List<IMongoQuery>(); _filterOn.ToList().ForEach(property => { IMongoQuery subQuery; BsonValue value; if (!MongoUtilities.TryConvertStringToBsonType( _sortFieldsInfo[property.Name], property.Value, out value)) { value = new BsonString(property.Value); } switch (property.Operator) { case "!=": subQuery = Query.NE(property.Name, value); break; case ">=": subQuery = Query.GTE(property.Name, value); break; case "<=": subQuery = Query.LTE(property.Name, value); break; case ">": subQuery = Query.GT(property.Name, value); break; case "<": subQuery = Query.LT(property.Name, value); break; case "like": subQuery = Query.Matches(property.Name, new BsonRegularExpression("(?i)" + property.Value)); break; case "in": case "!in": var values = new List<BsonValue>(); property.Value.Split(',').ToList().ForEach(item => { BsonValue val = null; if (!MongoUtilities.TryConvertStringToBsonType(_sortFieldsInfo[property.Name], item.Trim(), out val)) { val = new BsonString(item.Trim()); } values.Add(val); }); if (property.Operator == "in") { subQuery = Query.In(property.Name, values); } else { subQuery = Query.NotIn(property.Name, values); } break; default: subQuery = Query.EQ(property.Name, value); break; } queries.Add(subQuery); }); IMongoQuery query; if (queries.Count > 0) { query = Query.And(queries); } else { query = null; } var cur = col.Find(query).SetSkip(_pager.FirstItemIndex).SetLimit(_pager.PageSize); SortByBuilder sort = new SortByBuilder(); _sortOn.ToList().ForEach(property => { if (property.Ascending) sort = sort.Ascending(property.Name); else sort = sort.Descending(property.Name); }); cur.SetSortOrder(sort); return cur; } catch (Exception ex) { Utilities.LogException(ex); } return null; }
public void TestUpdate() { DbTest(database => { // Update object var cmsHandler = new cms_handler(database); var id = Mocks.BsonDocumentMock["_id"].AsObjectId; var cmsParameter = new cms_update_parameter { id = id, collection = "entities", field = "Simple", value = new BsonString("New value.") }; var cmsResponse = cmsHandler.update(cmsParameter); // Check that the update was successful Assert.IsTrue(cmsResponse.success); // Check that reduced entity has the expected value var actual = cmsHandler.getCurrent("entities", id); actual.OrderFields(); var expected = Mocks.BsonDocumentMock.DeepClone().AsBsonDocument; expected = expected.Current().AsBsonDocument; expected["Simple"] = new BsonString("New value."); expected.OrderFields(); Assert.AreEqual(expected, actual); }); }
public void TestMapBsonString() { var value = new BsonString("hello"); var bsonValue = (BsonString) BsonTypeMapper.MapToBsonValue(value); Assert.AreSame(value, bsonValue); var bsonString = (BsonString) BsonTypeMapper.MapToBsonValue(value, BsonType.String); Assert.AreSame(value, bsonString); }
public void TestBsonString() { var booleanString = new BsonString("true"); var dateTimeString = new BsonString("2011-01-20"); var doubleString = new BsonString("1.5"); var intString = new BsonString("1"); Assert.AreSame(booleanString, ((IConvertible)booleanString).ToType(typeof(object), null)); Assert.AreEqual(true, Convert.ToBoolean(booleanString)); Assert.AreEqual(1, Convert.ToByte(intString)); Assert.AreEqual('1', Convert.ToChar(intString)); Assert.AreEqual(new DateTime(2011, 1, 20), Convert.ToDateTime(dateTimeString)); Assert.AreEqual(1.5m, Convert.ToDecimal(doubleString, CultureInfo.InvariantCulture)); Assert.AreEqual(1.5, Convert.ToDouble(doubleString, CultureInfo.InvariantCulture)); Assert.AreEqual(1, Convert.ToInt16(intString)); Assert.AreEqual(1, Convert.ToInt32(intString)); Assert.AreEqual(1, Convert.ToInt64(intString)); Assert.AreEqual(1, Convert.ToSByte(intString)); Assert.AreEqual(1.5F, Convert.ToSingle(doubleString, CultureInfo.InvariantCulture)); Assert.AreEqual("1.5", Convert.ToString(doubleString, CultureInfo.InvariantCulture)); Assert.AreEqual(1, Convert.ToUInt16(intString)); Assert.AreEqual(1, Convert.ToUInt32(intString)); Assert.AreEqual(1, Convert.ToUInt64(intString)); }
/// <summary> /// 使用属性会发生一些MONO上的移植问题 /// </summary> /// <returns></returns> public BsonValue GetValue(BsonValueEx.BasicType DataType) { BsonValue mValue = null; switch (DataType) { case BsonValueEx.BasicType.BsonString: mValue = new BsonString(txtBsonValue.Text); break; case BsonValueEx.BasicType.BsonInt32: mValue = new BsonInt32(Convert.ToInt32(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonInt64: mValue = new BsonInt64(Convert.ToInt64(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonDecimal128: mValue = new BsonDecimal128(Convert.ToDecimal(NumberPick.Value)); break; case BsonValueEx.BasicType.BsonDouble: mValue = new BsonDouble(Convert.ToDouble(txtBsonValue.Text)); break; case BsonValueEx.BasicType.BsonDateTime: mValue = new BsonDateTime(dateTimePicker.Value); break; case BsonValueEx.BasicType.BsonBoolean: mValue = radTrue.Checked ? BsonBoolean.True : BsonBoolean.False; break; case BsonValueEx.BasicType.BsonArray: case BsonValueEx.BasicType.BsonLegacyPoint: mValue = _mBsonArray; break; case BsonValueEx.BasicType.BsonGeoJSON: case BsonValueEx.BasicType.BsonDocument: mValue = _mBsonDocument; break; case BsonValueEx.BasicType.BsonMaxKey: mValue = BsonMaxKey.Value; break; case BsonValueEx.BasicType.BsonMinKey: mValue = BsonMinKey.Value; break; case BsonValueEx.BasicType.BsonBinary: mValue = new BsonBinaryData(Encoding.Default.GetBytes(txtBsonValue.Text)); break; } return mValue; }
/// <summary> /// Gets the attachments. /// </summary> /// <param name="applicationId">The application identifier.</param> /// <param name="controlName">Name of the control.</param> /// <returns>A map of filename and file data for the control.</returns> protected override Dictionary<string, byte[]> DoGetAttachments(string applicationId, string controlName) { Dictionary<string, byte[]> files = new Dictionary<string, byte[]>(); var attachmentCollection = this.Database.GetCollection(iApplyDb.ApplicationAttachments._COLLECTION_NAME); BsonValue bsonApplicationId = new BsonString(applicationId); BsonValue bsonControlName = new BsonString(controlName); var query = Query.And( Query.EQ(iApplyDb.ApplicationAttachments.APPLICATION_ID, bsonApplicationId), Query.EQ(iApplyDb.ApplicationAttachments.CONTROL_NAME, bsonControlName)); MongoCursor<BsonDocument> documents = attachmentCollection.Find(query).SetFields(iApplyDb.ApplicationAttachments.FILES); if (!documents.Any()) { return files; } foreach (BsonDocument file in documents.First()[iApplyDb.ApplicationAttachments.FILES].AsBsonArray) { files.Add(file[iApplyDb.ApplicationAttachments.Files.FILE_IDENTIFIER].AsString, file[iApplyDb.ApplicationAttachments.Files.FILE].AsByteArray); } return files; }
private bool TryTranslateStringMethodCall(MethodCallExpression node, out BsonValue result) { result = null; var field = TranslateValue(node.Object); switch (node.Method.Name) { case "Equals": if (node.Arguments.Count == 2 && node.Arguments[1].NodeType == ExpressionType.Constant) { var comparisonType = (StringComparison)((ConstantExpression)node.Arguments[1]).Value; switch (comparisonType) { case StringComparison.OrdinalIgnoreCase: result = new BsonDocument("$eq", new BsonArray(new BsonValue[] { new BsonDocument("$strcasecmp", new BsonArray(new[] { field, TranslateValue(node.Arguments[0]) })), 0 })); return true; case StringComparison.Ordinal: result = new BsonDocument("$eq", new BsonArray(new[] { field, TranslateValue(node.Arguments[0]) })); return true; default: throw new NotSupportedException("Only Ordinal and OrdinalIgnoreCase are supported for string comparisons."); } } break; case "IndexOf": var indexOfArgs = new BsonArray { field }; if (node.Arguments.Count < 1 || node.Arguments.Count > 3) { return false; } if (node.Arguments[0].Type != typeof(char) && node.Arguments[0].Type != typeof(string)) { return false; } var value = TranslateValue(node.Arguments[0]); if (value.BsonType == BsonType.Int32) { value = new BsonString(new string((char)value.AsInt32, 1)); } indexOfArgs.Add(value); if (node.Arguments.Count > 1) { if (node.Arguments[1].Type != typeof(int)) { return false; } var startIndex = TranslateValue(node.Arguments[1]); indexOfArgs.Add(startIndex); } if (node.Arguments.Count > 2) { if (node.Arguments[2].Type != typeof(int)) { return false; } var count = TranslateValue(node.Arguments[2]); var endIndex = new BsonDocument("$add", new BsonArray { indexOfArgs[2], count }); indexOfArgs.Add(endIndex); } var indexOpName = _stringTranslationMode == AggregateStringTranslationMode.CodePoints ? "$indexOfCP" : "$indexOfBytes"; result = new BsonDocument(indexOpName, indexOfArgs); return true; case "Split": if (node.Arguments.Count < 1 || node.Arguments.Count > 2) { return false; } if (node.Arguments[0].Type != typeof(char[]) && node.Arguments[0].Type != typeof(string[])) { return false; } var separatorArray = TranslateValue(node.Arguments[0]) as BsonArray; if (separatorArray == null || separatorArray.Count != 1) { return false; } var separator = separatorArray[0]; if (separator.BsonType == BsonType.Int32) { separator = new BsonString(new string((char)separator.AsInt32, 1)); } if (node.Arguments.Count == 2) { var constantExpression = node.Arguments[1] as ConstantExpression; if (constantExpression == null || constantExpression.Type != typeof(StringSplitOptions)) { return false; } var options = (StringSplitOptions)constantExpression.Value; if (options != StringSplitOptions.None) { return false; } } result = new BsonDocument("$split", new BsonArray { field, separator }); return true; case "Substring": if (node.Arguments.Count == 2) { var substrOpName = _stringTranslationMode == AggregateStringTranslationMode.CodePoints ? "$substrCP" : "$substr"; result = new BsonDocument(substrOpName, new BsonArray(new[] { field, TranslateValue(node.Arguments[0]), TranslateValue(node.Arguments[1]) })); return true; } break; case "ToLower": case "ToLowerInvariant": if (node.Arguments.Count == 0) { result = new BsonDocument("$toLower", field); return true; } break; case "ToUpper": case "ToUpperInvariant": if (node.Arguments.Count == 0) { result = new BsonDocument("$toUpper", field); return true; } break; } return false; }
/// <summary> /// Finds the workflow configurations that match the criteria. /// </summary> /// <param name="workflowType">The type of workflows to find.</param> /// <param name="externalCriteria">Filter the list to those with a matching external id.</param> /// <returns>The workflow configurations that match the criteria.</returns> protected override WorkflowConfigurationContainerList DoFindWorkflowConfigurations(WorkflowTargetType workflowType, Dictionary<string, int> externalCriteria) { BsonString bsonWorkflowType = new BsonString(workflowType.ToString()); IEnumerable<IMongoQuery> formCriteria = externalCriteria.Select(kvp => Query.And( Query.EQ(iApplyDb.WorkflowConfiguration.EXTERNAL_ID, new BsonString(kvp.Key)), Query.EQ(iApplyDb.WorkflowConfiguration.EXTERNAL_VERSION, new BsonInt32(kvp.Value)))); var eqQuery = Query.EQ(iApplyDb.WorkflowConfiguration.TYPE, bsonWorkflowType); IMongoQuery query = formCriteria.Any() ? Query.And(Query.Or(formCriteria), eqQuery) : eqQuery; MongoCollection<BsonDocument> collection = this.Database.GetCollection(iApplyDb.WorkflowConfiguration._COLLECTION_NAME); MongoCursor<BsonDocument> documents = collection.Find(query); WorkflowConfigurationContainerList list = BsonConverter.ConvertToObjectViaJson<WorkflowConfigurationContainerList>(documents); return list; }
/// <summary> /// Gets the <see cref="WorkflowConfiguration"/> matching the /// <paramref name="workflowType"/> and <paramref name="externalId"/>. /// </summary> /// <param name="workflowType">The workflow type to retrieve.</param> /// <param name="externalId">The workflow type reference id of the workflow to retrieve.</param> /// <param name="externalVersion">The version number of the workflow configuration to retrieve.</param> /// <returns>The <see cref="WorkflowConfiguration"/> matching the /// <paramref name="workflowType"/> and <paramref name="externalId"/>.</returns> protected override WorkflowConfigurationContainer DoGetWorkflowConfiguration(WorkflowTargetType workflowType, string externalId, int externalVersion) { BsonString bsonWorkflowType = new BsonString(workflowType.ToString()); BsonString bsonExternalId = new BsonString(externalId); BsonInt32 bsonExternalVersion = new BsonInt32(externalVersion); MongoCollection<BsonDocument> collection = this.Database.GetCollection(iApplyDb.WorkflowConfiguration._COLLECTION_NAME); IMongoQuery query = Query.And( Query.EQ(iApplyDb.WorkflowConfiguration.TYPE, bsonWorkflowType), Query.EQ(iApplyDb.WorkflowConfiguration.EXTERNAL_ID, bsonExternalId), Query.EQ(iApplyDb.WorkflowConfiguration.EXTERNAL_VERSION, bsonExternalVersion)); BsonDocument document = collection.FindOne(query); if (document == null) { return null; } return BsonConverter.ConvertToObjectViaJson<WorkflowConfigurationContainer>(document); }
/// <summary> /// 还原BsonValue /// </summary> /// <returns></returns> public BsonValue GetBsonValue() { BsonValue value = new BsonString(string.Empty); switch (MBsonType) { case "BsonString": value = new BsonString(MBsonString); break; case "BsonInt32": value = new BsonInt32(MBsonInt32); break; case "BsonDateTime": value = new BsonDateTime(MBsonDateTime); break; case "BsonBoolean": value = MBsonBoolean ? BsonBoolean.True : BsonBoolean.False; break; case "BsonDouble": value = new BsonDouble(MBsonDouble); break; } return value; }
/// <summary> /// Gets the data for one custom field, and any relevant GUIDs. /// </summary> /// <param name="hvo">Hvo of object we're getting the field for.</param> /// <param name="flid">Flid for this field.</param> /// <param name="fieldSourceType">Either "entry", "senses" or "examples". Could also be "allomorphs", eventually.</param> /// <param name="bsonForThisField">Output of a BsonDocument with the following structure: <br /> /// { fieldName: { "value": BsonValue, "guid": "some-guid-as-a-string" } } <br /> /// -OR- <br /> /// { fieldName: { "value": BsonValue, "guid": ["guid1", "guid2", "guid3"] } } <br /> /// The format of the fieldName key will be "customField_FOO_field_name_with_underscores", /// where FOO is one of "entry", "senses", or "examples". <br /> /// The type of the "guid" value (array or string) will determine whether there is a single GUID, /// or a list of GUIDs that happens to contain only one entry. /// If there is no "guid" key, that field has no need for a GUID. (E.g., a number). /// </param> /// <param name="listConverters">Dictionary of ConvertFdoToMongoOptionList instances, keyed by list code</param> /// <param name="customFieldType">output string of LF custom field type</param> private void GetCustomFieldData(int hvo, int flid, string fieldSourceType, IDictionary<string, ConvertFdoToMongoOptionList> listConverters, out BsonDocument bsonForThisField, out string customFieldType) { bsonForThisField = null; customFieldType = string.Empty; BsonValue fieldValue = null; BsonValue fieldGuid = null; // Might be a single value, might be a list (as a BsonArray) ISilDataAccessManaged data = (ISilDataAccessManaged)cache.DomainDataByFlid; CellarPropertyType fdoFieldType = (CellarPropertyType)fdoMetaData.GetFieldType(flid); var dataGuids = new List<Guid>(); // Valid field types in FDO are GenDate, Integer, String, OwningAtomic, ReferenceAtomic, and ReferenceCollection, so that's all we implement. switch (fdoFieldType) { case CellarPropertyType.GenDate: GenDate genDate = data.get_GenDateProp(hvo, flid); string genDateStr = genDate.ToLongString(); // LF wants single-string fields in the format { "ws": { "value": "contents" } } fieldValue = String.IsNullOrEmpty(genDateStr) ? null : LfMultiText.FromSingleStringMapping( MagicStrings.LanguageCodeForGenDateFields, genDateStr).AsBsonDocument(); break; // When parsing, will use GenDate.TryParse(str, out genDate) case CellarPropertyType.Integer: fieldValue = new BsonInt32(data.get_IntProp(hvo, flid)); if (fieldValue.AsInt32 == default(Int32)) fieldValue = null; // Suppress int fields with 0 in them, to save Mongo DB space else // LF wants single-string fields in the format { "ws": { "value": "contents" } } fieldValue = LfMultiText.FromSingleStringMapping( MagicStrings.LanguageCodeForIntFields, fieldValue.AsInt32.ToString()).AsBsonDocument(); break; case CellarPropertyType.OwningAtomic: case CellarPropertyType.ReferenceAtomic: int ownedHvo = data.get_ObjectProp(hvo, flid); fieldValue = GetCustomReferencedObject(ownedHvo, flid, listConverters, ref dataGuids); if (fieldValue != null && fdoFieldType == CellarPropertyType.ReferenceAtomic) { // Single CmPossiblity reference - LF expects format like { "value": "key of possibility" } fieldValue = new BsonDocument("value", fieldValue); } fieldGuid = new BsonString(dataGuids.FirstOrDefault().ToString()); break; case CellarPropertyType.MultiUnicode: ITsMultiString tss = data.get_MultiStringProp(hvo, flid); if (tss != null && tss.StringCount > 0) fieldValue = LfMultiText.FromMultiITsString(tss, cache.ServiceLocator.WritingSystemManager).AsBsonDocument(); break; case CellarPropertyType.OwningCollection: case CellarPropertyType.OwningSequence: case CellarPropertyType.ReferenceCollection: case CellarPropertyType.ReferenceSequence: int[] listHvos = data.VecProp(hvo, flid); var innerValues = new BsonArray(listHvos.Select(listHvo => GetCustomReferencedObject(listHvo, flid, listConverters, ref dataGuids)).Where(x => x != null)); if (innerValues.Count == 0) fieldValue = null; else { fieldValue = new BsonDocument("values", innerValues); fieldGuid = new BsonArray(dataGuids.Select(guid => guid.ToString())); } break; case CellarPropertyType.String: ITsString iTsValue = data.get_StringProp(hvo, flid); if (iTsValue == null || String.IsNullOrEmpty(iTsValue.Text)) fieldValue = null; else fieldValue = LfMultiText.FromSingleITsString(iTsValue, cache.ServiceLocator.WritingSystemManager).AsBsonDocument(); break; default: fieldValue = null; if (logger != null) logger.Warning("FDO CellarPropertyType.{0} not recognized for LF custom field", fdoFieldType.ToString()); break; } CellarPropertyTypeToLfCustomFieldType.TryGetValue(fdoFieldType, out customFieldType); if (fieldValue == null) return; else { var result = new BsonDocument(); result.Add("value", fieldValue ?? BsonNull.Value); // BsonValues aren't allowed to have C# nulls; they have their own null representation if (fieldGuid is BsonArray) result.Add("guid", fieldGuid, ((BsonArray)fieldGuid).Count > 0); else result.Add("guid", fieldGuid, fieldGuid != null); bsonForThisField = result; } }
public void TestConvertToObjectViaJson() { const string id = "51ca5da43d1b18cc15000000"; const string name = "Luke Skywalker"; const string gender = "Male"; DateTime dateOfBirth = new DateTime(1977, 5, 25); BsonDocument document = new BsonDocument(); document["_id"] = new BsonObjectId(new ObjectId(id)); document["Name"] = new BsonString(name); document["Gender"] = new BsonString(gender); document["DateOfBirth"] = new BsonDateTime(dateOfBirth); ////document["DateOfDeath"] = Deliberately excluded Person person = BsonConverter.ConvertToObjectViaJson<Person>(document); Assert.AreEqual(person.Id, id); Assert.AreEqual(person.Name, name); Assert.AreEqual(person.Gender, gender); Assert.AreEqual(person.DateOfBirth.ToUniversalTime(), dateOfBirth.ToUniversalTime()); Assert.IsNull(person.DateOfDeath); }