public BsonValue Execute(LiteDatabase db, StringScanner s) { var col = this.ReadCollection(db, s); var query = s.Match("{") ? Query.Query.All() : this.ReadQuery(s); var code = DynamicCode.GetCode(s); var docs = col.Find(query).ToArray(); try { db.BeginTrans(); foreach (var doc in docs) { code(doc["_id"], doc, col, db); } db.Commit(); return docs.Length; } catch (Exception ex) { db.Rollback(); throw ex; } }
public BsonValue Execute(LiteDatabase db, StringScanner s) { var col = this.ReadCollection(db, s); var index = s.Scan(this.FieldPattern).Trim(); return col.Max(index.Length == 0 ? "_id" : index); }
public override void Execute(ref LiteDatabase db, StringScanner s, Display d, InputCommand input) { var sb = new StringBuilder(); var enabled = !(s.Scan(@"off\s*").Length > 0); db.Log.Level = enabled ? Logger.FULL : Logger.NONE; }
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 BsonValue Execute(LiteDatabase db, StringScanner s) { var col = this.ReadCollection(db, s); var newName = s.Scan(@"[\w-]+"); return db.RenameCollection(col.Name, newName); }
public BsonValue Execute(LiteDatabase db, StringScanner s) { var col = this.ReadCollection(db, s); var query = this.ReadQuery(s); return col.Delete(query); }
public BsonValue Execute(LiteDatabase db, StringScanner s) { var col = this.ReadCollection(db, s); var docs = col.GetIndexes(); return new BsonArray(docs); }
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 BsonValue Execute(LiteDatabase db, StringScanner s) { var col = this.ReadCollection(db, s); var doc = JsonSerializer.Deserialize(s).AsDocument; return col.Update(doc); }
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()); } }
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 BsonValue Execute(LiteDatabase db, StringScanner s) { var cols = db.GetCollectionNames().OrderBy(x => x).ToArray(); if (cols.Length == 0) return BsonValue.Null; return string.Join(Environment.NewLine, cols); }
public override void Execute(ref LiteDatabase db, StringScanner s, Display display, InputCommand input) { if (db == null) throw LiteException.NoDatabase(); db.Dispose(); db = null; }
public override void Execute(ref LiteDatabase db, StringScanner s, Display display, InputCommand input) { var ver = typeof(LiteDatabase).Assembly.GetName().Version; display.WriteInfo(string.Format("v{0}.{1}.{2}", ver.Major, ver.Minor, ver.Build)); }
public override void Execute(ref LiteDatabase db, StringScanner s, Display display, InputCommand input) { var filename = s.Scan(@".+").Trim(); foreach (var line in File.ReadAllLines(filename)) { input.Queue.Enqueue(line); } }
public BsonValue Execute(LiteDatabase db, StringScanner s) { var col = this.ReadCollection(db, s); var query = this.ReadQuery(s); var skipLimit = this.ReadSkipLimit(s); var docs = col.Find(query, skipLimit.Key, skipLimit.Value); return new BsonArray(docs); }
//[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 override void Execute(ref LiteDatabase db, StringScanner s, Display display, InputCommand input) { var filename = s.Scan(@".+"); if (db != null) { db.Dispose(); } db = new LiteDatabase(filename); }
public void Bulk_Test() { using (var db = new LiteDatabase(new MemoryStream())) { var col = db.GetCollection("b"); col.Insert(GetDocs()); Assert.AreEqual(220, col.Count()); } }
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 BsonValue Execute(LiteDatabase db, StringScanner s) { var col = this.ReadCollection(db, s); var filename = s.Scan(@".*"); using (var sr = new StreamReader(filename, Encoding.UTF8)) { var docs = JsonSerializer.DeserializeArray(sr); return col.InsertBulk(docs.Select(x => x.AsDocument)); } }
public BsonValue Execute(LiteDatabase db, StringScanner s) { var id = this.ReadId(s); var filename = Path.GetFullPath(s.Scan(@"\s*.*").Trim()); if (!File.Exists(filename)) throw new IOException("File " + filename + " not found"); var file = db.FileStorage.Upload(id, filename); return file.AsDocument; }
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 MainForm() { InitializeComponent(); singleton = this; Database = new LiteDatabase(AppDatabaseFilename); Database.Tables.Add(new Database.Tables.Devices()); Database.Tables.Add(new Database.Tables.Keys()); Database.Open(); Watchers = new List<Forms.UsbWatcherForm>(); }
internal LiteFileStream(LiteDatabase db, LiteFileInfo file) { _db = db; _file = file; if (file.Length == 0) { throw LiteException.FileCorrupted(file); } _positionInChunk = 0; _currentChunkIndex = 0; _currentChunkData = this.GetChunkData(_currentChunkIndex); }
static void Main(string[] args) { LiteDatabase db = null; var input = new InputCommand(); var display = new Display(); display.TextWriters.Add(Console.Out); // show welcome message display.WriteWelcome(); // if has a argument, its database file - try open if (args.Length > 0) { try { db = new LiteDatabase(args[0]); } catch (Exception ex) { display.WriteError(ex.Message); } } while (true) { // read next command from user var cmd = input.ReadCommand(); if (string.IsNullOrEmpty(cmd)) continue; try { var isConsoleCommand = ConsoleCommand.TryExecute(cmd, ref db, display, input); if (isConsoleCommand == false) { if(db == null) throw LiteException.NoDatabase(); var result = db.Run(cmd); display.WriteResult(result); } } catch (Exception ex) { display.WriteError(ex.Message); } } }
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 LiteShell(LiteDatabase db) { this.Database = db; this.Commands = new List<ILiteCommand>(); var type = typeof(ILiteCommand); var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s => s.GetTypes()) .Where(p => type.IsAssignableFrom(p) && p.IsClass); foreach (var t in types) { this.Commands.Add((ILiteCommand)Activator.CreateInstance(t)); } }
/// <summary> /// If command is a console command, execute and returns true - if not, just returns false /// </summary> public static bool TryExecute(string command, ref LiteDatabase db, Display display, InputCommand input) { var s = new StringScanner(command); foreach (var cmd in _commands) { if (cmd.IsCommand(s)) { cmd.Execute(ref db, s, display, input); return true; } } return false; }
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 LiteDbContext(IHostingEnvironment environment, string fileName) { HostingEnvironment = environment; LiteDatabase = new LiteDatabase(fileName); }
public static void TestDb() { // открывает базу данных, если ее нет - то создает using (var db = new LiteDatabase(@"MyData.db")) { // Получаем коллекцию var col = db.GetCollection <Company>("companies"); var microsoft = new Company { Name = "Microsoft" }; microsoft.Users = new List <User> { new User { Name = "Bill Gates" } }; // Добавляем компанию в коллекцию col.Insert(microsoft); // Обновляем документ в коллекции microsoft.Name = "Microsoft Inc."; col.Update(microsoft); var google = new Company { Name = "Google" }; google.Users = new List <User> { new User { Name = "Larry Page" } }; col.Insert(google); // Получаем все документы var result = col.FindAll(); foreach (Company c in result) { Console.WriteLine(c.Name); foreach (User u in c.Users) { Console.WriteLine(u.Name); } Console.WriteLine(); } // Индексируем документ по определенному свойству col.EnsureIndex(x => x.Name); col.Delete(x => x.Name.Equals("Google")); Console.WriteLine("После удаления Google"); result = col.FindAll(); foreach (Company c in result) { Console.WriteLine(c.Name); foreach (User u in c.Users) { Console.WriteLine(u.Name); } Console.WriteLine(); } } }
public AppComponentController(IWebHostEnvironment env, AppsData data) { _env = env; _db = data.AppsDB; }
public DatabaseService() { _database = new LiteDatabase(DatabaseDir); }
public RepositoryBase() { Database = new LiteDatabase(Filename); }
public DB4Repository() { // DI Conttainer registers this as a singleton, so // we want to hold onto this instance _liteDatabase = new LiteDatabase(DbFileName); }
public LogWriterService(string dbFile, string tableName) { _db = new LiteDatabase(dbFile); _tableName = tableName; }
private void button1_Click(object sender, EventArgs e) { var dbase = new LiteDatabase(@"TestDB.db"); }
#pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #line 2 "R:\Programas\C#\Résmony_Silva_Muniz\GithubAPI\Views\Repositories\Favorites.cshtml" ViewData["Title"] = "Favorites"; Layout = "~/Views/Shared/_Layout.cshtml"; #line default #line hidden BeginContext(107, 30, true); WriteLiteral("\r\n<h1>Favoritos</h1>\r\n<br />\r\n"); EndContext(); #line 9 "R:\Programas\C#\Résmony_Silva_Muniz\GithubAPI\Views\Repositories\Favorites.cshtml" using (var db = new LiteDatabase(@"Data/favorites.db")) { var repos = db.GetCollection <Item>("items"); var results = repos.Find(x => x.name != null); if (!results.GetEnumerator().MoveNext()) { #line default #line hidden BeginContext(347, 103, true); WriteLiteral(" <div class=\"error-warning\">\r\n <h3>Nenhum repositório favorito</h3>\r\n </div>\r\n"); EndContext(); #line 16 "R:\Programas\C#\Résmony_Silva_Muniz\GithubAPI\Views\Repositories\Favorites.cshtml" } else { #line default #line hidden BeginContext(464, 189, true); WriteLiteral(" <table class=\"table table-sm table-hover table-borderless m-1\">\r\n <thead>\r\n <tr>\r\n <th>Nome</th>\r\n </tr>\r\n </thead>\r\n <tbody>\r\n"); EndContext(); #line 24 "R:\Programas\C#\Résmony_Silva_Muniz\GithubAPI\Views\Repositories\Favorites.cshtml" foreach (var result in results) { #line default #line hidden BeginContext(711, 38, true); WriteLiteral(" <tr>\r\n <td>"); EndContext(); BeginContext(750, 47, false); #line 26 "R:\Programas\C#\Résmony_Silva_Muniz\GithubAPI\Views\Repositories\Favorites.cshtml" Write(Html.ActionLink(result.name, "RepInfo", result)); #line default #line hidden EndContext(); BeginContext(797, 105, true); WriteLiteral("</td> \r\n <td colspan=\"5\">\r\n <span class=\"btn btn-outline-danger\">"); EndContext(); BeginContext(903, 68, false); #line 28 "R:\Programas\C#\Résmony_Silva_Muniz\GithubAPI\Views\Repositories\Favorites.cshtml" Write(Html.ActionLink("Remover", "RemoveFromFavs", "Repositories", result)); #line default #line hidden EndContext(); BeginContext(971, 51, true); WriteLiteral("</span>\r\n </td>\r\n </tr>\r\n"); EndContext(); #line 31 "R:\Programas\C#\Résmony_Silva_Muniz\GithubAPI\Views\Repositories\Favorites.cshtml" } #line default #line hidden BeginContext(1037, 34, true); WriteLiteral(" </tbody>\r\n\r\n </table>\r\n"); EndContext(); #line 35 "R:\Programas\C#\Résmony_Silva_Muniz\GithubAPI\Views\Repositories\Favorites.cshtml" } } #line default #line hidden }
public DownloadingFileItemRepository(LiteDatabase database) { _database = database; }
public ServerMessageSet(string dbFileFullName, bool isServer) { if (string.IsNullOrEmpty(dbFileFullName)) { throw new ArgumentNullException(nameof(dbFileFullName)); } _connectionString = $"filename={dbFileFullName}"; VirtualRoot.AddCmdPath <LoadNewServerMessageCommand>(action: message => { if (!RpcRoot.IsServerMessagesVisible) { return; } DateTime localTimestamp = VirtualRoot.LocalServerMessageSetTimestamp; // 如果已知服务器端最新消息的时间戳不比本地已加载的最新消息新就不用加载了 if (message.KnowServerMessageTimestamp <= Timestamp.GetTimestamp(localTimestamp)) { return; } RpcRoot.OfficialServer.ServerMessageService.GetServerMessagesAsync(localTimestamp, (response, e) => { if (response.IsSuccess()) { if (response.Data.Count > 0) { ReceiveServerMessage(response.Data); } } else { if (e != null) { Logger.ErrorDebugLine(e); } else { VirtualRoot.Out.ShowError(response.ReadMessage(e), autoHideSeconds: 4); } } }); }, location: this.GetType()); VirtualRoot.AddCmdPath <ReceiveServerMessageCommand>(action: message => { ReceiveServerMessage(message.Data); }, location: this.GetType()); VirtualRoot.AddCmdPath <AddOrUpdateServerMessageCommand>(action: message => { InitOnece(); if (isServer) { #region Server ServerMessageData exist; List <ServerMessageData> toRemoves = new List <ServerMessageData>(); ServerMessageData data = null; lock (_locker) { exist = _linkedList.FirstOrDefault(a => a.Id == message.Input.Id); if (exist != null) { exist.Update(message.Input); exist.Timestamp = DateTime.Now; _linkedList.Remove(exist); _linkedList.AddFirst(exist); } else { data = new ServerMessageData().Update(message.Input); data.Timestamp = DateTime.Now; _linkedList.AddFirst(data); while (_linkedList.Count > NTKeyword.ServerMessageSetCapacity) { toRemoves.Add(_linkedList.Last.Value); _linkedList.RemoveLast(); } } } if (exist != null) { try { using (LiteDatabase db = new LiteDatabase(_connectionString)) { var col = db.GetCollection <ServerMessageData>(); col.Update(exist); } } catch (Exception e) { Logger.ErrorDebugLine(e); } } else { try { using (LiteDatabase db = new LiteDatabase(_connectionString)) { var col = db.GetCollection <ServerMessageData>(); if (toRemoves.Count != 0) { foreach (var item in toRemoves) { col.Delete(item.Id); } } col.Insert(data); } } catch (Exception e) { Logger.ErrorDebugLine(e); } } #endregion } else { RpcRoot.OfficialServer.ServerMessageService.AddOrUpdateServerMessageAsync(new ServerMessageData().Update(message.Input), (response, ex) => { if (response.IsSuccess()) { VirtualRoot.Execute(new LoadNewServerMessageCommand()); } else { VirtualRoot.Out.ShowError(response.ReadMessage(ex), autoHideSeconds: 4); } }); } }, location: this.GetType()); VirtualRoot.AddCmdPath <MarkDeleteServerMessageCommand>(action: message => { InitOnece(); if (isServer) { #region Server ServerMessageData exist = null; lock (_locker) { exist = _linkedList.FirstOrDefault(a => a.Id == message.EntityId); if (exist != null) { exist.IsDeleted = true; exist.Content = string.Empty; exist.Timestamp = DateTime.Now; _linkedList.Remove(exist); _linkedList.AddFirst(exist); } } if (exist != null) { try { using (LiteDatabase db = new LiteDatabase(_connectionString)) { var col = db.GetCollection <ServerMessageData>(); col.Update(exist); } } catch (Exception e) { Logger.ErrorDebugLine(e); } } #endregion } else { RpcRoot.OfficialServer.ServerMessageService.MarkDeleteServerMessageAsync(message.EntityId, (response, ex) => { if (response.IsSuccess()) { VirtualRoot.Execute(new LoadNewServerMessageCommand()); } else { VirtualRoot.Out.ShowError(response.ReadMessage(ex), autoHideSeconds: 4); } }); } }, location: this.GetType()); VirtualRoot.AddCmdPath <ClearServerMessages>(action: message => { InitOnece(); // 服务端不应有清空消息的功能 if (isServer) { return; } try { using (LiteDatabase db = new LiteDatabase(_connectionString)) { lock (_locker) { _linkedList.Clear(); } db.DropCollection(nameof(ServerMessageData)); } } catch (Exception e) { Logger.ErrorDebugLine(e); } VirtualRoot.RaiseEvent(new ServerMessagesClearedEvent()); }, location: this.GetType()); }
public DatabaseDebugger(LiteDatabase db, int port) { _db = db; _port = port; }
public void 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); } }
public TranslateResultRepository(LiteDatabase database) : base(database) { }
public LiteDbContext() { liteDatabase = new LiteDatabase(@"Contact.db"); }
private void toolStripButton5_Click(object sender, EventArgs e) { if (fromExternalFile) { var correctAnswers = 0; var totalAnswers = likelyhood.Count; for (int i = 0; i < likelyhood.Count(); i++) { if (likelyhood[i] == checkedListBox1.GetItemChecked(i)) { correctAnswers += 1; } } using (var db = new LiteDatabase(@"MyData.db")) { var collection = db.GetCollection <StudentAnswers>("StudentAnswers"); var results = collection.Find(m => m.StudentId == FormHandler.StudentId); if (results.Count() == 0) { collection.Insert(new StudentAnswers() { CorrectAnswers = correctAnswers, Id = collection.Count() + 1, StudentId = FormHandler.StudentId, TotalAnswers = totalAnswers }); waiting = false; weStarted = false; toolStripStatusLabel5.Text = ""; progressBar2.Value = 0; toolStripStatusLabel2.Text = "Тест окончен!"; db.Dispose(); return; } var orderedResults = results.OrderBy(m => m.Id); var orderedResultsList = orderedResults.ToList(); orderedResultsList.Reverse(); PointPairList resultsTotal = new PointPairList(); PointPairList resultsCorrect = new PointPairList(); var testResults = new StudentAnswers() { Id = collection.Count() + 1, CorrectAnswers = correctAnswers, TotalAnswers = totalAnswers, StudentId = FormHandler.StudentId }; for (int i = 0; i < Math.Min(5, orderedResultsList.Count); i++) { resultsTotal.Add(i, orderedResultsList[i].TotalAnswers); resultsCorrect.Add(i, orderedResultsList[i].CorrectAnswers); } zedGraphControl1.Visible = true; zedGraphControl1.Refresh(); zedGraphControl1.GraphPane.Title.Text = "Предыдущие результаты"; GraphPane pane = zedGraphControl1.GraphPane; pane.XAxis.Title.Text = "Тест"; pane.YAxis.Title.Text = "Правильных ответов"; pane.AddBar("Всего", resultsTotal, Color.Blue); pane.AddBar("Правильно", resultsCorrect, Color.Black); zedGraphControl1.AxisChange(); zedGraphControl1.Invalidate(); var mesShow = MessageBox.Show(correctAnswers + " из " + totalAnswers + ": сохранить?", "Вы опять тут?", MessageBoxButtons.OKCancel); if (mesShow == DialogResult.OK) { collection.Insert(testResults); } collection.EnsureIndex(m => m.Id); } waiting = false; weStarted = false; toolStripStatusLabel5.Text = ""; progressBar2.Value = 0; toolStripStatusLabel2.Text = "Тест окончен!"; return; } waiting = false; weStarted = false; toolStripStatusLabel5.Text = ""; progressBar2.Value = 0; toolStripStatusLabel2.Text = "Тест окончен!"; using (var db = new LiteDatabase(@"MyData.db")) { var marksCol = db.GetCollection <StudentAnswers>("StudentAnswers"); var marks = marksCol.Find(m => m.StudentId == FormHandler.StudentId); var countMarks = marks.Count(); if (countMarks == 0) { int correctAnswers = 0; int totalAnswers = answers.Count; for (int i = 0; i < totalAnswers; i++) { if (answers[i] == checkedListBox1.GetItemChecked(i)) { correctAnswers += 1; } } marksCol.Insert(new StudentAnswers() { Id = marksCol.Count() + 1, StudentId = FormHandler.StudentId, CorrectAnswers = correctAnswers, TotalAnswers = totalAnswers }); marksCol.EnsureIndex(m => m.Id); } else { int correctAnswers = 0; int totalAnswers = answers.Count; for (int i = 0; i < totalAnswers; i++) { if (answers[i] == checkedListBox1.GetItemChecked(i)) { correctAnswers += 1; } } var lastRes = marks.Max(m => m.Id); var dialogRes = MessageBox.Show( "Бывший скор: " + marks.FirstOrDefault(m => m.Id == lastRes).CorrectAnswers + " из " + marks.FirstOrDefault(m => m.Id == lastRes).TotalAnswers + ", а сейчас... " + correctAnswers + " из " + totalAnswers + ".\nСохранить?", "Вам не впервой!", MessageBoxButtons.OKCancel); if (dialogRes == DialogResult.OK) { marksCol.Insert(new StudentAnswers() { Id = marksCol.Count() + 1, CorrectAnswers = correctAnswers, TotalAnswers = totalAnswers, StudentId = FormHandler.StudentId }); marksCol.EnsureIndex(x => x.Id); zedGraphControl1.Visible = true; zedGraphControl1.Refresh(); zedGraphControl1.GraphPane.Title.Text = "Предыдущие результаты"; PointPairList pointsTotal = new PointPairList(); PointPairList pointsCorrect = new PointPairList(); GraphPane pane = zedGraphControl1.GraphPane; pane.CurveList.Clear(); var marksSorted = marks.OrderBy(m => m.Id).ToList(); marksSorted.Reverse(); for (int i = 0; i < Math.Min(5, marksSorted.Count); i++) { pointsTotal.Add(i, marksSorted[i].TotalAnswers); pointsCorrect.Add(i, marksSorted[i].CorrectAnswers); } pane.XAxis.Title.Text = "Тест"; pane.YAxis.Title.Text = "Правильных ответов"; pane.AddBar("Всего", pointsTotal, Color.Blue); pane.AddBar("Правильно", pointsCorrect, Color.Black); zedGraphControl1.AxisChange(); zedGraphControl1.Invalidate(); } } } checkedListBox1.Items.Clear(); }
/// <summary> /// Save the Main VnInfo to the database /// </summary> /// <param name="visualNovel"></param> public static void SaveVnInfo(VisualNovel visualNovel) { if (visualNovel == null) { return; } try { var cred = CredentialManager.GetCredentials(App.CredDb); if (cred == null || cred.UserName.Length < 1) { return; } using (var db = new LiteDatabase($"{App.GetDbStringWithoutPass}'{cred.Password}'")) { var dbVnInfo = db.GetCollection <VnInfo>(DbVnInfo.VnInfo.ToString()); var dbVnInfoLinks = db.GetCollection <VnInfoLinks>(DbVnInfo.VnInfo_Links.ToString()); ILiteCollection <VnInfoScreens> dbVnInfoScreens = db.GetCollection <VnInfoScreens>(DbVnInfo.VnInfo_Screens.ToString()); ILiteCollection <VnInfoRelations> dbVnInfoRelations = db.GetCollection <VnInfoRelations>(DbVnInfo.VnInfo_Relations.ToString()); ILiteCollection <VnInfoTags> dbVnInfoTags = db.GetCollection <VnInfoTags>(DbVnInfo.VnInfo_Tags.ToString()); var prevVnInfo = dbVnInfo.Query().Where(x => x.VnId == visualNovel.Id).FirstOrDefault(); var prevVnInfoLinks = dbVnInfoLinks.Query().Where(x => x.VnId == visualNovel.Id).FirstOrDefault(); List <VnInfoTags> vnTags = new List <VnInfoTags>(); List <VnInfoRelations> vnRelations = new List <VnInfoRelations>(); List <VnInfoScreens> vnScreenshot = new List <VnInfoScreens>(); var vn = prevVnInfo ?? new VnInfo(); vn.VnId = visualNovel.Id; vn.Title = visualNovel.Name; vn.Original = visualNovel.OriginalName; vn.Released = visualNovel.Released?.ToString(); vn.Languages = CsvConverter.ConvertToCsv(visualNovel.Languages); vn.OriginalLanguages = CsvConverter.ConvertToCsv(visualNovel.OriginalLanguages); vn.Platforms = CsvConverter.ConvertToCsv(visualNovel.Platforms); vn.Aliases = CsvConverter.ConvertToCsv(visualNovel.Aliases); vn.Length = visualNovel.Length?.ToString(); vn.Description = visualNovel.Description; vn.ImageLink = !string.IsNullOrEmpty(visualNovel.Image) ? visualNovel.Image : string.Empty; vn.ImageRating = visualNovel.ImageRating; vn.Popularity = visualNovel.Popularity; vn.Rating = visualNovel.Rating; //links VnInfoLinks vnLinks = prevVnInfoLinks ?? new VnInfoLinks(); vnLinks.VnId = visualNovel.Id; vnLinks.Wikidata = visualNovel.VisualNovelLinks.Wikidata; //screenshot vnScreenshot.AddRange(FormatVnInfoScreens(visualNovel, dbVnInfoScreens)); //relations vnRelations.AddRange(FormatVnInfoRelations(visualNovel, dbVnInfoRelations)); //tags vnTags.AddRange(FormatVnInfoTags(visualNovel, dbVnInfoTags)); dbVnInfo.Upsert(vn); dbVnInfoLinks.Upsert(vnLinks); dbVnInfoScreens.Upsert(vnScreenshot); dbVnInfoRelations.Upsert(vnRelations); dbVnInfoTags.Upsert(vnTags); } } catch (IOException e) { App.Logger.Error(e, "an I/O exception occurred"); SentrySdk.CaptureException(e); } catch (Exception e) { App.Logger.Error(e, "Failed to save VnInfo"); SentrySdk.CaptureException(e); } }
private DbContent() { liteDatabase = new LiteDatabase("CozyMarkdown.db"); }
public StatisticService(LiteDatabase db, IMemoryCache cache) { _db = db; _cache = cache; }
public GUILibrary(LiteDatabase library, NotificationHandler notificationHandler, Dispatcher dispatcher) : base(library) { this.notificationHandler = notificationHandler; this.dispatcher = dispatcher; }
public LiteDbAdapter(string filename) { database = new LiteDatabase(filename); }
private ILiteCollection <SettingState> GetCollection(LiteDatabase db) { // Get a collection (or create, if doesn't exist) return(db.GetCollection <SettingState>("metadata")); }
public StocksService(IStockDbContext liteDbContext) { _database = liteDbContext.Database; }
public override LiteCollection <T> GetCollection(LiteDatabase db) => db.GetCollection <T>(CollectionName);
public CommandResult Execute(NewPostCommand command) { //TODO:应该验证TitleSlug是否唯一 var contentProvider = new FileContentProvider(null, Encoding.UTF8); var parser = new MarkdownService(contentProvider); var content = parser.ToHtml(command.MarkDown); var post = new BlogPost { Id = ObjectId.NewObjectId(), AuthorEmail = command.Author.Email, AuthorDisplayName = command.Author.DisplayName, MarkDown = command.MarkDown, Content = content, PubDate = command.PubDate.CloneToUtc(), Status = command.Published ? PublishStatus.Published : PublishStatus.Draft, Title = command.Title, TitleSlug = command.TitleSlug.IsNullOrWhitespace() ? command.Title.Trim().ToSlug() : command.TitleSlug.Trim().ToSlug(), DateUTC = DateTime.UtcNow }; using (var db = new LiteDatabase(_dbConfig.DbPath)) { 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; if (string.IsNullOrWhiteSpace(tag)) { continue; } var entry = tagCol.FindOne(t => t.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); } } tagCol.EnsureIndex(t => t.PostCount); } else { post.Tags = new string[] { }; } var blogPostCol = db.GetCollection <BlogPost>(DBTableNames.BlogPosts); blogPostCol.Insert(post); return(CommandResult.SuccessResult); } }
public DataBase(LiteDatabase db) { _db = db; }
public TagService(LiteDatabase db) { _db = db; }
public NodeHistory(ILiteDbContext liteDbContext) { _ctx = liteDbContext; _liteDb = liteDbContext.Database; }
public LiteDbRepositoryWrapper(LiteDatabase database, bool disposeDatabase = false) : base(database, disposeDatabase) { }
public DataBaseProvider(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; db = new LiteDatabase("Data.db"); }