Esempio n. 1
0
        public void LinqVisitor_Test()
        {
            var mapper = new BsonMapper();
            mapper.ResolveFieldName = (x) => x.ToLower();

            var qv = new QueryVisitor<User>(mapper);

            //var q1 = qv.Visit(x => x.Id == 1); // Query.EQ("_id", 1)

            //var q2 = qv.Visit(x => x.Active); // Query.EQ("Active", true);

            // not
            //var q3 = qv.Visit(x => !x.Active); // Query.Not("Active", true)
            //var q4 = qv.Visit(x => !(x.Id == 1)); // Query.Not(Query.EQ("_id", 1))
            //var q5 = qv.Visit(x => !x.Name.StartsWith("john")); // Query.Not(Query.StartsWith("John"))

            // enum
            //var q4 = qv.Visit(x => x.OS == PlatformID.Unix);

            //var q6 = qv.Visit(x => new int[] { 1, 2 }.Contains(x.Id));

            //var q7 = qv.Visit(x => x.Names.Contains("John"));

            //**var q8 = qv.Visit(x => x.Domains.Any(d => d.DomainName == "ABC"));

            //****var q8 = qv.Visit(x => x.Names.Any(z => z.StartsWith("John")));
            // => Query.StartsWith("Names", "John")
        }
Esempio n. 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);
        }
Esempio n. 3
0
        public void DbRefIndex_Test()
        {
            var mapper = new BsonMapper();

            mapper.Entity<DCustomer>()
                .Id(x => x.Login)
                .Field(x => x.Name, "customer_name");

            mapper.Entity<DOrder>()
                .Id(x => x.OrderNumber)
                .Field(x => x.Customer, "cust")
                .DbRef(x => x.Customer, "customers");

            using (var db = new LiteDatabase(new MemoryStream(), mapper))
            {
                var customer = new DCustomer { Login = "******", Name = "John Doe" };
                var order = new DOrder { OrderNumber = 1, Customer = customer };

                var customers = db.GetCollection<DCustomer>("Customers");
                var orders = db.GetCollection<DOrder>("Orders");

                customers.Insert(customer);
                orders.Insert(order);

                // create an index in Customer.Id ref
                // x.Customer.Login == "Customer.$id"
                orders.EnsureIndex(x => x.Customer.Login);

                var query = orders
                    .Include(x => x.Customer)
                    .FindOne(x => x.Customer.Login == "jd");

                Assert.AreEqual(customer.Name, query.Customer.Name);
            }
        }
Esempio n. 4
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);
        }
Esempio n. 5
0
 protected override void OnModelCreating(BsonMapper mapper)
 {
     mapper.Entity<Patient>()
         //.Index(x => x.Ward.Id)
         //.Index("Ward.Id")
         .DbRef(x => x.Ward, "Ward");
 }
Esempio n. 6
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);
        }
Esempio n. 7
0
 protected override void OnModelCreating(BsonMapper mapper)
 {
     mapper.Entity<Order>()
         .DbRef(x => x.Products, "products")
         .DbRef(x => x.ProductArray, "products")
         .DbRef(x => x.ProductColl, "products")
         .DbRef(x => x.ProductEmpty, "products")
         .DbRef(x => x.ProductsNull, "products")
         .DbRef(x => x.Customer, "customers")
         .DbRef(x => x.CustomerNull, "customers");
 }
Esempio n. 8
0
        protected override void OnModelCreating(BsonMapper mapper)
        {
            mapper.Entity<DCustomer>()
                .Id(x => x.Login)
                .Field(x => x.Name, "customer_name");

            mapper.Entity<DOrder>()
                .Id(x => x.OrderNumber)
                .Field(x => x.Customer, "cust")
                .DbRef(x => x.Customer, "customers");
        }
 public override void Register(BsonMapper bsonMapper)
 {
     bsonMapper.Entity <Order>()
     .Id(p => p.ClientOrderId)
     .Field(p => p.Id, "OrderId");
 }
Esempio n. 10
0
 public LiteDbStorage(LiteDatabase database)
 {
     _database = database;
     _mapper   = new BsonMapper();
 }
