public Task <WalletAddress> GetWalletAddressAsync(Currency currency, string address)
        {
            try
            {
                lock (_syncRoot)
                {
                    using (var db = new LiteDatabase(ConnectionString, _bsonMapper))
                    {
                        var addresses = db.GetCollection(AddressesCollectionName);

                        var document = addresses.FindById(address);

                        var walletAddress = document != null
                            ? _bsonMapper.ToObject <WalletAddress>(document)
                            : null;

                        return(Task.FromResult(walletAddress));
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e, "Error getting wallet address");
            }

            return(Task.FromResult <WalletAddress>(null));
        }
Beispiel #2
0
        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 InternalGet(BsonDocument bson, Type targetType)
 {
     if (targetType.IsPrimitiveOrSimple())   // unwrap the primitive:
     {
         return(bsonMapper.ToObject <PrimitiveWrapper>(bson).val);
     }
     return(bsonMapper.ToObject(targetType, bson));
 }
Beispiel #4
0
        public void Custom_Ctor()
        {
            var doc = new BsonDocument {
                ["_id"] = 10, ["name"] = "John"
            };

            var user = _mapper.ToObject <User>(doc);

            user.Id.Should().Be(10);
            user.Name.Should().Be("John");
        }
Beispiel #5
0
        public void Mapper_Test()
        {
            var mapper = new BsonMapper();

            mapper.UseLowerCaseDelimiter('_');

            var obj  = CreateModel();
            var doc  = mapper.ToDocument(obj);
            var nobj = mapper.ToObject <MyClass>(doc);

            var json = JsonSerializer.Serialize(doc, true);

            // 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.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);

            Assert.AreEqual(obj.MyStringArray[0], nobj.MyStringArray[0]);
            Assert.AreEqual(obj.MyStringArray[1], nobj.MyStringArray[1]);
            Assert.AreEqual(obj.MyDict[2], nobj.MyDict[2]);
        }
Beispiel #6
0
        public void MapGetOnlyCollection()
        {
            var mapper = new BsonMapper();

            mapper.UseLowerCaseDelimiter('_');

            var obj = CreateModel();
            var doc = mapper.ToDocument(obj);

            var json = JsonSerializer.Serialize(doc, true);

            var nobj = mapper.ToObject <CompositeObject>(doc);

            Assert.AreEqual(2, nobj.ReadOnlyCollection.Count);
            IList <SimpleObject> list = (IList <SimpleObject>)nobj.ReadOnlyCollection;

            Assert.AreEqual("Test one", list[0].Name);
            Assert.AreEqual("Test two", list[1].Name);

            IList <SimpleObject> enumeration = (IList <SimpleObject>)nobj.ReadOnlyEnumeration;

            Assert.AreEqual("Enum one", enumeration[0].Name);
            Assert.AreEqual("Enum two", enumeration[1].Name);

            Assert.AreEqual(0, nobj.ReadOnlyArray.Length);
        }
Beispiel #7
0
        public override BitcoinBasedTransaction Deserialize(BsonValue tx)
        {
            var bson = tx as BsonDocument;

            if (bson == null)
            {
                return(null);
            }

            var currencyName = bson[CurrencyKey].IsString
                ? bson[CurrencyKey].AsString
                : string.Empty;

            var currency = _currencies.FirstOrDefault(c => c.Name.Equals(currencyName));

            if (currency is BitcoinBasedCurrency btcBaseCurrency)
            {
                return(new BitcoinBasedTransaction(
                           currency: btcBaseCurrency,
                           tx: Transaction.Parse(bson[TxKey].AsString, btcBaseCurrency.Network),
                           blockInfo: !bson[BlockInfoKey].IsNull
                        ? BsonMapper.ToObject <BlockInfo>(bson[BlockInfoKey].AsDocument)
                        : null
                           ));
            }

            return(null);
        }
Beispiel #8
0
        public void 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);

            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);
        }
Beispiel #9
0
        public void Attribute_Mapper()
        {
            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);
        }
Beispiel #10
0
        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 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());
        }
Beispiel #12
0
        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
        }
Beispiel #13
0
        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);
        }
Beispiel #14
0
        public void DictList_Test()
        {
            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]);
        }
Beispiel #15
0
        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());
        }
Beispiel #16
0
        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);
        }
