public void MapInterfaces_Test() { var mapper = new BsonMapper(); var c1 = new MyClassWithInterface { Id = 1, Impl = new MyClassImpl { Name = "John Doe" } }; var c2 = new MyClassWithObject { Id = 1, Impl = new MyClassImpl { Name = "John Doe" } }; var c3 = new MyClassWithClassName { Id = 1, Impl = new MyClassImpl { Name = "John Doe" } }; var bson1 = mapper.ToDocument(c1); // add _type in Impl property var bson2 = mapper.ToDocument(c2); // add _type in Impl property var bson3 = mapper.ToDocument(c3); // do not add _type in Impl property //string dllName = this.GetType().Assembly.GetName().Name; // //Assert.AreEqual("LiteDB.Tests.MapperInterfaceTest+MyClassImpl, " + dllName, bson1["Impl"].AsDocument["_type"].AsString); //Assert.AreEqual("LiteDB.Tests.MapperInterfaceTest+MyClassImpl, " + dllName, bson2["Impl"].AsDocument["_type"].AsString); //Assert.AreEqual(false, bson3["Impl"].AsDocument.ContainsKey("_type")); var k1 = mapper.ToObject<MyClassWithInterface>(bson1); var k2 = mapper.ToObject<MyClassWithObject>(bson2); var k3 = mapper.ToObject<MyClassWithClassName>(bson3); Assert.AreEqual(c1.Impl.Name, k1.Impl.Name); Assert.AreEqual((c2.Impl as MyClassImpl).Name, (k2.Impl as MyClassImpl).Name); Assert.AreEqual(c3.Impl.Name, k3.Impl.Name); }
private object InternalSet(string key, object value) { var objType = value.GetType(); if (objType.IsPrimitiveOrSimple()) { value = new PrimitiveWrapper() { val = value }; } var oldBson = GetBson(key); var newVal = bsonMapper.ToDocument(value); if (oldBson == null) { lock (threadLock) { collection.Insert(key, newVal); } return(null); } else { var oldVal = InternalGet(oldBson, objType); lock (threadLock) { collection.Update(key, newVal); } return(oldVal); } }
public void Mapper_Test() { var mapper = new BsonMapper(); mapper.UseLowerCaseDelimiter('_'); var obj = CreateModel(); var doc = mapper.ToDocument(obj); var json = JsonSerializer.Serialize(doc, true); var nobj = mapper.ToObject <MyClass>(doc); // compare object to document Assert.AreEqual(doc["_id"].AsInt32, obj.MyId); Assert.AreEqual(doc["MY-STRING"].AsString, obj.MyString); Assert.AreEqual(doc["my_guid"].AsGuid, obj.MyGuid); // compare 2 objects Assert.AreEqual(obj.MyId, nobj.MyId); Assert.AreEqual(obj.MyString, nobj.MyString); Assert.AreEqual(obj.MyProperty, nobj.MyProperty); Assert.AreEqual(obj.MyGuid, nobj.MyGuid); Assert.AreEqual(obj.MyDateTime, nobj.MyDateTime); Assert.AreEqual(obj.MyDateTimeNullable, nobj.MyDateTimeNullable); Assert.AreEqual(obj.MyIntNullable, nobj.MyIntNullable); Assert.AreEqual(obj.MyEnumProp, nobj.MyEnumProp); Assert.AreEqual(obj.MyChar, nobj.MyChar); Assert.AreEqual(obj.MyByte, nobj.MyByte); Assert.AreEqual(obj.MyDecimal, nobj.MyDecimal); Assert.AreEqual(obj.MyUri, nobj.MyUri); #if !PORTABLE Assert.AreEqual(obj.MyNameValueCollection["key-1"], nobj.MyNameValueCollection["key-1"]); Assert.AreEqual(obj.MyNameValueCollection["KeyNumber2"], nobj.MyNameValueCollection["KeyNumber2"]); #endif // list Assert.AreEqual(obj.MyStringArray[0], nobj.MyStringArray[0]); Assert.AreEqual(obj.MyStringArray[1], nobj.MyStringArray[1]); Assert.AreEqual(obj.MyStringEnumerable.First(), nobj.MyStringEnumerable.First()); Assert.AreEqual(obj.MyStringEnumerable.Take(1).First(), nobj.MyStringEnumerable.Take(1).First()); Assert.AreEqual(true, obj.CustomStringEnumerable.SequenceEqual(nobj.CustomStringEnumerable)); Assert.AreEqual(obj.MyDict[2], nobj.MyDict[2]); // interfaces Assert.AreEqual(obj.MyInterface.Name, nobj.MyInterface.Name); Assert.AreEqual(obj.MyListInterface[0].Name, nobj.MyListInterface[0].Name); Assert.AreEqual(obj.MyIListInterface[0].Name, nobj.MyIListInterface[0].Name); // objects Assert.AreEqual(obj.MyObjectString, nobj.MyObjectString); Assert.AreEqual(obj.MyObjectInt, nobj.MyObjectInt); Assert.AreEqual((obj.MyObjectImpl as MyImpl).Name, (nobj.MyObjectImpl as MyImpl).Name); Assert.AreEqual(obj.MyObjectList[0], obj.MyObjectList[0]); Assert.AreEqual(obj.MyObjectList[1], obj.MyObjectList[1]); Assert.AreEqual(obj.MyObjectList[3], obj.MyObjectList[3]); #if !PCL Assert.AreEqual(nobj.MyInternalProperty, null); #endif }
public void Dictionary_Of_List_T() { var source = new DictListData { Id = 1, MyDict = new Dictionary <string, List <int?> >() { { "one", new List <int?> { 1, null, 3, null, 5 } } } }; var mapper = new BsonMapper(); var doc = mapper.ToDocument(source); var json = doc.ToString(); var dest = mapper.ToObject <DictListData>(doc); Assert.AreEqual(source.MyDict["one"][0], dest.MyDict["one"][0]); Assert.AreEqual(source.MyDict["one"][1], dest.MyDict["one"][1]); Assert.AreEqual(source.MyDict["one"][2], dest.MyDict["one"][2]); Assert.AreEqual(source.MyDict["one"][3], dest.MyDict["one"][3]); Assert.AreEqual(source.MyDict["one"][4], dest.MyDict["one"][4]); }
public void Getter_Setter_Structs() { var o = new GetterSetterStruct { PublicProperty = "PublicProperty", InternalProperty = "InternalProperty", PublicField = "PublicField", InternalField = "InternalField" }; o.SetPrivateProperty("PrivateProperty"); o.SetPrivateField("PrivateField"); var m = new BsonMapper { IncludeFields = true }; m.IncludeNonPublic = true; var clone = m.ToObject <GetterSetterStruct>(m.ToDocument <GetterSetterStruct>(o)); Assert.AreEqual(o.PublicProperty, clone.PublicProperty); Assert.AreEqual(o.InternalProperty, clone.InternalProperty); Assert.AreEqual(o.PublicField, clone.PublicField); Assert.AreEqual(o.InternalField, clone.InternalField); Assert.AreEqual(o.GetPrivateProperty(), clone.GetPrivateProperty()); Assert.AreEqual(o.GetPrivateField(), clone.GetPrivateField()); }
public BsonDocument ShouldSerializeCollectionClass() { var items = CreateCollection(); var document = _mapper.ToDocument(items); Assert.AreEqual("MyCollection", (string)document["MyItemCollectionName"]); var array = (BsonArray)document["_items"]; Assert.IsNotNull(array); var recoveritem = (BsonDocument)array[0]; Assert.AreEqual("MyItem", (string)recoveritem["MyItemName"]); return(document); }
public void MapperNonPublic_Test() { var mapper = new BsonMapper(); mapper.UseLowerCaseDelimiter('_'); mapper.IncludeNonPublic = true; var obj = CreateModel(); var doc = mapper.ToDocument(obj); var json = JsonSerializer.Serialize(doc, true); var nobj = mapper.ToObject<MyBsonFieldTestClass>(doc); Assert.AreEqual(doc["MY-STRING"].AsString, obj.MyString); Assert.AreEqual(doc["INTERNAL-PROPERTY"].AsString, obj.MyInternalPropertyNamed); Assert.AreEqual(doc["PRIVATE-PROPERTY"].AsString, obj.GetMyPrivatePropertyNamed()); Assert.AreEqual(doc["PROTECTED-PROPERTY"].AsString, obj.GetMyProtectedPropertyNamed()); Assert.AreEqual(obj.MyString, nobj.MyString); //Internal Assert.AreEqual(obj.MyInternalPropertyNamed, nobj.MyInternalPropertyNamed); Assert.AreEqual(obj.MyInternalPropertySerializable, nobj.MyInternalPropertySerializable); // Assert.AreEqual(nobj.MyInternalPropertyNotSerializable, null); //Private Assert.AreEqual(obj.GetMyPrivatePropertyNamed(), nobj.GetMyPrivatePropertyNamed()); Assert.AreEqual(obj.GetMyPrivatePropertySerializable(), nobj.GetMyPrivatePropertySerializable()); // Assert.AreEqual(nobj.GetMyPrivatePropertyNotSerializable(), null); //protected Assert.AreEqual(obj.GetMyProtectedPropertyNamed(), nobj.GetMyProtectedPropertyNamed()); Assert.AreEqual(obj.GetMyProtectedPropertySerializable(), nobj.GetMyProtectedPropertySerializable()); //Assert.AreEqual(nobj.GetMyProtectedPropertyNotSerializable(), null); }
public void MapperNonPublic_Test() { var mapper = new BsonMapper(); mapper.UseLowerCaseDelimiter('_'); mapper.IncludeNonPublic = true; var obj = CreateModel(); var doc = mapper.ToDocument(obj); var json = JsonSerializer.Serialize(doc, true); var nobj = mapper.ToObject <MyBsonFieldTestClass>(doc); Assert.AreEqual(doc["MY-STRING"].AsString, obj.MyString); Assert.AreEqual(doc["INTERNAL-PROPERTY"].AsString, obj.MyInternalPropertyNamed); Assert.AreEqual(doc["PRIVATE-PROPERTY"].AsString, obj.GetMyPrivatePropertyNamed()); Assert.AreEqual(doc["PROTECTED-PROPERTY"].AsString, obj.GetMyProtectedPropertyNamed()); Assert.AreEqual(obj.MyString, nobj.MyString); //Internal Assert.AreEqual(obj.MyInternalPropertyNamed, nobj.MyInternalPropertyNamed); Assert.AreEqual(obj.MyInternalPropertySerializable, nobj.MyInternalPropertySerializable); // Assert.AreEqual(nobj.MyInternalPropertyNotSerializable, null); //Private Assert.AreEqual(obj.GetMyPrivatePropertyNamed(), nobj.GetMyPrivatePropertyNamed()); Assert.AreEqual(obj.GetMyPrivatePropertySerializable(), nobj.GetMyPrivatePropertySerializable()); // Assert.AreEqual(nobj.GetMyPrivatePropertyNotSerializable(), null); //protected Assert.AreEqual(obj.GetMyProtectedPropertyNamed(), nobj.GetMyProtectedPropertyNamed()); Assert.AreEqual(obj.GetMyProtectedPropertySerializable(), nobj.GetMyProtectedPropertySerializable()); //Assert.AreEqual(nobj.GetMyProtectedPropertyNotSerializable(), null); }
public void AttributeMapper_Test() { var mapper = new BsonMapper(); var c0 = new AttrCustomer { MyPK = 1, NameCustomer = "J", Address = new AttrAddress { AddressPK = 5, Street = "R" }, Ignore = true, Addresses = new List <AttrAddress>() { new AttrAddress { AddressPK = 3 }, new AttrAddress { AddressPK = 4 } } }; var j0 = JsonSerializer.Serialize(mapper.ToDocument(c0)); var c1 = mapper.ToObject <AttrCustomer>(JsonSerializer.Deserialize(j0).AsDocument); Assert.AreEqual(c0.MyPK, c1.MyPK); Assert.AreEqual(c0.NameCustomer, c1.NameCustomer); Assert.AreEqual(false, c1.Ignore); Assert.AreEqual(c0.Address.AddressPK, c1.Address.AddressPK); Assert.AreEqual(c0.Addresses[0].AddressPK, c1.Addresses[0].AddressPK); Assert.AreEqual(c0.Addresses[1].AddressPK, c1.Addresses[1].AddressPK); }
public void Nested_Dictionary() { var mapper = new BsonMapper(); // map dictionary to bsondocument var dict = new Dictionary <string, object> { ["_id"] = 1, ["MyString"] = "This is string", ["Nested"] = new Dictionary <string, object>() { ["One"] = 1, ["Two"] = 2, ["Nested2"] = new Dictionary <string, object>() { ["Last"] = true } }, ["Array"] = new string[] { "one", "two" } }; var doc = mapper.ToDocument(dict); var nobj = mapper.ToObject <Dictionary <string, object> >(doc); Assert.AreEqual(dict["_id"], nobj["_id"]); Assert.AreEqual(dict["MyString"], nobj["MyString"]); Assert.AreEqual(((Dictionary <string, object>)dict["Nested"])["One"], ((Dictionary <string, object>)nobj["Nested"])["One"]); Assert.AreEqual(((string[])dict["Array"])[0], ((object[])nobj["Array"])[0].ToString()); }
public void Custom_Ctor_Byte_Property() { var obj1 = new ClassByte(150); var doc = _mapper.ToDocument(obj1); var obj2 = _mapper.ToObject <ClassByte>(doc); obj2.MyByte.Should().Be(obj1.MyByte); }
public BsonValue Execute(DbEngine engine, StringScanner s) { var col = this.ReadCollection(engine, s); var mapper = new BsonMapper().UseCamelCase(); return new BsonArray(engine.GetIndexes(col).Select(x => mapper.ToDocument<IndexInfo>(x))); }
public BsonValue Execute(DbEngine engine, StringScanner s) { var col = this.ReadCollection(engine, s); var mapper = new BsonMapper().UseCamelCase(); return(mapper.ToDocument <CollectionInfo>(engine.Stats(col))); }
public Task SaveChanges() { if (Interlocked.CompareExchange(ref _saveInProgress, 1, 0) == 0) { try { foreach (var remove in _entitiesToRemove.ToList()) { foreach (var removeItem in remove.Value.ToList()) { if (_entitiesToAdd.TryGetValue(remove.Key, out var toAddList)) { if (toAddList?.Contains(removeItem) == true) { remove.Value.Remove(removeItem); toAddList.Remove(removeItem); } } if (_entitiesToUpdate.TryGetValue(remove.Key, out var removeList)) { removeList.Remove(removeItem); } } } ProcessAction(_entitiesToAdd, (x, y) => y.Upsert(_mapper.ToDocument(x))); ProcessAction(_entitiesToUpdate, (x, y) => y.Update(_mapper.ToDocument(x))); ProcessAction(_entitiesToRemove, (x, y) => { if (!y.Delete(x.Id)) { throw new InvalidOperationException( "Failed to remove entity from storage " + _mapper.ToDocument(x)); } }); _database.Checkpoint(); } finally { _saveInProgress = 0; } } return(Task.CompletedTask); }
public void Dictionary_Map() { var obj = new Dict(); obj.DateDict[DateTime.Now] = "now!"; var doc = _mapper.ToDocument(obj); var newobj = _mapper.ToObject <Dict>(doc); newobj.DateDict.Keys.First().Should().Be(obj.DateDict.Keys.First()); }
public void Generic_Map() { var guid = Guid.NewGuid(); var today = DateTime.Today; var u0 = new User <int, string> { Id = 1, Name = "John" }; var u1 = new User <double, Guid> { Id = 99.9, Name = guid }; var u2 = new User <DateTime, string> { Id = today, Name = "Carlos" }; var u3 = new User <Dictionary <string, object>, string> { Id = new Dictionary <string, object> { ["f"] = "user1", ["n"] = 4 }, Name = "Complex User" }; var d0 = _mapper.ToDocument(u0.GetType(), u0); var d1 = _mapper.ToDocument(u1.GetType(), u1); var d2 = _mapper.ToDocument(u2.GetType(), u2); var d3 = _mapper.ToDocument(u3.GetType(), u3); d0["_id"].AsInt32.Should().Be(1); d0["Name"].AsString.Should().Be("John"); d1["_id"].AsDouble.Should().Be(99.9); d1["Name"].AsGuid.Should().Be(guid); d2["_id"].AsDateTime.Should().Be(today); d2["Name"].AsString.Should().Be("Carlos"); d3["_id"]["f"].AsString.Should().Be("user1"); d3["_id"]["n"].AsInt32.Should().Be(4); d3["Name"].AsString.Should().Be("Complex User"); }
public void Generic_Map() { var guid = Guid.NewGuid(); var today = DateTime.Today; var u0 = new User <int, string> { Id = 1, Name = "John" }; var u1 = new User <double, Guid> { Id = 99.9, Name = guid }; var u2 = new User <DateTime, string> { Id = today, Name = "Carlos" }; var u3 = new User <Dictionary <string, object>, string> { Id = new Dictionary <string, object> { ["f"] = "user1", ["n"] = 4 }, Name = "Complex User" }; var d0 = _mapper.ToDocument(u0.GetType(), u0); var d1 = _mapper.ToDocument(u1.GetType(), u1); var d2 = _mapper.ToDocument(u2.GetType(), u2); var d3 = _mapper.ToDocument(u3.GetType(), u3); Assert.AreEqual(1, d0["_id"].AsInt32); Assert.AreEqual("John", d0["Name"].AsString); Assert.AreEqual(99.9, d1["_id"].AsDouble); Assert.AreEqual(guid, d1["Name"].AsGuid); Assert.AreEqual(today, d2["_id"].AsDateTime); Assert.AreEqual("Carlos", d2["Name"].AsString); Assert.AreEqual("user1", d3["_id"]["f"].AsString); Assert.AreEqual(4, d3["_id"]["n"].AsInt32); Assert.AreEqual("Complex User", d3["Name"].AsString); }
public override BsonValue Serialize(Swap swap) { var bsonFromOutputs = swap.FromOutputs != null ? new BsonArray(swap.FromOutputs.Select(o => BsonMapper.ToDocument(o))) : null; return(new BsonDocument { [IdKey] = swap.Id, [OrderIdKey] = swap.OrderId, [StatusKey] = swap.Status.ToString(), [StateKey] = swap.StateFlags.ToString(), [TimeStampKey] = swap.TimeStamp, [SymbolKey] = swap.Symbol, [SideKey] = swap.Side.ToString(), [PriceKey] = swap.Price, [QtyKey] = swap.Qty, [IsInitiativeKey] = swap.IsInitiative, [ToAddressKey] = swap.ToAddress, [RewardForRedeemKey] = swap.RewardForRedeem, [PaymentTxIdKey] = swap.PaymentTxId, [RedeemScriptKey] = swap.RedeemScript, [RefundAddressKey] = swap.RefundAddress, [FromAddressKey] = swap.FromAddress, [FromOutputsKey] = bsonFromOutputs, [RedeemFromAddressKey] = swap.RedeemFromAddress, [PartyAddressKey] = swap.PartyAddress, [PartyRewardForRedeemKey] = swap.PartyRewardForRedeem, [PartyPaymentTxIdKey] = swap.PartyPaymentTxId, [PartyRedeemScriptKey] = swap.PartyRedeemScript, [PartyRefundAddressKey] = swap.PartyRefundAddress, [MakerNetworkFeeKey] = swap.MakerNetworkFee, [SecretKey] = swap.Secret, [SecretHashKey] = swap.SecretHash, [PaymentTxKey] = swap.PaymentTx != null ? BsonMapper.ToDocument(swap.PaymentTx) : null, [RefundTxKey] = swap.RefundTx != null ? BsonMapper.ToDocument(swap.RefundTx) : null, [RedeemTxKey] = swap.RedeemTx != null ? BsonMapper.ToDocument(swap.RedeemTx) : null, [PartyPaymentTxKey] = swap.PartyPaymentTx != null ? BsonMapper.ToDocument(swap.PartyPaymentTx) : null, }); }
public void MapInterfaces_Test() { var mapper = new BsonMapper(); var c1 = new MyClassWithInterface { Id = 1, Impl = new MyClassImpl { Name = "John Doe" } }; var c2 = new MyClassWithObject { Id = 1, Impl = new MyClassImpl { Name = "John Doe" } }; var c3 = new MyClassWithClassName { Id = 1, Impl = new MyClassImpl { Name = "John Doe" } }; var bson1 = mapper.ToDocument(c1); // add _type in Impl property var bson2 = mapper.ToDocument(c2); // add _type in Impl property var bson3 = mapper.ToDocument(c3); // do not add _type in Impl property string dllName = this.GetType().GetTypeInfo().Assembly.GetName().Name; Assert.AreEqual("LiteDB.Tests.MapperInterfaceTest+MyClassImpl, " + dllName, bson1["Impl"].AsDocument["_type"].AsString); Assert.AreEqual("LiteDB.Tests.MapperInterfaceTest+MyClassImpl, " + dllName, bson2["Impl"].AsDocument["_type"].AsString); Assert.AreEqual(false, bson3["Impl"].AsDocument.ContainsKey("_type")); var k1 = mapper.ToObject <MyClassWithInterface>(bson1); var k2 = mapper.ToObject <MyClassWithObject>(bson2); var k3 = mapper.ToObject <MyClassWithClassName>(bson3); Assert.AreEqual(c1.Impl.Name, k1.Impl.Name); Assert.AreEqual((c2.Impl as MyClassImpl).Name, (k2.Impl as MyClassImpl).Name); Assert.AreEqual(c3.Impl.Name, k3.Impl.Name); }
public void Interface_Base() { var m = new BsonMapper(); var p = new Partner("one", "host1"); var doc = m.ToDocument(p); Assert.AreEqual("one", doc["_id"].AsString); Assert.AreEqual("host1", doc["HostId"].AsString); var no = m.ToObject <Partner>(doc); Assert.AreEqual("one", no.PartnerId); Assert.AreEqual("host1", no.HostId); }
public void MapReadOnlyCollection() { var mapper = new BsonMapper(); mapper.UseLowerCaseDelimiter('_'); var obj = CreateReadOnlyModel(); var doc = mapper.ToDocument(obj); var json = JsonSerializer.Serialize(doc, true); var nobj = mapper.ToObject <ReadOnlyCompositeObject>(doc); Assert.AreEqual(3, nobj.ReadOnlyInWrapperWithSetter.Count); Assert.AreEqual(3, nobj.ReadOnlyInWrapper.Count); }
private void Eval <T, K>(T entity, Expression <Func <T, K> > expr, params K[] expect) { var expression = _mapper.GetExpression(expr); var doc = _mapper.ToDocument <T>(entity); var results = expression.Execute(doc).ToArray(); var index = 0; Assert.AreEqual(expect.Length, results.Length); foreach (var result in results) { var exp = _mapper.Serialize(typeof(K), expect[index++]); Assert.AreEqual(exp, result); } }
public void Put(string key, T tag) { try { lock (_lock) { if (key == null) { return; } using (var db = new LiteDatabase(_dataBaseFile)) { _fileHashCollection = db.GetCollection <FileHashTableEntry <T> >(_databaseName); var results = _fileHashCollection.FindOne(x => x.Key.Equals(key)); if (results != null) { results.Tag = tag; results.DeleteDate = DateTime.UtcNow + TimeSpan.FromSeconds(_expirationTime); _fileHashCollection.Update(results); } else { var ob = new FileHashTableEntry <T> { Key = key, Tag = tag, DeleteDate = DateTime.UtcNow + TimeSpan.FromSeconds(_expirationTime) }; // binary-encoded format. Extends the JSON model to provide // additional data types, ordered fields and it's quite // efficient for encoding and decoding within different languages var mapper = new BsonMapper(); var doc = mapper.ToDocument(typeof(FileHashTableEntry <T>), ob); _fileHashCollection.Insert(ob); } } } } catch (Exception ex) { _logger.Error("LifeTimeStorage.Put() - " + ex.Message); } }
public override BsonValue Serialize(BitcoinBasedTransaction tx) { if (tx == null) { return(null); } return(new BsonDocument { [IdKey] = tx.Id, [CurrencyKey] = tx.Currency.Name, [TxKey] = tx.ToBytes().ToHexString(), [BlockInfoKey] = tx.BlockInfo != null ? BsonMapper.ToDocument(tx.BlockInfo) : null }); }
public void Enum_Convert_Into_Document() { var mapper = new BsonMapper(); var c = new Customer { Id = 1, Type = CustomerType.Loyal }; var doc = mapper.ToDocument(c); doc["Type"].AsString.Should().Be("Loyal"); doc["NullableType"].IsNull.Should().BeTrue(); var fromDoc = mapper.ToObject <Customer>(doc); fromDoc.Type.Should().Be(CustomerType.Loyal); fromDoc.NullableType.Should().BeNull(); }
public void BsonField_Test() { var test_name = "BsonField_Test"; var mapper = new BsonMapper(); mapper.UseLowerCaseDelimiter('_'); var obj = CreateModel(); var doc = mapper.ToDocument(obj); var json = JsonSerializer.Serialize(doc, true); var nobj = mapper.ToObject <MyBsonFieldTestClass>(doc); Helper.AssertIsTrue(test_name, 0, doc["MY-STRING"].AsString == obj.MyString); Helper.AssertIsTrue(test_name, 1, doc["INTERNAL-PROPERTY"].AsString == obj.MyInternalPropertyNamed); Helper.AssertIsTrue(test_name, 2, doc["PRIVATE-PROPERTY"].AsString == obj.GetMyPrivatePropertyNamed()); Helper.AssertIsTrue(test_name, 3, doc["PROTECTED-PROPERTY"].AsString == obj.GetMyProtectedPropertyNamed()); Helper.AssertIsTrue(test_name, 4, obj.MyString == nobj.MyString); }
public void Struct_Test() { var mapper = new BsonMapper(); mapper.IncludeFields = true; var obj = new ContainerValue { Id = Guid.NewGuid(), Struct = new StructValue { Property = "PropertyValue" } }; var doc = mapper.ToDocument(obj); var nobj = mapper.Deserialize <ContainerValue>(doc); Assert.AreEqual(obj.Id, nobj.Id); Assert.AreEqual(obj.Struct.Property, nobj.Struct.Property); }
private void Export_Click(object sender, EventArgs e) { var sfd = new SaveFileDialog { RestoreDirectory = true, Title = @"Dump Database data to file", Filter = @"Dump file|*.dmp" }; if (sfd.ShowDialog() != DialogResult.OK) { return; } try { using (var writer = File.CreateText(sfd.FileName)) { var mapper = new BsonMapper().UseCamelCase(); foreach (var name in _db.GetCollectionNames()) { writer.WriteLine("-- Collection '{0}'", name); var col = _db.GetCollection(name); foreach (var index in col.GetIndexes().Where(x => x.Field != "_id")) { writer.WriteLine("db.{0}.ensureIndex {1} {2}", name, index.Field, JsonSerializer.Serialize(mapper.ToDocument(index.Options))); } foreach (var doc in col.Find(Query.All())) { writer.WriteLine("db.{0}.insert {1}", name, JsonSerializer.Serialize(doc)); } writer.Flush(); } } } catch (Exception ex) { MessageBox.Show(ex.Message, @"Dumping Database", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public override BsonValue Serialize(Swap swap) { return(new BsonDocument { [IdKey] = swap.Id, [OrderIdKey] = swap.OrderId, [StatusKey] = swap.Status.ToString(), [StateKey] = swap.StateFlags.ToString(), [TimeStampKey] = swap.TimeStamp, [SymbolKey] = swap.Symbol, [SideKey] = swap.Side.ToString(), [PriceKey] = swap.Price, [QtyKey] = swap.Qty, [IsInitiativeKey] = swap.IsInitiative, [ToAddressKey] = swap.ToAddress, [RewardForRedeemKey] = swap.RewardForRedeem, [PaymentTxIdKey] = swap.PaymentTxId, [RedeemScriptKey] = swap.RedeemScript, [PartyAddressKey] = swap.PartyAddress, [PartyRewardForRedeemKey] = swap.PartyRewardForRedeem, [PartyPaymentTxIdKey] = swap.PartyPaymentTxId, [PartyRedeemScriptKey] = swap.PartyRedeemScript, [SecretKey] = swap.Secret, [SecretHashKey] = swap.SecretHash, [PaymentTxKey] = swap.PaymentTx != null ? BsonMapper.ToDocument(swap.PaymentTx) : null, [RefundTxKey] = swap.RefundTx != null ? BsonMapper.ToDocument(swap.RefundTx) : null, [RedeemTxKey] = swap.RedeemTx != null ? BsonMapper.ToDocument(swap.RedeemTx) : null, [PartyPaymentTxKey] = swap.PartyPaymentTx != null ? BsonMapper.ToDocument(swap.PartyPaymentTx) : null, }); }
public void Fluent_Api_Mapping() { var o = new FluentClass { CurrentKey = 1, GetPath = () => "", PropName = "name" }; var m = new BsonMapper(); m.Entity <FluentClass>() .Id(x => x.CurrentKey) .Ignore(x => x.GetPath) .Field(x => x.PropName, "prop_name"); var d = m.ToDocument(o); Assert.AreEqual(1, d["_id"].AsInt32); Assert.IsFalse(d.Keys.Contains("GetPath")); Assert.AreEqual("name", d["prop_name"].AsString); }
public void ThreadedMappingShouldNotCauseConstructorException() { // arrange var exceptionOccured = false; var rand = new Random(); var mapper = new BsonMapper(); var list = new List <BsonDocument>(); for (var r = 0; r < rand.Next(10); r++) { var obj = new MyClassWithInterface { Id = r, Impl = new MyClassImpl { Name = $"Name_{r}" } }; list.Add(mapper.ToDocument(obj)); } // act Parallel.ForEach(list, t => { try { mapper.ToObject <MyClassWithInterface>(t); } catch (LiteException exception) { if (exception.ErrorCode == 202) { exceptionOccured = true; } } }); // assert Assert.IsFalse(exceptionOccured); }
public override BsonValue Serialize(BitcoinBasedTransaction tx) { if (tx == null) { return(null); } return(new BsonDocument { [IdKey] = tx.UniqueId, [TxIdKey] = tx.Id, [CreationTimeKey] = tx.CreationTime, [CurrencyKey] = tx.Currency, [TxKey] = tx.ToBytes().ToHexString(), [BlockInfoKey] = tx.BlockInfo != null ? BsonMapper.ToDocument(tx.BlockInfo) : null, [FeesKey] = tx.Fees, [StateKey] = tx.State.ToString(), [TypeKey] = tx.Type.ToString(), [AmountKey] = tx.Amount }); }
public void AttributeMapper_Test() { var mapper = new BsonMapper(); var c0 = new AttrCustomer { MyPK = 1, NameCustomer = "J", Address = new AttrAddress { AddressPK = 5, Street = "R" }, Ignore = true, Addresses = new List<AttrAddress>() { new AttrAddress { AddressPK = 3 }, new AttrAddress { AddressPK = 4 } } }; var j0 = JsonSerializer.Serialize(mapper.ToDocument(c0)); var c1 = mapper.ToObject<AttrCustomer>(JsonSerializer.Deserialize(j0).AsDocument); Assert.AreEqual(c0.MyPK, c1.MyPK); Assert.AreEqual(c0.NameCustomer, c1.NameCustomer); Assert.AreEqual(false, c1.Ignore); Assert.AreEqual(c0.Address.AddressPK, c1.Address.AddressPK); Assert.AreEqual(c0.Addresses[0].AddressPK, c1.Addresses[0].AddressPK); Assert.AreEqual(c0.Addresses[1].AddressPK, c1.Addresses[1].AddressPK); }