Esempio n. 11
0
        public void DbRef_Include()
        {
            var mapper = new BsonMapper();

            mapper.Entity <Order>()
            .DbRef(x => x.Products, "products")
            .DbRef(x => x.ProductArray, "products")
            .DbRef(x => x.ProductColl, "products")
            .DbRef(x => x.ProductEmpty, "products")
            .DbRef(x => x.ProductsNull, "products")
            .DbRef(x => x.Customer, "customers")
            .DbRef(x => x.CustomerNull, "customers");

            mapper.Entity <Customer>()
            .DbRef(x => x.MainAddress, "addresses");

            mapper.Entity <Product>()
            .DbRef(x => x.SupplierAddress, "addresses");

            using (var db = new LiteDatabase(new MemoryStream(), mapper))
            {
                var address = new Address {
                    StreetName = "3600 S Las Vegas Blvd"
                };
                var customer = new Customer {
                    Name = "John Doe", MainAddress = address
                };

                var product1 = new Product {
                    Name = "TV", Price = 800, SupplierAddress = address
                };
                var product2 = new Product {
                    Name = "DVD", Price = 200
                };

                var customers = db.GetCollection <Customer>("customers");
                var addresses = db.GetCollection <Address>("addresses");
                var products  = db.GetCollection <Product>("products");
                var orders    = db.GetCollection <Order>("orders");

                // insert ref documents
                addresses.Insert(address);
                customers.Insert(customer);
                products.Insert(new Product[] { product1, product2 });

                var order = new Order
                {
                    Customer     = customer,
                    CustomerNull = null,
                    Products     = new List <Product>()
                    {
                        product1, product2
                    },
                    ProductArray = new Product[] { product1 },
                    ProductColl  = new List <Product>()
                    {
                        product2
                    },
                    ProductEmpty = new List <Product>(),
                    ProductsNull = null
                };

                orders.Insert(order);

                //var r0 = orders
                //    .Include(x => x.Products)
                //    .Include(x => x.Products[0].SupplierAddress)
                //    .FindAll()
                //    .FirstOrDefault();

                orders.EnsureIndex(x => x.Customer.Id);

                // query orders using customer $id
                // include customer data and customer address
                var r1 = orders
                         .Include(x => x.Customer)
                         .Include(x => x.Customer.MainAddress)
                         .Find(x => x.Customer.Id == 1)
                         .FirstOrDefault();

                Assert.AreEqual(order.Id, r1.Id);
                Assert.AreEqual(order.Customer.Name, r1.Customer.Name);
                Assert.AreEqual(order.Customer.MainAddress.StreetName, r1.Customer.MainAddress.StreetName);

                // include all
                var result = orders
                             .Include(x => x.Customer)
                             .Include("Customer.MainAddress")
                             .Include(x => x.CustomerNull)
                             .Include(x => x.Products)
                             .Include(x => x.ProductArray)
                             .Include(x => x.ProductColl)
                             .Include(x => x.ProductsNull)
                             // not supported yet
                             .Include(x => x.Products[0].SupplierAddress)
                             .FindAll()
                             .FirstOrDefault();

                Assert.AreEqual(customer.Name, result.Customer.Name);
                Assert.AreEqual(customer.MainAddress.StreetName, result.Customer.MainAddress.StreetName);
                Assert.AreEqual(product1.Price, result.Products[0].Price);
                Assert.AreEqual(product2.Name, result.Products[1].Name);
                Assert.AreEqual(product1.Name, result.ProductArray[0].Name);
                Assert.AreEqual(product2.Price, result.ProductColl.ElementAt(0).Price);
                Assert.AreEqual(null, result.ProductsNull);
                Assert.AreEqual(0, result.ProductEmpty.Count);

                // not support yet
                //Assert.AreEqual(product1.SupplierAddress.StreetName, result.Products[0].SupplierAddress.StreetName);
                //Assert.AreEqual(null, result.Products[1].SupplierAddress);
            }
        }