Beispiel #17
0
        public override BitcoinBasedTransaction Deserialize(BsonValue tx)
        {
            var bson = tx as BsonDocument;

            if (bson == null)
            {
                return(null);
            }

            var currencyName = bson[CurrencyKey].IsString
                ? bson[CurrencyKey].AsString
                : string.Empty;

            var currency = _currencies.FirstOrDefault(c => c.Name.Equals(currencyName));

            if (currency is BitcoinBasedConfig btcBaseCurrency)
            {
                var blockInfo = !bson[BlockInfoKey].IsNull
                    ? BsonMapper.ToObject <BlockInfo>(bson[BlockInfoKey].AsDocument)
                    : null;

                return(new BitcoinBasedTransaction(
                           currency: btcBaseCurrency.Name,
                           tx: Transaction.Parse(bson[TxKey].AsString, btcBaseCurrency.Network),
                           blockInfo: blockInfo,
                           fees: !bson[FeesKey].IsNull
                        ? (long?)bson[FeesKey].AsInt64
                        : null
                           )
                {
                    State = !bson[StateKey].IsNull
                        ? (BlockchainTransactionState)Enum.Parse(typeof(BlockchainTransactionState), bson[StateKey].AsString)
                        : BlockchainTransactionState.Unknown,

                    Type = !bson[TypeKey].IsNull
                        ? (BlockchainTransactionType)Enum.Parse(typeof(BlockchainTransactionType), bson[TypeKey].AsString)
                        : BlockchainTransactionType.Unknown,

                    Amount = !bson[AmountKey].IsNull
                        ? bson[AmountKey].AsInt64
                        : 0,

                    CreationTime = bson.ContainsKey(CreationTimeKey) && !bson[CreationTimeKey].IsNull
                        ? bson[CreationTimeKey].AsDateTime
                        : blockInfo?.FirstSeen ?? blockInfo?.BlockTime
                });
            }

            return(null);
        }
Beispiel #18
0
        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);
        }
Beispiel #19
0
        public void Custom_Ctor_With_Custom_Id()
        {
            var mapper = new BsonMapper();

            mapper.Entity <UserWithCustomId>()
            .Id(u => u.Key, false);

            var doc = new BsonDocument {
                ["_id"] = 10, ["name"] = "John"
            };

            var user = mapper.ToObject <UserWithCustomId>(doc);

            user.Key.Should().Be(10); //     Expected user.Key to be 10, but found 0.
            user.Name.Should().Be("John");
        }
Beispiel #20
0
        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);
        }
Beispiel #21
0
        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();
        }
Beispiel #22
0
        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);
        }
Beispiel #23
0
        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.ToObject <ContainerValue>(doc);

            Assert.AreEqual(obj.Id, nobj.Id);
            Assert.AreEqual(obj.Struct.Property, nobj.Struct.Property);
        }
Beispiel #24
0
        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);
        }
Beispiel #25
0
        public void CustomType_Test()
        {
            var mapper = new BsonMapper();
            var o      = new CustomType
            {
                Re1 = new Regex("^a+"),
                Re2 = new Regex("^a*", RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace),
                Url = new Uri("http://www.litedb.org"),
                Ts  = TimeSpan.FromSeconds(10)
            };

            var doc = mapper.ToDocument(o);
            var no  = mapper.ToObject <CustomType>(doc);

            Assert.AreEqual("^a+", doc["Re1"].AsString);
            Assert.AreEqual("^a*", doc["Re2"].AsDocument["p"].AsString);

            Assert.AreEqual(o.Re1.ToString(), no.Re1.ToString());
            Assert.AreEqual(o.Re2.ToString(), no.Re2.ToString());
            Assert.AreEqual(o.Re2.Options, no.Re2.Options);
            Assert.AreEqual(o.Url, no.Url);
            Assert.AreEqual(o.Ts, no.Ts);
        }
        public void AddData(string data)
        {
            List <BrowserDBData> dbData = JsonConvert.DeserializeObject <List <BrowserDBData> >(data);

            foreach (var dbObj in dbData)
            {
                if (dbObj.type == AvailableDataType.WalletAddress.ToString())
                {
                    _addresses[dbObj.id] =
                        _bsonMapper.ToObject <WalletAddress>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }
                else if (dbObj.type == AvailableDataType.Transaction.ToString())
                {
                    string[] parsedId = dbObj.id.Split(Convert.ToChar("/"));
                    string   id       = parsedId[0];
                    string   currency = parsedId[1];

                    BsonDocument bd = BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data));
                    _transactions[$"{id}:{currency}"] = (IBlockchainTransaction)_bsonMapper.ToObject(doc: bd,
                                                                                                     type: _currencies.GetByName(currency).TransactionType);
                }
                else if (dbObj.type == AvailableDataType.Swap.ToString())
                {
                    _swaps[long.Parse(dbObj.id)] =
                        _bsonMapper.ToObject <Swap>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }
                else if (dbObj.type == AvailableDataType.Output.ToString())
                {
                    string[] parsedId = dbObj.id.Split(Convert.ToChar("/"));
                    string   id       = parsedId[0];
                    string   currency = parsedId[1];
                    string   address  = parsedId[2];

                    BsonDocument       bd = BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data));
                    BitcoinBasedConfig BtcBasedCurrency = _currencies.Get <BitcoinBasedConfig>(currency);
                    ITxOutput          output           =
                        (ITxOutput)_bsonMapper.ToObject(doc: bd, type: BtcBasedCurrency.OutputType());

                    _outputs[id] = new OutputEntity {
                        Output = output, Currency = currency, Address = address
                    };
                }
                else if (dbObj.type == AvailableDataType.Order.ToString())
                {
                    _orders[dbObj.id] =
                        _bsonMapper.ToObject <Order>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }

                else if (dbObj.type == AvailableDataType.TezosTokenAddress.ToString())
                {
                    _tezosTokensAddresses[dbObj.id] = _bsonMapper.ToObject <WalletAddress>(
                        BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }

                else if (dbObj.type == AvailableDataType.TezosTokenContract.ToString())
                {
                    _tezosTokensContracts[dbObj.id] =
                        _bsonMapper.ToObject <TokenContract>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }

                else if (dbObj.type == AvailableDataType.TezosTokenTransfer.ToString())
                {
                    _tezosTokensTransfers[dbObj.id] =
                        _bsonMapper.ToObject <TokenTransfer>(
                            BsonSerializer.Deserialize(Convert.FromBase64String(dbObj.data)));
                }
            }
        }
 private ClassWithInterface MapAndDemapObject(BsonMapper mapper, ClassWithInterface obj)
 {
     return(mapper.ToObject <ClassWithInterface>(mapper.ToDocument(obj)));
 }
