public void DerivedType_Test() { using (var db = new LiteDatabase(new MemoryStream())) { var derived1 = new Derived1 { Id = 1, Member1 = "Derived1" }; var derived2 = new Derived2 { Id = 2, Member2 = "Dereived2" }; var colTyped = db.GetCollection<Base>("Collection"); colTyped.Insert(derived1); colTyped.Insert(derived2); var colBson = db.GetCollection<BsonDocument>("Collection"); // checks if BsonDocument contains _type var doc1 = colBson.FindById(1); var doc2 = colBson.FindById(2); Assert.IsTrue(doc1["_type"].AsString.Contains("Derived1")); Assert.IsTrue(doc2["_type"].AsString.Contains("Derived2")); // now, test if all document will deserialize with right type var d1 = colTyped.FindById(1); var d2 = colTyped.FindById(2); Assert.IsTrue(d1 is Derived1); Assert.IsTrue(d2 is Derived2); } }
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); } }
public void Index_Order() { using (var db = new LiteDatabase(new MemoryStream())) { var col = db.GetCollection<BsonDocument>("order"); col.Insert(new BsonDocument().Add("text", "D")); col.Insert(new BsonDocument().Add("text", "A")); col.Insert(new BsonDocument().Add("text", "E")); col.Insert(new BsonDocument().Add("text", "C")); col.Insert(new BsonDocument().Add("text", "B")); col.EnsureIndex("text"); var asc = string.Join("", col.Find(Query.All("text", Query.Ascending)) .Select(x => x["text"].AsString) .ToArray()); var desc = string.Join("", col.Find(Query.All("text", Query.Descending)) .Select(x => x["text"].AsString) .ToArray()); Assert.AreEqual(asc, "ABCDE"); Assert.AreEqual(desc, "EDCBA"); } }
public void TransactionNestedException_Test() { using (var f = new TempFile()) using (var db = new LiteDatabase(f.Filename)) { var col = db.GetCollection<Person>("Person"); try { using (var transaction1 = db.BeginTrans()) { col.Insert(new Person { Id = 1, Fullname = "John" }); using (var transaction2 = db.BeginTrans()) { col.Insert(new Person { Id = 2, Fullname = "Joana" }); } col.Insert(new Person { Id = 1, Fullname = "Foo Bar" }); // throws duplicate key exception } } catch (LiteException) { } Assert.AreEqual(0, col.Count()); } }
// tmp test method public dynamic GetAllDataTmp() { var collection1 = _dbRunningValues?.GetCollection <DataCollectorDataEntry>(Collection_RunningExections); var collection2 = _dbRunningValues?.GetCollection <DataCollectorDataAgg>(Collection_Agg_IntraHour); var collection3 = _dbRunningValues?.GetCollection <AuditEntry>(Collection_Audit); var x = new { Executions = collection1?.FindAll().TakeLast(50).ToList(), Agg = collection2?.FindAll().TakeLast(20).ToList(), Audit = collection3?.FindAll().TakeLast(10).ToList(), ExecutionCnt = collection1?.Count(), AggCnt = collection2?.Count(), AuditCnt = collection3?.Count() }; return(x); }
public static IStateOperationBuilder <T> StateStore <T>(this LiteDatabase db, string id) { if (db is null) { throw new ArgumentNullException(nameof(db)); } var collection = db?.GetCollection <KVEntity <T> >(KVEntity <T> .DefaultCollection); return(new StateOperationBuilder <T>(collection, id)); }
public void Bulk_Test() { using (var db = new LiteDatabase(new MemoryStream())) { var col = db.GetCollection("b"); col.Insert(GetDocs()); Assert.AreEqual(220, col.Count()); } }
//[TestMethod] public void LongCountTest_Test() { using (var db = new LiteDatabase(DB.RandomFile())) { var c = db.GetCollection("col1"); c.Insert(GetDocs()); Assert.AreEqual(TOTAL_COUNT, c.LongCount()); } }
public void AutoIndex_Test() { using (var database = new LiteDatabase(new MemoryStream())) { var doc1 = new BsonDocument { ["name"] = "john doe" }; var people = database.GetCollection("people"); people.Insert(doc1); var result = people.FindOne(Query.EQ("name", "john doe")); Assert.AreEqual(doc1["name"], result["name"]); } }
public void DropCollection_Test() { using (var db = new LiteDatabase(new MemoryStream())) { Assert.IsFalse(db.CollectionExists("customerCollection")); var collection = db.GetCollection<Customer>("customerCollection"); collection.Insert(new Customer()); Assert.IsTrue(db.CollectionExists("customerCollection")); db.DropCollection("customerCollection"); Assert.IsFalse(db.CollectionExists("customerCollection")); } }
public void Linq_Test() { using (var db = new LiteDatabase(new MemoryStream())) { var c1 = new User { Id = 1, Name = "Mauricio", Active = true, Domain = new UserDomain { DomainName = "Numeria" } }; var c2 = new User { Id = 2, Name = "Malatruco", Active = false, Domain = new UserDomain { DomainName = "Numeria" } }; var c3 = new User { Id = 3, Name = "Chris", Domain = new UserDomain { DomainName = "Numeria" } }; var c4 = new User { Id = 4, Name = "Juliane" }; var col = db.GetCollection<User>("Customer"); col.EnsureIndex(x => x.Name, true); col.Insert(new User[] { c1, c2, c3, c4 }); // a simple lambda function to returns string "Numeria" Func<string> GetNumeria = () => "Numeria"; var strNumeria = GetNumeria(); // sub-class Assert.AreEqual(3, col.Count(x => x.Domain.DomainName == "Numeria")); Assert.AreEqual(3, col.Count(x => x.Domain.DomainName == GetNumeria())); Assert.AreEqual(3, col.Count(x => x.Domain.DomainName == strNumeria)); // == != Assert.AreEqual(1, col.Count(x => x.Id == 1)); Assert.AreEqual(3, col.Count(x => x.Id != 1)); // member booleans Assert.AreEqual(3, col.Count(x => !x.Active)); Assert.AreEqual(1, col.Count(x => x.Active)); // methods Assert.AreEqual(1, col.Count(x => x.Name.StartsWith("mal"))); Assert.AreEqual(1, col.Count(x => x.Name.Equals("Mauricio"))); Assert.AreEqual(1, col.Count(x => x.Name.Contains("cio"))); // > >= < <= Assert.AreEqual(1, col.Count(x => x.Id > 3)); Assert.AreEqual(1, col.Count(x => x.Id >= 4)); Assert.AreEqual(1, col.Count(x => x.Id < 2)); Assert.AreEqual(1, col.Count(x => x.Id <= 1)); // and/or Assert.AreEqual(1, col.Count(x => x.Id > 0 && x.Name == "MAURICIO")); Assert.AreEqual(2, col.Count(x => x.Name == "malatruco" || x.Name == "MAURICIO")); } }
public void EnumerableTest() { using (var file = new TempFile()) using (var db = new LiteDatabase(file.Filename)) { var col = db.GetCollection<User>("Users"); col.EnsureIndex(x => x.Name, true); col.EnsureIndex(x => x.Age); col.Insert(new[] { new User() { Id = 1, Name = "John Smith", Age = 10 }, new User() { Id = 2, Name = "Jane Smith", Age = 12 }, new User() { Id = 3, Name = "John Doe", Age = 24 }, new User() { Id = 4, Name = "Jane Doe", Age = 42 } }); var empty = new string[] { }; Assert.AreEqual(0, col.Count(user => empty.All(name => user.Name.Contains(name)))); Assert.AreEqual(0, col.Count(user => empty.Any(name => user.Name.Contains(name)))); var firstNames = new[] { "John", "Jane", "Jon", "Janet" }; Assert.AreEqual(0, col.Count(user => firstNames.All(name => user.Name.StartsWith(name)))); Assert.AreEqual(4, col.Count(user => firstNames.Any(name => user.Name.StartsWith(name)))); var surnames = new[] { "Smith", "Doe", "Mason", "Brown" }; Assert.AreEqual(0, col.Count(user => surnames.All(name => user.Name.Contains(name)))); Assert.AreEqual(4, col.Count(user => surnames.Any(name => user.Name.Contains(name)))); var johnSmith = new[] { "John", "Smith" }; Assert.AreEqual(1, col.Count(user => johnSmith.All(name => user.Name.Contains(name)))); Assert.AreEqual(3, col.Count(user => johnSmith.Any(name => user.Name.Contains(name)))); var janeDoe = new[] { "Jane", "Doe" }; Assert.AreEqual(1, col.Count(user => janeDoe.All(name => user.Name.Contains(name)))); Assert.AreEqual(3, col.Count(user => janeDoe.Any(name => user.Name.Contains(name)))); var numRange = new[] { new { Min = 10, Max = 12 }, new { Min = 21, Max = 33 } }; var numQuery = numRange.Select(num => Query.And(Query.GTE("Age", num.Min), Query.LTE("Age", num.Max))); var queryResult = col.Find(numQuery.Aggregate((lhs, rhs) => Query.Or(lhs, rhs))); var lambdaResult = col.Find(p => numRange.Any(num => p.Age >= num.Min && p.Age <= num.Max)); var seq1 = queryResult.OrderBy(u => u.Name); var seq2 = lambdaResult.OrderBy(u => u.Name); Assert.IsTrue(queryResult.OrderBy(u => u.Name).SequenceEqual(lambdaResult.OrderBy(u => u.Name))); } }
//[TestMethod] public void BigFile_Test() { var fileSize = 8L * 1024L * 1024L * 1024L; // 5Gb var filename = "C:/Github/LiteDB/TestResults/test-4gb.db"; // DB.Path(); //File.Delete(filename); while (GetFileSize(filename) < fileSize) { using (var db = new LiteDatabase("journal=false;filename=" + filename)) { var col = db.GetCollection("col1"); col.Insert(GetDocs()); } } }
public void DataTable_Test() { using (var db = new LiteDatabase(new MemoryStream())) { db.Run("db.col1.insert {name:\"John Doe\"}"); db.Run("db.col1.insert {name:\"Jonatan Doe\", age: 25}"); db.Run("db.col1.insert {name:\"Maria Doe\", age: 32, active: false}"); var query = db.GetCollection("col1").FindAll(); var dt = query.ToDataTable(); Assert.AreEqual(3, dt.Rows.Count); Assert.AreEqual("John Doe", (string)dt.Rows[0]["name"]); Assert.AreEqual(25, (int)dt.Rows[1]["age"]); Assert.AreEqual(false, (bool)dt.Rows[2]["active"]); } }
public void TransactionCommit_Test() { using (var f = new TempFile()) using (var db = new LiteDatabase(f.Filename)) { var col = db.GetCollection<Person>("Person"); col.Insert(new Person { Fullname = "John" }); col.Insert(new Person { Fullname = "Doe" }); using (var transaction = db.BeginTrans()) { col.Insert(new Person { Fullname = "Joana" }); col.Insert(new Person { Fullname = "Marcus" }); } Assert.AreEqual(4, col.Count()); } }
public void DeleteByName_Test() { using (var f = new TempFile()) using (var db = new LiteDatabase(f.Filename)) { var col = db.GetCollection<Person>("Person"); col.Insert(new Tests.Person { Fullname = "John" }); col.Insert(new Tests.Person { Fullname = "Doe" }); col.Insert(new Tests.Person { Fullname = "Joana" }); col.Insert(new Tests.Person { Fullname = "Marcus" }); // lets auto-create index in FullName and delete from a non-pk node var del = col.Delete(x => x.Fullname.StartsWith("J")); Assert.AreEqual(2, del); } }
public void ShrinkDatabaseTest_Test() { using (var file = new TempFile()) using (var db = new LiteDatabase(file.Filename)) { var col = db.GetCollection<LargeDoc>("col"); col.Insert(GetDocs(1, 10000)); db.DropCollection("col"); // full disk usage var size = file.Size; var r = db.Shrink(); // only header page Assert.AreEqual(BasePage.PAGE_SIZE, size - r); } }
public void MultiKeyMapper_Test() { using (var file = new TempFile()) using (var db = new LiteDatabase(file.Filename)) { var col = db.GetCollection<MultiKeyDoc>("col"); col.Insert(new MultiKeyDoc { Id = 1, Keys = new int[] { 1, 2, 3 }, Customers = new List<Customer>() { new Customer { Name = "John" }, new Customer { Name = "Ana" }, new Customer { Name = "Doe" } } }); col.Insert(new MultiKeyDoc { Id = 2, Keys = new int[] { 2 }, Customers = new List<Customer>() { new Customer { Name = "Ana" } } }); col.EnsureIndex(x => x.Keys); col.EnsureIndex(x => x.Customers.Select(z => z.Name)); // Query.EQ("Keys", 2) Assert.AreEqual(2, col.Count(x => x.Keys.Contains(2))); // Query.StartsWith("Customers.Name", "Ana"); Assert.AreEqual(2, col.Count(x => x.Customers.Any(z => z.Name.StartsWith("Ana")))); } }
public void FindAll_Test() { using (var f = new TempFile()) { using (var db = new LiteDatabase(f.Filename)) { var col = db.GetCollection<Person>("Person"); col.Insert(new Tests.Person { Fullname = "John" }); col.Insert(new Tests.Person { Fullname = "Doe" }); col.Insert(new Tests.Person { Fullname = "Joana" }); col.Insert(new Tests.Person { Fullname = "Marcus" }); } // close datafile using (var db = new LiteDatabase(f.Filename)) { var p = db.GetCollection<Person>("Person").Find(Query.All("Fullname", Query.Ascending)); Assert.AreEqual(4, p.Count()); } } }
public void Polymorphic_Test() { using (var file = new TempFile()) { using (var db = new LiteDatabase(file.Filename)) { var col = db.GetCollection<MyBase>("col1"); col.Insert(new Descendant1() { Id = 1 }); col.Insert(new Descendant2() { Id = 2 }); } using (var db = new LiteDatabase(file.Filename)) { var col = db.GetCollection<MyBase>("col1"); var d1 = col.FindById(1); var d2 = col.FindById(2); Assert.AreEqual(typeof(Descendant1), d1.GetType()); Assert.AreEqual(typeof(Descendant2), d2.GetType()); } } }
public void TransactionException_Test() { using (var f = new TempFile()) using (var db = new LiteDatabase(f.Filename)) { var col = db.GetCollection<Person>("Person"); col.Insert(new Person { Fullname = "John" }); col.Insert(new Person { Fullname = "Doe" }); try { using (var transaction = db.BeginTrans()) { col.Insert(new Person { Fullname = "Joana" }); col.Insert(new Person { Fullname = "Marcus" }); throw new IOException(); } } catch (IOException) { } Assert.AreEqual(2, col.Count()); } }
private ILiteCollection <JsonItem> GetCollection(LiteDatabase db) { return(db?.GetCollection <JsonItem>("json_items")); }
public jsDALHealthDbEntry GetLatest() { var dbCollection = _database?.GetCollection <jsDALHealthDbEntry>($"HealthData"); return(dbCollection?.FindOne(Query.All(Query.Descending))); }
public Library() { ipMacPairs = db.GetCollection(nameof(ipMacPairs)); }
public NoteDb() { db = new LiteDatabase(@"note.db"); col = db.GetCollection <Note>("note"); }
public void Migration0toCurrentTest() { var path = Path.Combine(Playnite.PlayniteTests.TempPath, "migration_0_Current.db"); FileSystem.DeleteFile(path); var games = new List <Playnite.Models.Old0.Game>() { new Playnite.Models.Old0.Game() { Provider = Provider.Custom, ProviderId = "TestId1", Name = "Test Name 1", CommunityHubUrl = @"http://communityurl.com", StoreUrl = @"http://storeurl.com", WikiUrl = @"http://wiki.com" }, new Playnite.Models.Old0.Game() { Provider = Provider.Custom, ProviderId = "TestId2", Name = "Test Name 2", CommunityHubUrl = @"http://communityurl.com" }, new Playnite.Models.Old0.Game() { Provider = Provider.Custom, ProviderId = "TestId3", Name = "Test Name 3" } }; using (var database = new LiteDatabase(path)) { database.Engine.UserVersion = 0; var collection = database.GetCollection <Playnite.Models.Old0.Game>("games"); foreach (var game in games) { var id = collection.Insert(game); var genericCollection = database.GetCollection("games"); var record = genericCollection.FindById(id); record.AsDocument["_type"] = "Playnite.Models.Game, Playnite"; genericCollection.Update(record.AsDocument); } } GameDatabase.MigrateDatabase(path); var db = new GameDatabase(null, path); using (db.OpenDatabase()) { Assert.IsTrue(db.GamesCollection.Count() == 3); var migratedGames = db.GamesCollection.FindAll().ToList(); Assert.AreEqual(3, migratedGames[0].Links.Count); Assert.IsFalse(string.IsNullOrEmpty(migratedGames[0].Links.First(a => a.Name == "Store").Url)); Assert.IsFalse(string.IsNullOrEmpty(migratedGames[0].Links.First(a => a.Name == "Wiki").Url)); Assert.IsFalse(string.IsNullOrEmpty(migratedGames[0].Links.First(a => a.Name == "Forum").Url)); Assert.AreEqual(1, migratedGames[1].Links.Count); Assert.IsNull(migratedGames[2].Links); } }
public static Class1 GetObjetoClass1(int id) { return(_encryptedDB.GetCollection <Class1>("Classes").FindOne(x => x.CLASS_ID == id)); }
private Migrator(IReadOnlyList <Migration <T> > migrations, LiteDatabase db) { this.Migrations = migrations; this._migrationCollection = db?.GetCollection <DbMigration>("__migrations__"); this._migrationCollection?.EnsureIndex(x => x.Id, unique: true); }
public UrlSiteMapper(IPrint print, string filename = "Sites.Db") { _print = print; db = new LiteDatabase(filename); liteCollection = db.GetCollection <UrlSiteMapperRecord>("SiteUrls"); }
public void AutoId_Test() { string test_name = "AutoId_Test"; var mapper = new BsonMapper(); mapper.RegisterAutoId( (s) => s == null, (c) => "doc-" + c.Count() ); using (var db = new LiteDatabase(new MemoryStream(), 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 Helper.AssertIsTrue(test_name, 0, 1 == cint_1.Id); Helper.AssertIsTrue(test_name, 1, 2 == cint_2.Id); Helper.AssertIsTrue(test_name, 2, 5 == cint_5.Id); Helper.AssertIsTrue(test_name, 3, 6 == cint_6.Id); // test for guid Helper.AssertIsTrue(test_name, 4, guid == cguid_1.Id); Helper.AssertIsTrue(test_name, 5, Guid.Empty != cguid_2.Id); Helper.AssertIsTrue(test_name, 6, cguid_2.Id != cguid_1.Id); // test for oid Helper.AssertIsTrue(test_name, 7, ObjectId.Empty != coid_1.Id); Helper.AssertIsTrue(test_name, 8, oid == coid_2.Id); // test for string Helper.AssertIsTrue(test_name, 9, "doc-0" == cstr_1.Id); Helper.AssertIsTrue(test_name, 10, "mydoc2" == cstr_2.Id); } }
public DatabaseHelper() { context = new LiteDatabase("ticketDb - V2.db"); allTickets = context.GetCollection <Ticket>("allTickets"); }
/// <summary> /// Read collection name from db.(colname).(command) /// </summary> public LiteCollection<BsonDocument> ReadCollection(LiteDatabase db, StringScanner s) { return db.GetCollection(s.Scan(@"db\.([\w-]+)\.\w+\s*", 1)); }
public IEnumerable <TModel> FindAll() { return(_liteDb.GetCollection <TModel>(ModelRepository).FindAll()); }
/// <summary> /// Private method to build the ContactService from the constructor. /// </summary> /// <param name="connectionString">LiteDB connection string</param> /// <param name="network">NBitcion-compatible blockchain network</param> private void ContactSetup(string connectionString, Network network) { MainNetwork = network; db = new LiteDatabase(connectionString); collection = db.GetCollection <Contact>(); }
public TaxRules AddTaxRules(TaxRules rules) { //insert check if exists //_taxRules.Add(rules.TaxRuleNumber, rules); _liteDb.GetCollection <TaxRules>("TaxRules").Insert(rules); return(rules); }
public static void Register(IRouter router, LiteDatabase db) { var cookingSchedule = db.GetCollection <Cooking>("cooking"); router.Get("", Utils.Authed, (req, res) => { try { var c = cookingSchedule.FindAll(); return(res.SendJson(c)); } catch (Exception e) { // We get to this point if we have malformed data in the database. We do not care about preserving // old data ATM, so simply delete it. cookingSchedule.Delete(c => true); return(res.SendJson(new List <Cooking>())); } }); router.Post("", Utils.Authed, async(req, res) => { var form = await req.GetFormDataAsync(); if (!Cooking.TryParseForm(form, out var cooking, out var error, true)) { return(await res.SendString(error, status: HttpStatusCode.BadRequest)); } cooking.Chef = req.GetData <OsteSession>().Name; var items = cookingSchedule.Find(item => item.Date.Equals(cooking.Date)); if (items.Any()) { return(await res.SendString("Der findes allerede et måltid for den uge", status: HttpStatusCode.BadRequest)); } cooking.Participants.Add(cooking.Chef); cookingSchedule.Insert(cooking); return(await res.SendJson(cooking)); }); router.Put("", Utils.Authed, async(req, res) => { var form = await req.GetFormDataAsync(); if (!Cooking.TryParseForm(form, out var cooking, out var error)) { return(await res.SendString(error, status: HttpStatusCode.BadRequest)); } Console.WriteLine(cooking.ToString()); var cook = cookingSchedule.FindOne(i => i.Equals(cooking)); if (cook == null) { return(await res.SendString("Der findes ikke noget måltid for den valgte dato", status: HttpStatusCode.BadRequest)); } cook.Date = cooking.Date; cook.Meal = cooking.Meal; cook.Chef = req.GetData <OsteSession>().Name; cook.Price = cooking.Price; cookingSchedule.Update(cook); return(await res.SendJson(cook)); }); router.Put("/participate", Utils.Authed, async(req, res) => { // Validate that a user is logged in var user = req.GetData <OsteSession>().Name; if (string.IsNullOrEmpty(user)) { return(await res.SendString("Dit brugernavn kunne ikke findes. Er du logget ind?", status: HttpStatusCode.BadRequest)); } // Get the week number of the cooking session the user wishes to participate in var form = await req.GetFormDataAsync(); if (!form.ContainsKey("week")) { return(await res.SendString("Could not find field 'week'", status: HttpStatusCode.BadRequest)); } string id = form["id"]; // Find the cooking session var cooking = cookingSchedule.FindOne(i => i.Id.Equals(id)); // Check if the user has already subscribed, return error if so if (cooking.Participants == null) { cooking.Participants = new List <string>(); } if (cooking.Participants.Contains(user)) { return(await res.SendString("Du deltager allerede i det måltid")); } // Add the user and return OK cooking.Participants.Add(user); cookingSchedule.Update(cooking); return(await res.SendJson(cooking)); }); router.Delete("/participate", Utils.Authed, async(req, res) => { // Validate that a user is logged in var user = req.GetData <OsteSession>().Name; if (string.IsNullOrEmpty(user)) { return(await res.SendString("Dit brugernavn kunne ikke findes. Er du logget ind?", status: HttpStatusCode.BadRequest)); } // Get the week number of the cooking session and find the session in the database var form = await req.GetFormDataAsync(); if (!form.ContainsKey("id")) { return(await res.SendString("Could not find field 'id'", status: HttpStatusCode.BadRequest)); } string id = form["id"]; var cooking = cookingSchedule.FindOne(c => c.Id.Equals(id)); // Check if the user is the chef, return error if so, as the Chef must participate in the session if (cooking.Chef == user) { return(await res.SendString("Du skal deltage i dit eget måltid", status: HttpStatusCode.BadRequest)); } // Check if the user is participating, return error if not if (cooking.Participants == null) { cooking.Participants = new List <string>(); } if (!cooking.Participants.Contains(user)) { return(await res.SendString("Du kan ikke forlade et måltid du ikke deltager i", status: HttpStatusCode.BadRequest)); } // Now remote the user, and save the changes to the database. cooking.Participants.Remove(user); cookingSchedule.Update(cooking); return(await res.SendJson(cooking)); }); router.Delete("", Utils.Authed, async(req, res) => { var form = await req.GetFormDataAsync(); if (!form.ContainsKey("id")) { return(await res.SendString("Intet måltid valgt", status: HttpStatusCode.BadRequest)); } string id = form["id"]; Console.WriteLine(id); var m = cookingSchedule.FindOne(w => w.Id.Equals(id)); if (m == null) { return(await res.SendString("Der er ikke nogen menu for den valgte dato", status: HttpStatusCode.NotFound)); } cookingSchedule.Delete(m.Id); return(await res.SendStatus(HttpStatusCode.OK)); }); }
public void Linq_Test() { using (var file = new TempFile()) using (var db = new LiteDatabase(file.Filename)) { var c1 = new User { Id = 1, Name = "Mauricio", Active = true, Domain = new UserDomain { DomainName = "Numeria" }, OS = PlatformID.Xbox }; var c2 = new User { Id = 2, Name = "Malatruco", Active = false, Domain = new UserDomain { DomainName = "Numeria" }, OS = PlatformID.Win32NT }; var c3 = new User { Id = 3, Name = "Chris", Domain = new UserDomain { DomainName = "Numeria" }, OS = PlatformID.Win32NT }; var c4 = new User { Id = 4, Name = "Juliane", OS = PlatformID.Win32NT }; var col = db.GetCollection<User>("Customer"); col.EnsureIndex(x => x.Name, true); col.EnsureIndex(x => x.OS, false); col.EnsureIndex(x => x.Domains.Select(z => z.DomainName), false); col.Insert(new User[] { c1, c2, c3, c4 }); // a simple lambda function to returns string "Numeria" Func<string> GetNumeria = () => "Numeria"; var strNumeria = GetNumeria(); // == != Assert.AreEqual(1, col.Count(x => x.Id == 1)); Assert.AreEqual(3, col.Count(x => x.Id != 1)); // member booleans Assert.AreEqual(3, col.Count(x => !x.Active)); Assert.AreEqual(1, col.Count(x => x.Active)); // > >= < <= Assert.AreEqual(1, col.Count(x => x.Id > 3)); Assert.AreEqual(1, col.Count(x => x.Id >= 4)); Assert.AreEqual(1, col.Count(x => x.Id < 2)); Assert.AreEqual(1, col.Count(x => x.Id <= 1)); // sub-class Assert.AreEqual(3, col.Count(x => x.Domain.DomainName == "Numeria")); Assert.AreEqual(3, col.Count(x => x.Domain.DomainName == GetNumeria())); Assert.AreEqual(3, col.Count(x => x.Domain.DomainName == strNumeria)); // methods Assert.AreEqual(1, col.Count(x => x.Name.StartsWith("Mal"))); Assert.AreEqual(1, col.Count(x => x.Name.Equals("Mauricio"))); Assert.AreEqual(1, col.Count(x => x.Name.Contains("cio"))); // enum Assert.AreEqual(1, col.Count(x => x.OS == PlatformID.Xbox)); Assert.AreEqual(1, col.Count(x => x.OS == (PlatformID)5)); // Xbox Assert.AreEqual(1, col.Count(x => x.OS == (PlatformID)Enum.Parse(typeof(PlatformID), "Xbox"))); Assert.AreEqual(3, col.Count(x => x.OS == PlatformID.Win32NT)); // doesnt works... must be a better linq provider //var Platforms = new PlatformID[] { PlatformID.Xbox, PlatformID.Win32NT }; //Assert.AreEqual(4, col.Count(x => Platforms.Contains(x.OS))); // and/or Assert.AreEqual(1, col.Count(x => x.Id > 0 && x.Name == "Mauricio")); Assert.AreEqual(2, col.Count(x => x.Name == "Malatruco" || x.Name == "Mauricio")); } }
private RecentDB() { liteDb = new LiteDatabase($"{Environment.UserName}.recent.db"); collection = liteDb.GetCollection <RecentItem>("recents"); }
public IssueTracker(IOptions <AppSettings> appSettings) { database = new LiteDatabase(appSettings.Value.ConnectionStrings.ApplicationDb); collection = database.GetCollection <Issue>(); }
public void Concurrent_Test() { var dbname = DB.RandomFilename(); var N = 300; // interate counter var a = new LiteDatabase(dbname); var b = new LiteDatabase(dbname); var c = new LiteDatabase(dbname); var d = new LiteDatabase(dbname); // task A -> insert N documents var ta = Task.Factory.StartNew(() => { var col = a.GetCollection("col1"); col.EnsureIndex("name"); for (var i = 1; i <= N; i++) { col.Insert(this.CreateDoc(i, "-insert-")); } }); // task B -> update N documents var tb = Task.Factory.StartNew(() => { var col = b.GetCollection("col1"); var i = 1; while (i <= N) { var doc = this.CreateDoc(i, "-update-"); doc["date"] = new DateTime(2015, 1, 1); doc["desc"] = null; var success = col.Update(doc); if (success) i++; } }); // tasK C -> delete N-1 documents (keep only _id = 1) var tc = Task.Factory.StartNew(() => { var col = c.GetCollection("col1"); var i = 2; while (i <= N) { // delete document after update if (col.Exists(Query.And(Query.EQ("_id", i), Query.EQ("name", "-update-")))) { var success = col.Delete(i); if (success) i++; } } }); // task D -> upload 40 files + delete 20 var td = Task.Factory.StartNew(() => { for (var i = 1; i <= 40; i++) { d.FileStorage.Upload("f" + i, this.CreateMemoryFile(20000)); } for (var i = 1; i <= 20; i++) { d.FileStorage.Delete("f" + i); } }); // Now, test data Task.WaitAll(ta, tb, tc, td); a.Dispose(); b.Dispose(); c.Dispose(); d.Dispose(); using (var db = new LiteDatabase(dbname)) { var col = db.GetCollection("col1"); var doc = col.FindById(1); Assert.AreEqual("-update-", doc["name"].AsString); Assert.AreEqual(new DateTime(2015, 1, 1), doc["date"].AsDateTime); Assert.AreEqual(true, doc["desc"].IsNull); Assert.AreEqual(col.Count(), 1); Assert.AreEqual(1, col.Count()); Assert.AreEqual(20, db.FileStorage.FindAll().Count()); } }
private void CreateTestTable() { _collection = _database.GetCollection <CoreDataUnit>(Helper.TABLE_NAME); }
public CommandResult Execute(EditPostCommand command) { using (var db = new LiteDatabase(_dbConfig.DbPath)) { var blogPostCol = db.GetCollection <BlogPost>(DBTableNames.BlogPosts); var post = blogPostCol.FindById(command.PostId); if (post == null) { throw new ApplicationException("Post with id: {0} was not found".FormatWith(command.PostId)); } if (post.Tags != null) { var tagCol = db.GetCollection <Tag>(DBTableNames.Tags); foreach (var tag in post.Tags) { var slug = tag.ToSlug(); var tagEntry = tagCol.FindOne(x => x.Slug.Equals(slug)); if (tagEntry != null) { tagEntry.PostCount--; tagCol.Update(tagEntry); } } } var contentProvider = new FileContentProvider(null, Encoding.UTF8); var parser = new MarkdownService(contentProvider); var content = parser.ToHtml(command.MarkDown); //TODO:应该验证TitleSlug是否是除了本文外唯一的 post.MarkDown = command.MarkDown; post.Content = content; post.PubDate = command.PubDate.CloneToUtc(); post.Status = command.Published ? PublishStatus.Published : PublishStatus.Draft; post.Title = command.Title; post.TitleSlug = command.TitleSlug.Trim().ToSlug(); if (!command.Tags.IsNullOrWhitespace()) { var tags = command.Tags.AsTags(); post.Tags = tags.Keys.ToArray(); var tagCol = db.GetCollection <Tag>(DBTableNames.Tags); foreach (var kv in tags) { var slug = kv.Key; var tag = kv.Value; var entry = tagCol.FindOne(x => x.Slug.Equals(slug)); if (entry != null) { entry.PostCount++; tagCol.Update(entry); } else { entry = new Tag { Id = ObjectId.NewObjectId(), Slug = slug, Name = tag, PostCount = 1 }; tagCol.Insert(entry); } } } else { post.Tags = new string[] { }; } db.GetCollection <BlogPost>(DBTableNames.BlogPosts).Update(post); return(CommandResult.SuccessResult); } }
public SheetService(LiteDatabase database, FileManager _srd) { Client = new HttpClient(); collection = database.GetCollection <Character>("Characters"); FileManager = _srd; }
public Task <IEnumerable <Article> > GetAll() => Task.Run( () => _liteDatabase.GetCollection <Article>().FindAll() );
public static void ClassInit(TestContext context) { db = new LiteDatabase(new MemoryStream()); col = db.GetCollection<TestPocoClass>("col1"); col.EnsureIndex(o => o.Key); }
private void Setup() { using (var db = new LiteDatabase(_filename)) { db.DropCollection("targets"); for (var i = 0; i < 1000; i++) { db.GetCollection<Target>("targets").Insert(this.CreateTarget()); } } }
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 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); } }
internal LiteDbLockFactory(LiteDatabase db) { _db = db; _fileLocks = db.GetCollection <IndexFileLock>(LiteDbCollectionsInfo.FileLocks); }
protected AbstractRepo(LiteDatabase db) { Collection = db.GetCollection <T>(CollectionName); }
public LiteCollection <T> GetCollection <T>(string name) { return(database.GetCollection <T>(name)); }
public void AutoId_Test() { using (var db = new LiteDatabase(new MemoryStream())) { 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 { Name = "Using Int 1" }; var cint_2 = new EntityInt { Name = "Using Int 2" }; var cint_5 = new EntityInt { Id = 5, Name = "Using Int 5" }; // set Id, do not generate (jump 3 and 4)! var cint_6 = new EntityInt { Id = 0, Name = "Using Int 6" }; // for int, 0 is empty // guid var guid = Guid.NewGuid(); var cguid_1 = new EntityGuid { Id = guid, Name = "Using Guid" }; var cguid_2 = new EntityGuid { Name = "Using Guid" }; // oid var oid = ObjectId.NewObjectId(); var coid_1 = new EntityOid { Name = "ObjectId-1" }; var coid_2 = new EntityOid { Id = oid, Name = "ObjectId-2" }; // string - there is no AutoId for string var cstr_1 = new EntityString { Name = "Object using String" }; 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); try { cs_str.Insert(cstr_1); Assert.Fail(); } catch (LiteException) { // must fail because EntityString class has a defined Id // but has no value and no auto_id funtion - issue #43 } // test for int Assert.AreEqual(cint_1.Id, 1); Assert.AreEqual(cint_2.Id, 2); Assert.AreEqual(cint_5.Id, 5); Assert.AreEqual(cint_6.Id, 6); // test for guid Assert.AreEqual(cguid_1.Id, guid); Assert.AreNotEqual(cguid_2.Id, Guid.Empty); Assert.AreNotEqual(cguid_1.Id, cguid_2.Id); // test for oid Assert.AreNotEqual(coid_1, ObjectId.Empty); Assert.AreEqual(coid_2.Id, oid); } }
private static ILiteCollection <Source> AllSources(LiteDatabase db) { return(db.GetCollection <Source>(LiteDbContext.Sources)); }
public LiteCollection <T> GetTable <T>() where T : new() { return(liteDataBase.GetCollection <T>(nameof(T))); }
public void Migration1toCurrentTest() { var path = Path.Combine(Playnite.PlayniteTests.TempPath, "migration_1_Current.db"); FileSystem.DeleteFile(path); var emulators = new List <Playnite.Models.Old1.Emulator>() { new Playnite.Models.Old1.Emulator("TestEmu") { Arguments = "Test Arguments", Executable = "Test Executable", ImageExtensions = new List <string>() { ".ext1", ".ext2" }, Platforms = new List <int>() { 1, 2 }, WorkingDirectory = "Test Directory" }, new Playnite.Models.Old1.Emulator("TestEmu2") { Arguments = "Test Arguments2", Executable = "Test Executable2", ImageExtensions = new List <string>() { ".ext3", ".ext4" }, Platforms = new List <int>() { 3 }, WorkingDirectory = "Test Directory2" } }; var platforms = new List <Playnite.Models.Old1.Platform>() { new Playnite.Models.Old1.Platform("TestPlat1"), new Playnite.Models.Old1.Platform("TestPlat2") }; using (var database = new LiteDatabase(path)) { database.Engine.UserVersion = 1; var emuCol = database.GetCollection <Playnite.Models.Old1.Emulator>("emulators"); emuCol.InsertBulk(emulators); var platCol = database.GetCollection <Playnite.Models.Old1.Platform>("platforms"); platCol.InsertBulk(platforms); var gamesCol = database.GetCollection <Playnite.Models.Old1.Game>("games"); var games = new List <Playnite.Models.Old1.Game>() { new Playnite.Models.Old1.Game() { Provider = Provider.Custom, ProviderId = "TestId1", PlatformId = 1, Name = "Test Name 1", PlayTask = new Playnite.Models.Old1.GameTask() { Type = GameTaskType.Emulator, EmulatorId = emuCol.FindAll().First().Id }, OtherTasks = new ObservableCollection <Playnite.Models.Old1.GameTask>() { new Playnite.Models.Old1.GameTask() { Type = GameTaskType.Emulator, EmulatorId = emuCol.FindAll().First().Id } } }, new Playnite.Models.Old1.Game() { Provider = Provider.Custom, ProviderId = "TestId2", PlatformId = null, Name = "Test Name 2", PlayTask = new Playnite.Models.Old1.GameTask() { Type = GameTaskType.Emulator, EmulatorId = 0 }, OtherTasks = new ObservableCollection <Playnite.Models.Old1.GameTask>() { new Playnite.Models.Old1.GameTask() { Type = GameTaskType.Emulator, EmulatorId = 0 } } } }; gamesCol.InsertBulk(games); var genericCollection = database.GetCollection("games"); foreach (var game in genericCollection.FindAll().ToList()) { game.AsDocument["_type"] = "Playnite.Models.Game, Playnite"; genericCollection.Update(game.AsDocument); } var file = Playnite.PlayniteTests.CreateFakeFile(); database.FileStorage.Upload(file.Name, file.Path); file = Playnite.PlayniteTests.CreateFakeFile(); database.FileStorage.Upload(file.Name, file.Path); } GameDatabase.MigrateDatabase(path); var db = new GameDatabase(null, path); using (db.OpenDatabase()) { var plats = db.PlatformsCollection.FindAll().ToList(); Assert.IsNotNull(plats[0].Id); Assert.IsNotNull(plats[1].Id); var emus = db.EmulatorsCollection.FindAll().ToList(); Assert.AreEqual(2, emus.Count()); Assert.AreEqual(plats[0].Id, emus[0].Profiles[0].Platforms[0]); Assert.AreEqual(plats[1].Id, emus[0].Profiles[0].Platforms[1]); CollectionAssert.IsEmpty(emus[1].Profiles[0].Platforms); Assert.IsNotNull(emus[0].Id); Assert.IsNotNull(emus[1].Id); var emu = emus.First(); var emuConf = emu.Profiles.First(); Assert.AreEqual(1, emu.Profiles.Count); Assert.IsNotNull(emu.Profiles); Assert.AreEqual("Test Arguments", emuConf.Arguments); Assert.AreEqual("Test Executable", emuConf.Executable); Assert.AreEqual("Test Directory", emuConf.WorkingDirectory); Assert.AreEqual(2, emuConf.Platforms.Count); Assert.AreEqual(2, emuConf.ImageExtensions.Count); Assert.AreEqual("ext1", emuConf.ImageExtensions[0]); Assert.AreEqual("ext2", emuConf.ImageExtensions[1]); var games = db.GamesCollection.FindAll().ToList(); var game = games[0]; Assert.AreEqual(plats[0].Id, game.PlatformId); Assert.AreEqual(emu.Profiles.First().Id, game.PlayTask.EmulatorProfileId); Assert.AreEqual(emu.Id, game.PlayTask.EmulatorId); Assert.AreEqual(emu.Profiles.First().Id, game.OtherTasks[0].EmulatorProfileId); Assert.AreEqual(emu.Id, game.OtherTasks[0].EmulatorId); Assert.IsNull(games[1].PlatformId); Assert.IsNull(games[1].PlayTask.EmulatorId); Assert.IsNull(games[1].PlayTask.EmulatorProfileId); Assert.IsNull(games[1].OtherTasks[0].EmulatorId); Assert.IsNull(games[1].OtherTasks[0].EmulatorProfileId); var files = db.Database.FileStorage.FindAll().ToList(); Assert.AreEqual(2, files.Count); foreach (var file in files) { Assert.IsTrue(file.Metadata.ContainsKey("checksum")); Assert.IsFalse(string.IsNullOrEmpty(file.Metadata["checksum"].AsString)); } } }
private ILiteCollection <T> GetDbCollection <T>(string name) where T : new() { return(db.GetCollection <T>(name)); }
private ILiteCollection <JiraSprint> GetCollection() { return(_db.GetCollection <JiraSprint>(COLLECTION_SPRINTS)); }