Esempio n. 12
0
        public async Task AutoId_Strong_Typed()
        {
            var mapper = new BsonMapper();

            using (var db = new LiteDatabaseAsync(new MemoryStream(), mapper))
            {
                var cs_int  = db.GetCollection <EntityInt>("int");
                var cs_long = db.GetCollection <EntityLong>("long");
                var cs_guid = db.GetCollection <EntityGuid>("guid");
                var cs_oid  = db.GetCollection <EntityOid>("oid");
                var cs_str  = db.GetCollection <EntityString>("str");

                // int32
                var cint_1 = new EntityInt()
                {
                    Name = "R1"
                };
                var cint_2 = new EntityInt()
                {
                    Name = "R2"
                };
                var cint_3 = new EntityInt()
                {
                    Name = "R3"
                };
                var cint_4 = new EntityInt()
                {
                    Name = "R4"
                };

                // long
                var clong_1 = new EntityLong()
                {
                    Name = "R1"
                };
                var clong_2 = new EntityLong()
                {
                    Name = "R2"
                };
                var clong_3 = new EntityLong()
                {
                    Name = "R3"
                };
                var clong_4 = new EntityLong()
                {
                    Name = "R4"
                };

                // guid
                var cguid_1 = new EntityGuid()
                {
                    Name = "R1"
                };
                var cguid_2 = new EntityGuid()
                {
                    Name = "R2"
                };
                var cguid_3 = new EntityGuid()
                {
                    Name = "R3"
                };
                var cguid_4 = new EntityGuid()
                {
                    Name = "R4"
                };

                // oid
                var coid_1 = new EntityOid()
                {
                    Name = "R1"
                };
                var coid_2 = new EntityOid()
                {
                    Name = "R2"
                };
                var coid_3 = new EntityOid()
                {
                    Name = "R3"
                };
                var coid_4 = new EntityOid()
                {
                    Name = "R4"
                };

                // string - there is no AutoId for string
                var cstr_1 = new EntityString()
                {
                    Id = "a", Name = "R1"
                };
                var cstr_2 = new EntityString()
                {
                    Id = "b", Name = "R2"
                };
                var cstr_3 = new EntityString()
                {
                    Id = "c", Name = "R3"
                };
                var cstr_4 = new EntityString()
                {
                    Id = "d", Name = "R4"
                };

                // insert first 3 documents
                await cs_int.InsertAsync(new[] { cint_1, cint_2, cint_3 });

                await cs_long.InsertAsync(new[] { clong_1, clong_2, clong_3 });

                await cs_guid.InsertAsync(new[] { cguid_1, cguid_2, cguid_3 });

                await cs_oid.InsertAsync(new[] { coid_1, coid_2, coid_3 });

                await cs_str.InsertAsync(new[] { cstr_1, cstr_2, cstr_3 });

                // change document 2
                cint_2.Name  = "Changed 2";
                clong_2.Name = "Changed 2";
                cguid_2.Name = "Changed 2";
                coid_2.Name  = "Changed 2";
                cstr_2.Name  = "Changed 2";

                // update document 2
                var nu_int = await cs_int.UpdateAsync(cint_2);

                var nu_long = await cs_long.UpdateAsync(clong_2);

                var nu_guid = await cs_guid.UpdateAsync(cguid_2);

                var nu_oid = await cs_oid.UpdateAsync(coid_2);

                var nu_str = await cs_str.UpdateAsync(cstr_2);

                nu_int.Should().BeTrue();
                nu_long.Should().BeTrue();
                nu_guid.Should().BeTrue();
                nu_oid.Should().BeTrue();
                nu_str.Should().BeTrue();

                // change document 3
                cint_3.Name  = "Changed 3";
                clong_3.Name = "Changed 3";
                cguid_3.Name = "Changed 3";
                coid_3.Name  = "Changed 3";
                cstr_3.Name  = "Changed 3";

                // upsert (update) document 3
                var fu_int = await cs_int.UpsertAsync(cint_3);

                var fu_long = await cs_long.UpsertAsync(clong_3);

                var fu_guid = await cs_guid.UpsertAsync(cguid_3);

                var fu_oid = await cs_oid.UpsertAsync(coid_3);

                var fu_str = await cs_str.UpsertAsync(cstr_3);

                fu_int.Should().BeFalse();
                fu_long.Should().BeFalse();
                fu_guid.Should().BeFalse();
                fu_oid.Should().BeFalse();
                fu_str.Should().BeFalse();

                // test if was changed
                (await cs_int.FindOneAsync(x => x.Id == cint_3.Id)).Name.Should().Be(cint_3.Name);
                (await cs_long.FindOneAsync(x => x.Id == clong_3.Id)).Name.Should().Be(clong_3.Name);
                (await cs_guid.FindOneAsync(x => x.Id == cguid_3.Id)).Name.Should().Be(cguid_3.Name);
                (await cs_oid.FindOneAsync(x => x.Id == coid_3.Id)).Name.Should().Be(coid_3.Name);
                (await cs_str.FindOneAsync(x => x.Id == cstr_3.Id)).Name.Should().Be(cstr_3.Name);

                // upsert (insert) document 4
                var tu_int = await cs_int.UpsertAsync(cint_4);

                var tu_long = await cs_long.UpsertAsync(clong_4);

                var tu_guid = await cs_guid.UpsertAsync(cguid_4);

                var tu_oid = await cs_oid.UpsertAsync(coid_4);

                var tu_str = await cs_str.UpsertAsync(cstr_4);

                tu_int.Should().BeTrue();
                tu_long.Should().BeTrue();
                tu_guid.Should().BeTrue();
                tu_oid.Should().BeTrue();
                tu_str.Should().BeTrue();

                // test if was included
                (await cs_int.FindOneAsync(x => x.Id == cint_4.Id)).Name.Should().Be(cint_4.Name);
                (await cs_long.FindOneAsync(x => x.Id == clong_4.Id)).Name.Should().Be(clong_4.Name);
                (await cs_guid.FindOneAsync(x => x.Id == cguid_4.Id)).Name.Should().Be(cguid_4.Name);
                (await cs_oid.FindOneAsync(x => x.Id == coid_4.Id)).Name.Should().Be(coid_4.Name);
                (await cs_str.FindOneAsync(x => x.Id == cstr_4.Id)).Name.Should().Be(cstr_4.Name);

                // count must be 4
                (await cs_int.CountAsync(Query.All())).Should().Be(4);
                (await cs_long.CountAsync(Query.All())).Should().Be(4);
                (await cs_guid.CountAsync(Query.All())).Should().Be(4);
                (await cs_oid.CountAsync(Query.All())).Should().Be(4);
                (await cs_str.CountAsync(Query.All())).Should().Be(4);

                // for Int32 (or Int64) - add "bouble" on sequence
                var cint_10 = new EntityInt {
                    Id = 10, Name = "R10"
                };
                var cint_11 = new EntityInt {
                    Name = "R11"
                };
                var cint_7 = new EntityInt {
                    Id = 7, Name = "R7"
                };
                var cint_12 = new EntityInt {
                    Name = "R12"
                };

                await cs_int.InsertAsync(cint_10); // "loose" sequente between 5-9

                await cs_int.InsertAsync(cint_11); // insert as 11

                await cs_int.InsertAsync(cint_7);  // insert as 7

                await cs_int.InsertAsync(cint_12); // insert as 12

                cint_10.Id.Should().Be(10);
                cint_11.Id.Should().Be(11);
                cint_7.Id.Should().Be(7);
                cint_12.Id.Should().Be(12);
            }
        }