Beispiel #28
0
        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 override Swap Deserialize(BsonValue bsonValue)
        {
            var bson = bsonValue as BsonDocument;

            if (bson == null)
            {
                return(null);
            }

            Enum.TryParse <SwapStatus>(bson[StatusKey].AsString, out var status);
            Enum.TryParse <SwapStateFlags>(bson[StateKey].AsString, out var state);
            Enum.TryParse <Side>(bson[SideKey].AsString, out var side);

            var symbol            = bson[SymbolKey].AsString;
            var soldCurrency      = _currencies.GetByName(symbol.SoldCurrency(side));
            var purchasedCurrency = _currencies.GetByName(symbol.PurchasedCurrency(side));

            return(new Swap
            {
                Id = bson[IdKey].AsInt64,
                OrderId = !bson[OrderIdKey].IsNull ? bson[OrderIdKey].AsInt64 : 0,
                Status = status,
                StateFlags = state,
                TimeStamp = bson[TimeStampKey].AsDateTime,
                Symbol = bson[SymbolKey].AsString,
                Side = side,
                Price = bson[PriceKey].AsDecimal,
                Qty = bson[QtyKey].AsDecimal,
                IsInitiative = bson[IsInitiativeKey].AsBoolean,
                ToAddress = bson[ToAddressKey].AsString,
                RewardForRedeem = bson[RewardForRedeemKey].AsDecimal,
                PaymentTxId = bson[PaymentTxIdKey].AsString,
                RedeemScript = bson[RedeemScriptKey].AsString,
                PartyAddress = bson[PartyAddressKey].AsString,
                PartyRewardForRedeem = bson[PartyRewardForRedeemKey].AsDecimal,
                PartyPaymentTxId = bson[PartyPaymentTxIdKey].AsString,
                PartyRedeemScript = bson[PartyRedeemScriptKey].AsString,

                Secret = bson[SecretKey].AsBinary,
                SecretHash = bson[SecretHashKey].AsBinary,

                PaymentTx = !bson[PaymentTxKey].IsNull
                    ? (IBlockchainTransaction)BsonMapper.ToObject(
                    type: soldCurrency.TransactionType,
                    doc: bson[PaymentTxKey].AsDocument)
                    : null,

                RefundTx = !bson[RefundTxKey].IsNull
                    ? (IBlockchainTransaction)BsonMapper.ToObject(
                    type: soldCurrency.TransactionType,
                    doc: bson[RefundTxKey].AsDocument)
                    : null,

                RedeemTx = !bson[RedeemTxKey].IsNull
                    ? (IBlockchainTransaction)BsonMapper.ToObject(
                    type: purchasedCurrency.TransactionType,
                    doc: bson[RedeemTxKey].AsDocument)
                    : null,

                PartyPaymentTx = !bson[PartyPaymentTxKey].IsNull
                    ? (IBlockchainTransaction)BsonMapper.ToObject(
                    type: purchasedCurrency.TransactionType,
                    doc: bson[PartyPaymentTxKey].AsDocument)
                    : null,
            });
        }