Esempio n. 13
0
 public static void InitializeMapping()
 {
     BsonMapper.RegisterTypeWithAutoMap <MongoModel>();
     BsonMapper.RegisterClassMaps(typeof(Character), typeof(Movement), typeof(Move),
                                  typeof(CharacterAttributeRow), typeof(CharacterAttribute), typeof(UniqueData));
 }
Esempio n. 14
0
 public virtual void RegisterCustomSerializers(BsonMapper mapper)
 {
 }
Esempio n. 15
0
 /// <summary>
 /// Starts LiteDB database using a generic Stream implementation (mostly MemoryStrem).
 /// Use another MemoryStrem as LOG file.
 /// </summary>
 public LiteDatabaseAsync(Stream stream, BsonMapper mapper = null)
 {
     _liteDB           = new LiteDatabase(stream, mapper);
     _backgroundThread = new Thread(BackgroundLoop);
     _backgroundThread.Start();
 }
Esempio n. 16
0
 /// <summary>
 /// Initialize database using any read/write Stream (like MemoryStream)
 /// </summary>
 internal PersistentLiteDatabase(Stream stream, BsonMapper mapper = null) : base(stream, mapper)
 {
 }
Esempio n. 17
0
 /// <summary>
 /// Starts LiteDB database using full parameters
 /// </summary>
 internal PersistentLiteDatabase(IDiskService diskService, BsonMapper mapper = null) : base(diskService, mapper)
 {
 }
 /// <inheritdoc />
 public SMALiteDabase(IDiskService diskService, BsonMapper mapper = null, string password = null,
                      TimeSpan?timeout = null, int cacheSize = 5000, Logger log = null)
     : base(diskService, mapper, password, timeout, cacheSize, log)
 {
 }
Esempio n. 19
0
 /// <summary>
 /// Starts LiteDB database using a connection string for file system database
 /// </summary>
 internal PersistentLiteDatabase(string connectionString, BsonMapper mapper = null) : base(connectionString, mapper)
 {
 }
 /// <inheritdoc />
 public SMALiteDabase(Stream stream, BsonMapper mapper = null, string password = null, bool disposeStream = false)
     : base(stream, mapper, password, disposeStream)
 {
 }
 /// <inheritdoc />
 public SMALiteDabase(ConnectionString connectionString, BsonMapper mapper = null, Logger log = null)
     : base(connectionString, mapper, log)
 {
 }
Esempio n. 22
0
File: Db.cs Progetto: cnkker/Bounds
 public Db(BsonMapper mapper = null)
     : base(Core.Application.Global.Global.ConnectionString, mapper)
 {
 }
Esempio n. 23
0
 protected override void OnModelCreating(BsonMapper mapper)
 {
     mapper.Entity <WorkItem>()
     .DbRef(x => x.Entries, CollectionNames.TimeEntries);
 }
Esempio n. 24
0
 protected override void OnModelCreating(BsonMapper mapper)
 {
     mapper.Entity <VirtualFieldEntity>()
     .Index("name_length", (c) => c.Name.Length);
 }
        public override ClientSwap 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            = _symbols.GetByName(bson[SymbolKey].AsString);
            var soldCurrency      = symbol.SoldCurrency(side);
            var purchasedCurrency = symbol.PurchasedCurrency(side);

            return(new ClientSwap
            {
                Id = bson[IdKey].AsInt64,
                Status = status,
                StateFlags = state,
                TimeStamp = bson[TimeStampKey].AsDateTime,
                Symbol = symbol,
                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,
                PartyAddress = bson[PartyAddressKey].AsString,
                PartyRewardForRedeem = bson[PartyRewardForRedeemKey].AsDecimal,
                PartyPaymentTxId = bson[PartyPaymentTxIdKey].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,
            });
        }
Esempio n. 26
0
 public static IEntityBuilder <TObject> For <TObject>(this BsonMapper mapper) => new InternalEntityBuilder <TObject>(mapper.Entity <TObject>());
Esempio n. 27
0
        public static void Main(string[] args)
        {
            TestFileRoller.TestDaily();
            TestFileRoller.TestQuarterly();
            TestFileRoller.TestHalfHourly();
            TestFileRoller.TestHourly();
            var connectionString = @"filename=c:\tmp\log1.db";
            var mapper           = new BsonMapper();

            if (File.Exists(connectionString))
            {
                File.Delete(connectionString);
            }

            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.LiterateConsole(LogEventLevel.Debug)
                         .WriteTo.LiteDB(connectionString, rollingFilePeriod: RollingPeriod.Quarterly)
                         .Enrich.WithProperty("app", "Serilog.Sinks.LiteDB.ConsoleTest")
                         .Enrich.FromLogContext()
                         .CreateLogger();

            var customer = new Customer()
            {
                Name = "cust1", Id = 23, Culture = "en-GB"
            };

            var logger = Log.ForContext <Program>();

            logger.Debug("TEST1");
            logger.Debug("datetime {date}, string {text}, integer {nummer}", DateTime.Now, "hallo", 105);
            logger.Debug("new customer {@customer}", customer);
            logger.Debug("integer {nummer}", 123);
            logger.Debug("string {text}", "hallo");
            logger.Debug("datetime {date}", DateTime.Now.AddHours(-3));
            logger.Fatal(new ArgumentNullException("haha", new Exception("INNER")), "exception {msg}", "Exception!");

            System.Threading.Thread.Sleep(6000);

            using (var db = new LiteDatabase(FileRoller.GetFilename(connectionString, RollingPeriod.Quarterly, DateTime.UtcNow)))
            {
                var result1 = db.GetCollection("log").FindOne(Query.Contains("_m", "TEST"));
                Console.WriteLine(result1.ToString());
                Console.WriteLine("");

                var result2 = db.GetCollection("log").Find(Query.EQ("app", "Serilog.Sinks.LiteDB.ConsoleTest"));
                Console.WriteLine(result2.Count());
                Console.WriteLine("");

                var result3 = db.GetCollection("log").Find(Query.GTE("nummer", 100));
                Console.WriteLine(result3.Count());
                Console.WriteLine("");

                var result4 = db.GetCollection("log").Find(Query.GTE("date", DateTime.Now.AddHours(-1)));
                Console.WriteLine(result4.Count());
                Console.WriteLine("");

                //Console.WriteLine(db.Run("db.info").ToString());

                var coll = db.GetCollection("log");
                coll.Insert(new BsonDocument(new System.Collections.Generic.Dictionary <string, BsonValue>
                {
                    { "name", new BsonValue("name1") },
                    { "created", new BsonValue(DateTime.Now) },
                }
                                             ));

                var a = db.GetCollection("log").Find(Query.All(), 0, 10);
                foreach (var a1 in a)
                {
                    var jsonString = JsonSerializer.Serialize(a1);//, true);
                    Console.WriteLine(jsonString);
                }

                var documents = coll.FindAll();
                foreach (var document in documents)
                {
                    Console.WriteLine(document.ToString());

                    //var logEvent = new LogEvent(document["Timestamp"].AsDateTime, LogEventLevel.Information, null, new MessageTemplate(document["MessageTemplate"].AsDocument["Text"], document["MessageTemplate"].AsDocument["Tokens"].AsArray), null);
                }
            }
        }
Esempio n. 28
0
 /// <summary>
 /// Starts LiteDB database using a connection string for file system database
 /// </summary>
 public LiteDatabaseAsync(string connectionString, BsonMapper mapper = null)
 {
     UnderlyingDatabase = new LiteDatabase(connectionString, mapper);
     _backgroundThread  = new Thread(BackgroundLoop);
     _backgroundThread.Start();
 }
Esempio n. 29
0
 public QueryVisitor(BsonMapper mapper)
 {
     _mapper = mapper;
     _type   = typeof(T);
 }
Esempio n. 30
0
        public void AutoId_Test()
        {
            var mapper = new BsonMapper();

            mapper.RegisterAutoId(
                (s) => s == null,
                (db, col) => "doc-" + db.Count(col, null)
                );

            // register for "long" - use an collection to manage
            mapper.RegisterAutoId <long>(
                v => v == 0,
                (db, col) =>
            {
                var seq = "_sequence";
                db.BeginTrans();
                var next = 0L;
                try
                {
                    var current = db.Find(seq, Query.EQ("_id", col)).FirstOrDefault();

                    if (current == null)
                    {
                        db.Insert(seq, new BsonDocument {
                            { "_id", col }, { "value", 1L }
                        });
                        next = 1;
                    }
                    else
                    {
                        next = current["value"] = current["value"].AsInt64 + 1;
                        db.Update(seq, current);
                    }

                    db.Commit();
                }
                catch (Exception)
                {
                    db.Rollback();
                    throw;
                }

                return(next);
            }
                );

            using (var file = new TempFile())
                using (var db = new LiteDatabase(file.Filename, mapper))
                {
                    var cs_int  = db.GetCollection <EntityInt>("int");
                    var cs_long = db.GetCollection <EntityLong>("long");
                    var cs_guid = db.GetCollection <EntityGuid>("guid");
                    var cs_oid  = db.GetCollection <EntityOid>("oid");
                    var cs_str  = db.GetCollection <EntityString>("str");

                    // int32
                    var cint_1 = new EntityInt {
                    };
                    var cint_2 = new EntityInt {
                    };
                    var cint_5 = new EntityInt {
                        Id = 5
                    };                                 // set Id, do not generate (jump 3 and 4)!
                    var cint_6 = new EntityInt {
                        Id = 0
                    };                                 // for int, 0 is empty

                    // long
                    var clong_1 = new EntityLong {
                    };
                    var clong_2 = new EntityLong {
                    };
                    var clong_3 = new EntityLong {
                    };
                    var clong_4 = new EntityLong {
                    };

                    // guid
                    var guid = Guid.NewGuid();

                    var cguid_1 = new EntityGuid {
                        Id = guid
                    };
                    var cguid_2 = new EntityGuid {
                    };

                    // oid
                    var oid = ObjectId.NewObjectId();

                    var coid_1 = new EntityOid {
                    };
                    var coid_2 = new EntityOid {
                        Id = oid
                    };

                    // string - there is no AutoId for string
                    var cstr_1 = new EntityString {
                    };
                    var cstr_2 = new EntityString {
                        Id = "mydoc2"
                    };

                    cs_int.Insert(cint_1);
                    cs_int.Insert(cint_2);
                    cs_int.Insert(cint_5);
                    cs_int.Insert(cint_6);

                    cs_long.Insert(clong_1);
                    cs_long.Insert(clong_2);
                    // delete 1 and 2 and will not re-used
                    cs_long.Delete(Query.In("_id", 1, 2));
                    cs_long.Insert(clong_3);
                    cs_long.Insert(clong_4);

                    cs_guid.Insert(cguid_1);
                    cs_guid.Insert(cguid_2);

                    cs_oid.Insert(coid_1);
                    cs_oid.Insert(coid_2);

                    cs_str.Insert(cstr_1);

                    // test for int
                    Assert.AreEqual(1, cint_1.Id);
                    Assert.AreEqual(2, cint_2.Id);
                    Assert.AreEqual(5, cint_5.Id);
                    Assert.AreEqual(6, cint_6.Id);

                    // test for long
                    Assert.AreEqual(3, clong_3.Id);
                    Assert.AreEqual(4, clong_4.Id);

                    // test for guid
                    Assert.AreEqual(guid, cguid_1.Id);
                    Assert.AreNotEqual(Guid.Empty, cguid_2.Id);
                    Assert.AreNotEqual(cguid_2.Id, cguid_1.Id);

                    // test for oid
                    Assert.AreNotEqual(ObjectId.Empty, coid_1.Id);
                    Assert.AreEqual(oid, coid_2.Id);

                    // test for string
                    Assert.AreEqual("doc-0", cstr_1.Id);
                    Assert.AreEqual("mydoc2", cstr_2.Id);
                }
        }
Esempio n. 31
0
 public override void Register(BsonMapper bsonMapper)
 {
     bsonMapper.Entity <EthereumTransaction>()
     .Id(tx => tx.UniqueId)
     .Field(tx => tx.Id, "TxId");
 }
 public LiteDbRepositoryWrapper(Stream stream, BsonMapper mapper = null, string password = null) : base(stream, mapper, password)
 {
 }
Esempio n. 33
0
 private static void RegisterMappings(BsonMapper mapper)
 {
     mapper.Entity <TaskActivity>()
     .DbRef(x => x.Task, CollectionsNames.Tasks);
 }
Esempio n. 34
0
 private ClassWithInterface MapAndDemapObject(BsonMapper mapper, ClassWithInterface obj)
 {
     return(mapper.ToObject <ClassWithInterface>(mapper.ToDocument(obj)));
 }
Esempio n. 35
0
        public void Include_Test()
        {
            var mapper = new BsonMapper();

            mapper.Entity<Order>()
               .DbRef(x => x.Products, "products")
               .DbRef(x => x.ProductArray, "products")
               .DbRef(x => x.ProductColl, "products")
               .DbRef(x => x.ProductEmpty, "products")
               .DbRef(x => x.ProductsNull, "products")
               .DbRef(x => x.Customer, "customers")
               .DbRef(x => x.CustomerNull, "customers");

            mapper.Entity<Customer>()
                .DbRef(x => x.MainAddress, "addresses");

            mapper.Entity<Product>()
                .DbRef(x => x.SupplierAddress, "addresses");

            using (var file = new TempFile())
            using (var db = new LiteDatabase(file.Filename, mapper))
            {
                var address = new Address { StreetName = "3600 S Las Vegas Blvd" };
                var customer = new Customer { Name = "John Doe", MainAddress = address };

                var product1 = new Product { Name = "TV", Price = 800, SupplierAddress = address };
                var product2 = new Product { Name = "DVD", Price = 200 };

                var customers = db.GetCollection<Customer>("customers");
                var addresses = db.GetCollection<Address>("addresses");
                var products = db.GetCollection<Product>("products");
                var orders = db.GetCollection<Order>("orders");

                // insert ref documents
                addresses.Insert(address);
                customers.Insert(customer);
                products.Insert(new Product[] { product1, product2 });

                var order = new Order
                {
                    Customer = customer,
                    CustomerNull = null,
                    Products = new List<Product>() { product1, product2 },
                    ProductArray = new Product[] { product1 },
                    ProductColl = new List<Product>() { product2 },
                    ProductEmpty = new List<Product>(),
                    ProductsNull = null
                };

                orders.Insert(order);

                var query = orders
                    .Include(x => x.Customer)
                    .Include(x => x.Customer.MainAddress)
                    .Include(x => x.CustomerNull)
                    .Include(x => x.Products)
                    .Include(x => x.ProductArray)
                    .Include(x => x.ProductColl)
                    .Include(x => x.ProductsNull)
                    .FindAll()
                    .FirstOrDefault();

                Assert.AreEqual(customer.Name, query.Customer.Name);
                Assert.AreEqual(customer.MainAddress.StreetName, query.Customer.MainAddress.StreetName);
                Assert.AreEqual(product1.Price, query.Products[0].Price);
                Assert.AreEqual(product2.Name, query.Products[1].Name);
                Assert.AreEqual(product1.Name, query.ProductArray[0].Name);
                Assert.AreEqual(product2.Price, query.ProductColl.ElementAt(0).Price);
                Assert.AreEqual(null, query.ProductsNull);
                Assert.AreEqual(0, query.ProductEmpty.Count);
            }
        }
Esempio n. 36
0
 private CerberusDatabase(string connectionString, BsonMapper mapper = null, Logger log = null) : base(connectionString, mapper, log)
 {
 }
Esempio n. 37
0
        public void AutoId_Test()
        {
            var mapper = new BsonMapper();

            mapper.RegisterAutoId(
                (s) => s == null,
                (c) => "doc-" + c.Count()
                );

            using (var file = new TempFile())
                using (var db = new LiteDatabase(file.Filename, mapper))
                {
                    var cs_int  = db.GetCollection <EntityInt>("int");
                    var cs_guid = db.GetCollection <EntityGuid>("guid");
                    var cs_oid  = db.GetCollection <EntityOid>("oid");
                    var cs_str  = db.GetCollection <EntityString>("str");

                    // int32
                    var cint_1 = new EntityInt {
                    };
                    var cint_2 = new EntityInt {
                    };
                    var cint_5 = new EntityInt {
                        Id = 5
                    };                                 // set Id, do not generate (jump 3 and 4)!
                    var cint_6 = new EntityInt {
                        Id = 0
                    };                                 // for int, 0 is empty

                    // guid
                    var guid = Guid.NewGuid();

                    var cguid_1 = new EntityGuid {
                        Id = guid
                    };
                    var cguid_2 = new EntityGuid {
                    };

                    // oid
                    var oid = ObjectId.NewObjectId();

                    var coid_1 = new EntityOid {
                    };
                    var coid_2 = new EntityOid {
                        Id = oid
                    };

                    // string - there is no AutoId for string
                    var cstr_1 = new EntityString {
                    };
                    var cstr_2 = new EntityString {
                        Id = "mydoc2"
                    };

                    cs_int.Insert(cint_1);
                    cs_int.Insert(cint_2);
                    cs_int.Insert(cint_5);
                    cs_int.Insert(cint_6);

                    cs_guid.Insert(cguid_1);
                    cs_guid.Insert(cguid_2);

                    cs_oid.Insert(coid_1);
                    cs_oid.Insert(coid_2);

                    cs_str.Insert(cstr_1);

                    // test for int
                    Assert.AreEqual(1, cint_1.Id);
                    Assert.AreEqual(2, cint_2.Id);
                    Assert.AreEqual(5, cint_5.Id);
                    Assert.AreEqual(6, cint_6.Id);

                    // test for guid
                    Assert.AreEqual(guid, cguid_1.Id);
                    Assert.AreNotEqual(Guid.Empty, cguid_2.Id);
                    Assert.AreNotEqual(cguid_2.Id, cguid_1.Id);

                    // test for oid
                    Assert.AreNotEqual(ObjectId.Empty, coid_1.Id);
                    Assert.AreEqual(oid, coid_2.Id);

                    // test for string
                    Assert.AreEqual("doc-0", cstr_1.Id);
                    Assert.AreEqual("mydoc2", cstr_2.Id);
                }
        }
 public LiteDbRepositoryWrapper(ConnectionString connectionString, BsonMapper mapper = null) : base(connectionString, mapper)
 {
 }
Esempio n. 39
0
 public void Initialize()
 {
     _mapper = new CollectionMapperClass();
 }
Esempio n. 40
0
        public void AutoId_Test()
        {
            var mapper = new BsonMapper();

            mapper.RegisterAutoId(
                (s) => s == null,
                (c) => "doc-" + c.Count()
            );

            using (var file = new TempFile())
            using (var db = new LiteDatabase(file.Filename, mapper))
            {
                var cs_int = db.GetCollection<EntityInt>("int");
                var cs_guid = db.GetCollection<EntityGuid>("guid");
                var cs_oid = db.GetCollection<EntityOid>("oid");
                var cs_str = db.GetCollection<EntityString>("str");

                // int32
                var cint_1 = new EntityInt { };
                var cint_2 = new EntityInt { };
                var cint_5 = new EntityInt { Id = 5 }; // set Id, do not generate (jump 3 and 4)!
                var cint_6 = new EntityInt { Id = 0 }; // for int, 0 is empty

                // guid
                var guid = Guid.NewGuid();

                var cguid_1 = new EntityGuid { Id = guid };
                var cguid_2 = new EntityGuid { };

                // oid
                var oid = ObjectId.NewObjectId();

                var coid_1 = new EntityOid { };
                var coid_2 = new EntityOid { Id = oid };

                // string - there is no AutoId for string
                var cstr_1 = new EntityString { };
                var cstr_2 = new EntityString { Id = "mydoc2" };

                cs_int.Insert(cint_1);
                cs_int.Insert(cint_2);
                cs_int.Insert(cint_5);
                cs_int.Insert(cint_6);

                cs_guid.Insert(cguid_1);
                cs_guid.Insert(cguid_2);

                cs_oid.Insert(coid_1);
                cs_oid.Insert(coid_2);

                cs_str.Insert(cstr_1);

                // test for int
                Assert.AreEqual(1, cint_1.Id);
                Assert.AreEqual(2, cint_2.Id);
                Assert.AreEqual(5, cint_5.Id);
                Assert.AreEqual(6, cint_6.Id);

                // test for guid
                Assert.AreEqual(guid, cguid_1.Id);
                Assert.AreNotEqual(Guid.Empty, cguid_2.Id);
                Assert.AreNotEqual(cguid_2.Id, cguid_1.Id);

                // test for oid
                Assert.AreNotEqual(ObjectId.Empty, coid_1.Id);
                Assert.AreEqual(oid, coid_2.Id);

                // test for string
                Assert.AreEqual("doc-0", cstr_1.Id);
                Assert.AreEqual("mydoc2", cstr_2.Id);
            }
        }