public TorrentImdbEntry GetById(Uri id) { using (var db = new LiteDatabase(PCinemaDbName)) { var movie = db.GetCollection<TorrentImdbEntry>(TorrentImdbEntryCollectionName) .Find(x => x.TorrentLink == id) .FirstOrDefault(x => x.TorrentLink == id); return movie; } }
private void Import_OnClick(object sender, RoutedEventArgs e) { var openFileDialog = new OpenFileDialog { Filter = "Файлы БД программы (USD.db)|USD.db|Все файлы БД (*.db)|*.db|Все файлы (*.*)|*.*" }; if (openFileDialog.ShowDialog() == true) { using (var db = new LiteDatabase(DirectoryHelper.GetDataDirectory() + Settings.Default.LiteDbFileName)) { using (var db1 = new LiteDatabase(openFileDialog.FileName)) { if (!db1.CollectionExists("screenings")) { MessageBox.Show( "Не подходящая база данных. Используйте базу данных, только от этой программы.", "УЗД", MessageBoxButton.OK, MessageBoxImage.Error); return; } var origCol = db.GetCollection("screenings"); var newCol = db1.GetCollection("screenings"); foreach (var source in newCol.FindAll().ToList()) { source["Id"] = null; origCol.Insert(source); } } } (DataContext as ListViewModel.ListViewModel)?.LoadData(); MessageBox.Show("Данные успешно импортированны", "УЗД", MessageBoxButton.OK, MessageBoxImage.Information); } }
public Task <T> GetAsync <T>(string key) { if (string.IsNullOrEmpty(key)) { throw new ArgumentException("Key MUST have a value"); } var tcs = new TaskCompletionSource <T>(); try { using (var db = new LiteDB.LiteDatabase(dbPath)) { var collection = db.GetCollection <LiteDbDataStoreItem>(DataStoreCollectionName); var idKey = GenerateStoredKey(key, typeof(T)); var item = collection.FindById(idKey); tcs.SetResult(item == null ? default(T) : NewtonsoftJsonSerializer.Instance.Deserialize <T>(item.Data)); } } catch (Exception ex) { tcs.SetException(ex); } return(tcs.Task); }
public static LiteDatabase CreateDBContext() { //打开或者创建新的数据库 var db = new LiteDatabase("App_Data/MyData.db"); return db; }
private void search(string by, string what) { try { reception_Frm = new Reception_frm(this); using (var db = new LiteDB.LiteDatabase(@"database.db")) { var coll = db.GetCollection <Reserve>("Reserves"); coll.EnsureIndex(x => x.name); coll.EnsureIndex(x => x.reserveDate); var row = coll.Find(Query.StartsWith(by, what)).Select(x => new { Code = x.ID, Name = x.name, Mobile = x.mobile, Job = x.job, Department = x.dept, Date = x.reserveDate.ToString("d/MM/yyyy") }); MessageBox.Show("github"); dgReception.DataSource = row.ToList(); } } catch (Exception) { } }
public void change_password() { var author = new Author() { Email = "*****@*****.**", HashedPassword = Hasher.GetMd5Hash("mzblog") }; using (var _db = new LiteDatabase(_dbConfig.DbPath)) { var authorCol = _db.GetCollection<Author>(DBTableNames.Authors); authorCol.Insert(author); new ChangePasswordCommandInvoker(_dbConfig) .Execute(new ChangePasswordCommand() { AuthorId = author.Id, OldPassword = "******", NewPassword = "******", NewPasswordConfirm = "pswtest" }) .Success.Should().BeTrue(); authorCol.FindById(author.Id).HashedPassword.Should().BeEquivalentTo(Hasher.GetMd5Hash("pswtest")); } }
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 Task<int> SaveDataAsync(InventurItem item, bool isNew = false) { return Task.Factory.StartNew(() => { item.ChangedAt = DateTime.Now; item.Exported = false; using (var db = new LiteDatabase(dbName)) { var col = db.GetCollection<InventurItem>(tabName); if (isNew) { //Zuerst prüfen ob es bereits einen Eintrag gibt var existing = col.Find(x => x.EANCode == item.EANCode && x.Exported == false).FirstOrDefault(); if (existing != null) { existing.Amount += item.Amount; existing.ChangedAt = item.ChangedAt; col.Update(existing); } else { item.CreatedAt = DateTime.Now; var res = col.Insert(item); } } else { col.Update(item); } return 1; } }); }
/// <summary> /// Wraps a database operation in a try/catch block /// </summary> /// <typeparam name="U">The type of result expected from the function</typeparam> /// <param name="path">The database path and filename</param> /// <param name="f">The operation to invoke</param> /// <returns>A CallResult with the result of the operation</returns> #pragma warning disable CS1573 public static CallResult <U> LiteDbAction <U>(string path, Func <LiteDatabase, U> f, [CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = 0) #pragma warning restore CS1573 { var result = new CallResult <U>(); try { if (f == null) { throw new ArgumentNullException("LiteDbAction: Parameter 'f' cannot be null"); } using (var db = new LiteDB.LiteDatabase(path)) { result.Result = f.Invoke(db); result.Success = true; } } catch (LiteException e) { result.Exception = e; Log.e(new Exception(string.Format("LiteException: ErrorCode={0}, Message={1}", e.ErrorCode, e.Message), e)); } catch (Exception e) { result.Exception = e; Log.e(new Exception(string.Format("Caller:{0}, Line:{1}, File:{2}", callerMemberName, callerLineNumber, callerFilePath), e)); } return(result); }
public bool Delete(int id) { //var results = col.Find(x => x.Name.StartsWith("Jo")); try { using (var db = new LiteDatabase(liteDBPath)) { // Get a collection (or create, if not exits) var col = db.GetCollection<Note>("notes"); var note = col.FindOne(x => x.Id == id); if (note == null) return false; if (col.Delete(x => x.Id == id) <= 0) return false; return true; } } catch (Exception) { //throw; return false; } }
/// <summary> /// Retrieve byte data from the database /// </summary> /// <param name="path">The database path and filename</param> /// <param name="id">The unique id used to identify the data</param> /// <returns>The data if found, otherwise null</returns> public static CallResult <byte[]> Download(this string path, string id) { var result = new CallResult <byte[]>(); try { using (var db = new LiteDB.LiteDatabase(path)) { var li = db.FileStorage.FindById(id); using (var ms = new System.IO.MemoryStream()) { ms.Seek(0, System.IO.SeekOrigin.Begin); li.CopyTo(ms); result.Result = ms.ToArray(); result.Success = true; } } } catch (Exception e) { result.Exception = e; Log.e(e); } return(result); }
public ControllerFactory(string dbpath =null) { if (String.IsNullOrEmpty(dbpath) == false) this.db = DbContextFactory.CreateLiteDBContext(dbpath); else this.db = DbContextFactory.CreateLiteDBContext(); }
// Parameter has no matching param tag in the XML comment (but other parameters do) /// <summary> /// Wraps a database operation in a try/catch block /// </summary> /// <typeparam name="T">The Type which determines the database collection name</typeparam> /// <typeparam name="U">The type of result expected from the operation</typeparam> /// <param name="path">The database path and filename</param> /// <param name="f">The operation to invoke</param> /// <returns>A CallResult with the result of the operation</returns> #pragma warning disable CS1573 public static CallResult <U> LiteDbAction <T, U>(string path, Func <LiteDatabase, LiteCollection <T>, U> f, [CallerMemberName] string callerMemberName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = 0) where T : new() #pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) { //return LiteDbAction<T, U>(path, database => //{ // return f.Invoke(database, GetCollection<T>(database)); //}, callerMemberName, callerFilePath, callerLineNumber); var result = new CallResult <U>(); try { if (f == null) { throw new ArgumentNullException("LiteDbAction: Parameter 'f' cannot be null"); } using (var db = new LiteDB.LiteDatabase(path)) { var collection = GetCollection <T>(db); result.Result = f.Invoke(db, collection); result.Success = true; } } catch (LiteException e) { result.Exception = e; Log.e(new Exception(string.Format("LiteException: ErrorCode={0}, Message={1}", e.ErrorCode, e.Message), e)); } catch (Exception e) { result.Exception = e; Log.e(new Exception(string.Format("Caller:{0}, Line:{1}, File:{2}", callerMemberName, callerLineNumber, callerFilePath), e)); } return(result); }
public void FileStorage_InsertDelete() { // create a dump file File.WriteAllText("Core.dll", "FileCoreContent"); using (var db = new LiteDatabase(DB.Path())) { db.FileStorage.Upload("Core.dll", "Core.dll"); var exists = db.FileStorage.Exists("Core.dll"); Assert.Equal(true, exists); var deleted = db.FileStorage.Delete("Core.dll"); Assert.Equal(true, deleted); var deleted2 = db.FileStorage.Delete("Core.dll"); Assert.Equal(false, deleted2); } File.Delete("Core.dll"); }
public void FileStorage_Concurrency() { using (var db = new LiteDatabase(fdb)) { } var t1 = new Thread(new ThreadStart(TaskInsert)); var t2 = new Thread(new ThreadStart(TaskInsert)); var t3 = new Thread(new ThreadStart(TaskInsert)); var t4 = new Thread(new ThreadStart(TaskInsert)); var t5 = new Thread(new ThreadStart(TaskInsert)); var t6 = new Thread(new ThreadStart(TaskInsert)); t1.Start(); t2.Start(); t3.Start(); t4.Start(); t5.Start(); t6.Start(); t1.Join(); t2.Join(); t3.Join(); t4.Join(); t5.Join(); t6.Join(); }
public override void Initialize() { DataBase = new LiteDatabase(ConnectionString); LCol = DataBase.GetCollection <CacheItem>(CollectionName); LCol.EnsureIndex(c => c.Key); //CurrentCollectionCount = LCol.Count(); }
public void Include_Test() { using (var db = new LiteDatabase(DB.Path())) { var customers = db.GetCollection<Customer>("customers"); var orders = db.GetCollection<Order>("orders"); var customer = new Customer { Name = "John Doe" }; // insert and set customer.Id customers.Insert(customer); var order = new Order { Customer = new DbRef<Customer>(customers, customer.Id) }; orders.Insert(order); var query = orders .Include((x) => x.Customer.Fetch(db)) .FindAll() .Select(x => new { CustomerName = x.Customer.Item.Name }) .FirstOrDefault(); Assert.Equal(customer.Name, query.CustomerName); } }
public async Task Sync() { var github = new GitHubClient(new ProductHeaderValue("Jackett")); var releases = await github.Release.GetAll("zone117x", "Jackett"); if (releases.Count > 0) { using (var db = new LiteDatabase(GetDBPath())) { var releaseCollection = db.GetCollection<Release>("Releases"); releaseCollection.Drop(); releaseCollection.EnsureIndex(x => x.When); foreach (var release in releases) { releaseCollection.Insert(new Release() { When = release.PublishedAt.Value.DateTime, Description = release.Body, Title = release.Name, Url = release.HtmlUrl, Version = release.TagName }); } } } }
public static List<Release> GetReleases() { using (var db = new LiteDatabase(GetDBPath())) { var releaseCollection = db.GetCollection<Release>("Releases"); return releaseCollection.FindAll().OrderByDescending(x => x.When).ToList(); } }
protected virtual LiteDB.LiteDatabase GetDatabase(bool refersh = false) { if (this.db == null || refersh) { this.db = new LiteDB.LiteDatabase(connectionString); } return(this.db); }
public static LiteDatabase OpenOrCreateDefault() { if (_dbInstance == null) { _dbInstance = new LiteDatabase("betago_srv.lidb"); } return _dbInstance; }
private LiteStorage GetLiteFileStorage() { using (var db = new LiteDB.LiteDatabase(_connectionString)) { var q = db.FileStorage; return(q); } }
// TODO: Clear out data after it has gone stale // TODO: Allow for multiple matches to be stored simultaneously public static CricinfoMatchDetails GetLastStore() { using (var db = new LiteDatabase(@"C:\Temp\Cricket.db")) { var col = db.GetCollection<CricinfoMatchDetails>("score"); return col.FindAll().OrderByDescending(x => x.RetrievedDate).FirstOrDefault(); } }
private void button2_Click(object sender, EventArgs e) { LiteDatabase db = new LiteDatabase(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "app.bin")); var x = db.GetCollection<Histories>(nameof(Histories)); x.Delete(Query.All()); comboBox1.Items.Clear(); this.buttonLoad.Enabled = false; }
public IEnumerable<TorrentMovie> GetAll() { using (var db = new LiteDatabase(PCinemaDbName)) { var movies = db.GetCollection<TorrentMovie>(TorrentMovieCollectionName).Find(Query.GTE("LastUpdated", DateTime.Now.AddDays(-1))); return movies.ToList(); } }
public static bool RemoveUniqueUser(ulong id) { using (var db = new LiteDatabase(ConstData.path)) { var uniqueUsers = db.GetCollection<UniqueUser>("uniqueUsers"); uniqueUsers.Delete(Query.EQ("userID", id)); return true; } }
public bool Delete(int laneId) { using (var database = new LiteDB.LiteDatabase(ConnectionString)) { var lanes = database.GetCollection <LaneDocument>(); var result = lanes.Delete(laneId); return(result); } }
private LiteCollection <T> GetLiteCollection <T>() { using (var db = new LiteDB.LiteDatabase(_connectionString)) { var q = db.GetCollection <T>(_tableName); return(q); } }
public static string GetServerPrefix(ulong serverID) { using (var db = new LiteDatabase(ConstData.path)) { var servers = db.GetCollection<ServerSetting>("servers"); var customServerSetting = servers.FindOne(Query.EQ("serverID", serverID)); return (customServerSetting != null && customServerSetting.customPrefix != null) ? customServerSetting.customPrefix : "TARS"; } }
public LoggingMiddleware(RequestDelegate next, LiteDB.LiteDatabase db) { _db = db; if (next == null) { throw new ArgumentNullException(nameof(next)); } _next = next; }
public static bool IsUniqueUser(ulong id) { using (var db = new LiteDatabase(ConstData.path)) { var uniqueUsers = db.GetCollection<UniqueUser>("uniqueUsers"); var resultUser = uniqueUsers.FindOne(Query.EQ("userID", id)); return resultUser != null ? true : false; } }
public Task ClearAsync() { using (var db = new LiteDB.LiteDatabase(dbPath)) if (db.CollectionExists(DataStoreCollectionName)) { db.DropCollection(DataStoreCollectionName); } return(CompletedTask); }
public static bool AddUniqueUser(string name, ulong id) { using (var db = new LiteDatabase(ConstData.path)) { var uniqueUsers = db.GetCollection<UniqueUser>("uniqueUsers"); var uniqueUser = new UniqueUser { userName = name, userID = id }; uniqueUsers.Insert(uniqueUser); return true; } }
public ImdbData GetById(int id) { using (var db = new LiteDatabase(PCinemaDbName)) { var movie = db.GetCollection<ImdbData>(ImdbMovieCollectionName) .Find(x => x.Id == id && x.LastUpdated >= DateTime.Now.AddDays(-7)) .FirstOrDefault(); return movie; } }
public LiteDBBackedTest() { var dbDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory); _dbConfig = new Config { DbPath = Path.Combine(dbDir, "blog.db") }; using (var _db = new LiteDatabase(_dbConfig.DbPath)) { var authorCol = _db.GetCollection<Author>(DBTableNames.Authors); authorCol.EnsureIndex<string>(x => x.Id); } }
//private readonly Lazy<IDictionariesRepository> _dictionariesRepository; protected BaseDocumentDatabase(string dbPath) { if (String.IsNullOrWhiteSpace(dbPath)) throw new ArgumentException("Argument is null or whitespace", nameof(dbPath)); _dbPath = dbPath; _db = new LiteDatabase(_dbPath); //_dictionariesRepository = new Lazy<IDictionariesRepository>(() => new LiteDictionariesRepository(_db)); }
public Archage_AH_DataCollector() { InitializeComponent(); path = Directory.GetCurrentDirectory() + "\\ItemDB.db"; DB = new LiteDatabase(@path); inventoryPath = Directory.GetCurrentDirectory() + "\\InventoryDB.db"; InventoryDB = new LiteDatabase(@inventoryPath); conversionPath = Directory.GetCurrentDirectory() + "\\ConversionDB.db"; ConversionDB = new LiteDatabase(@conversionPath); AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); RecipesPath = @Directory.GetCurrentDirectory() + "\\Recipe.json"; if (File.Exists(RecipesPath)) { string Recipes = System.IO.File.ReadAllText(RecipesPath); RecipeItemsTop = new List<RecipeItem>(); RecipeItemsTop = JsonConvert.DeserializeObject<List<RecipeItem>>(Recipes); } else { RecipeItemsTop = new List<RecipeItem>(); } AuctionPath = @Directory.GetCurrentDirectory() + "\\AuctionData.json"; if (File.Exists(AuctionPath)) { string Auctions = System.IO.File.ReadAllText(AuctionPath); AuctionItemsTop = JsonConvert.DeserializeObject<List<AuctionItem>>(Auctions); } else { AuctionItemsTop = new List<AuctionItem>(); } InventoryPath = @Directory.GetCurrentDirectory() + "\\Inventory.json"; if (File.Exists(InventoryPath)) { string Inventory = System.IO.File.ReadAllText(InventoryPath); InventoryItemsTop = JsonConvert.DeserializeObject<List<InventoryItem>>(Inventory); } else { InventoryItemsTop = new List<InventoryItem>(); } ConversionPath = @Directory.GetCurrentDirectory() + "\\Conversion.json"; if (File.Exists(ConversionPath)) { string Conversion = System.IO.File.ReadAllText(ConversionPath); ConversionItemsTop = JsonConvert.DeserializeObject<List<Conversion>>(Conversion); } else { ConversionItemsTop = new List<Conversion>(); } }
public DbRepo(string dp, ILogger logger, IJsonSerializer json = null) { DataPath = dp; //LitePlatform.Initialize(new LitePlatformFullDotNet()); var data = Path.Combine(DataPath, dataName); _logger = logger; _json = json; if (File.Exists(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.ldb"))) { File.Delete(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.ldb")); } if (File.Exists(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.2.ldb"))) { File.Delete(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.2.ldb")); } if (File.Exists(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.3.ldb"))) { File.Delete(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.3.ldb")); } if (File.Exists(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.31.ldb"))) { File.Delete(Path.Combine(DataPath, "Emby.Kodi.SyncQueue.1.31.ldb")); } if (!Directory.Exists(DataPath)) { Directory.CreateDirectory(DataPath); } if (!File.Exists(data)) { } if (DB == null) { DB = new LiteDatabase(data); } folders = DB.GetCollection<FolderRec>("Folders"); items = DB.GetCollection<ItemRec>("Items"); userinfos = DB.GetCollection<UserInfoRec>("UserInfos"); folders.EnsureIndex(x => x.ItemId); folders.EnsureIndex(x => x.UserId); folders.EnsureIndex(x => x.LastModified); folders.EnsureIndex(x => x.Status); folders.EnsureIndex(x => x.MediaType); items.EnsureIndex(x => x.ItemId); items.EnsureIndex(x => x.LastModified); items.EnsureIndex(x => x.Status); items.EnsureIndex(x => x.MediaType); userinfos.EnsureIndex(x => x.ItemId); userinfos.EnsureIndex(x => x.UserId); userinfos.EnsureIndex(x => x.LastModified); userinfos.EnsureIndex(x => x.MediaType); }
private static void DbMigration() { using (var db = new LiteDatabase(DirectoryHelper.GetDataDirectory() + Settings.Default.LiteDbFileName)) { if (!db.CollectionExists("screenings")) return; var col = db.GetCollection("screenings"); IEnumerable<BsonDocument> items = col.FindAll().ToList(); foreach (var item in items) { var isNeedUpdate = false; var formations = item["FocalFormations"].AsArray; foreach (var form in formations) { var size = form.AsDocument["Size"]; if (!size.IsString) { form.AsDocument.Set("Size", size.AsString); isNeedUpdate = true; } if (size.IsNull) { form.AsDocument.Set("Size", string.Empty); isNeedUpdate = true; } var cdk = form.AsDocument["CDK"]; if (cdk.AsString == "Avascular") { form.AsDocument.Set("CDK", "None"); isNeedUpdate = true; } } var cysts = item["Cysts"].AsArray; if (cysts != null) { foreach (var cyst in cysts) { var cdk = cyst.AsDocument["CDK"]; if (cdk.AsString == "Avascular") { cyst.AsDocument.Set("CDK", "None"); isNeedUpdate = true; } } } if (isNeedUpdate) { col.Update(item); } } } }
internal LiteFileInfo(LiteDatabase db, BsonDocument doc) { _db = db; this.Id = doc["_id"].AsString; this.Filename = doc["filename"].AsString; this.MimeType = doc["mimeType"].AsString; this.Length = doc["length"].AsInt64; this.UploadDate = doc["uploadDate"].AsDateTime; this.Metadata = doc["metadata"].AsDocument; }
public static void StoreNew(CricinfoMatchDetails current) { using (var db = new LiteDatabase(@"C:\Temp\Cricket.db")) { // Get customer collection var col = db.GetCollection<CricinfoMatchDetails>("score"); // Insert new customer document (Id will be auto-incremented) col.Insert(current); } }
public void Bulk_Test() { using (var db = new LiteDatabase(new MemoryStream())) { var col = db.GetCollection("b"); col.Insert(GetDocs()); Assert.AreEqual(220, col.Count()); } }
public void Update(int targetId, string laneLabel, int projectId) { using (var database = new LiteDB.LiteDatabase(ConnectionString)) { var lanes = database.GetCollection <LaneDocument>(); lanes.Update(targetId, new LaneDocument() { Title = laneLabel, ProjectId = projectId }); } }
public List <LaneDocument> GetAll(int projectId) { var laneDocuments = new List <LaneDocument>(); using (var database = new LiteDB.LiteDatabase(ConnectionString)) { var lanes = database.GetCollection <LaneDocument>(); laneDocuments = lanes.Find(Query.EQ("ProjectId", projectId)).ToList(); } return(laneDocuments); }
public List <ProjectDocument> GetAll() { List <ProjectDocument> results; using (var database = new LiteDB.LiteDatabase(ConnectionString)) { var projects = database.GetCollection <ProjectDocument>(); results = projects.FindAll().ToList(); } return(results); }
public bool Delete(int cardId) { bool result; using (var database = new LiteDB.LiteDatabase(ConnectionString)) { var cards = database.GetCollection <CardDocument>(); cards.EnsureIndex("Id"); result = cards.Delete(cardId); } return(result); }
public List <CardDocument> Get(int laneId) { var cardDocuments = new List <CardDocument>(); using (var database = new LiteDB.LiteDatabase(ConnectionString)) { var cards = database.GetCollection <CardDocument>(); cards.EnsureIndex("ParentLaneId"); cardDocuments = cards.Find(x => x.ParentLaneId == laneId).ToList(); } return(cardDocuments); }
public ProjectDocument Get(int projectId) { ProjectDocument result; using (var database = new LiteDB.LiteDatabase(ConnectionString)) { var projects = database.GetCollection <ProjectDocument>(); projects.EnsureIndex("Id"); result = projects.Find(x => x.Id == projectId).FirstOrDefault(); } return(result); }
// Returns a list of customers from the DB. // This is the main DB functionality public static IEnumerable <Customer> ToList(CustomerColumn orderBy, bool ascending, string filter = "") { //Open DB using (var db = new LiteDB.LiteDatabase(AppDomain.CurrentDomain.BaseDirectory + @"\uomi.db")) { // Retrieve 'customers' collection var col = db.GetCollection <Customer>("customers"); // Declare a return variable IEnumerable <Customer> retCustomers; //Check if a filter was provided if (string.IsNullOrEmpty(filter)) { //No filter, fetch everything retCustomers = col.FindAll(); } else { //Apply filter in name or address or phonenumber retCustomers = col.Find(x => true).Where(x => CultureInfo.CurrentCulture.CompareInfo.IndexOf(x.Name, filter, CompareOptions.IgnoreCase) >= 0 || CultureInfo.CurrentCulture.CompareInfo.IndexOf(x.Address, filter, CompareOptions.IgnoreCase) >= 0 || CultureInfo.CurrentCulture.CompareInfo.IndexOf(x.Phonenumber, filter, CompareOptions.IgnoreCase) >= 0); } //Order the output switch (orderBy) { case CustomerColumn.Id: retCustomers = ascending ? retCustomers.OrderBy(x => x.Id) : retCustomers.OrderByDescending(x => x.Id); break; case CustomerColumn.Name: retCustomers = ascending ? retCustomers.OrderBy(x => x.Name) : retCustomers.OrderByDescending(x => x.Name); break; case CustomerColumn.Address: retCustomers = ascending ? retCustomers.OrderBy(x => x.Address) : retCustomers.OrderByDescending(x => x.Address); break; case CustomerColumn.Phonenumber: retCustomers = ascending ? retCustomers.OrderBy(x => x.Phonenumber) : retCustomers.OrderByDescending(x => x.Phonenumber); break; case CustomerColumn.Balance: retCustomers = ascending ? retCustomers.OrderBy(x => x.Balance) : retCustomers.OrderByDescending(x => x.Balance); break; } return(retCustomers); } }
/// <summary> /// Find and return the first item found matching the criteria /// </summary> /// <typeparam name="T">The Type which determines the database collection name</typeparam> /// <param name="path">The database path and filename</param> /// <param name="match">A matching function used to find matches</param> /// <returns>The first item found matching the criteria. Null if no matches were found.</returns> public static CallResult <T> FindOne <T>(string path, System.Linq.Expressions.Expression <Func <T, bool> > match) where T : new() { using (var db = new LiteDB.LiteDatabase(path)) { var collection = GetCollection <T>(db); var result = collection.Find(match).FirstOrDefault(); return(new CallResult <T>(result != null, result)); } //return LiteDbAction<T, T>(path, (database, collection) => //{ // return collection.FindOne(f => match.Invoke(f)); //}); }
public int Insert(string laneLabel, int projectId) { int id; using (var database = new LiteDB.LiteDatabase(ConnectionString)) { var lanes = database.GetCollection <LaneDocument>(); id = lanes.Insert(new LaneDocument() { Title = laneLabel, ProjectId = projectId }); } return(id); }
public int New(string projectName) { int result = 0; using (var database = new LiteDB.LiteDatabase(ConnectionString)) { var projects = database.GetCollection <ProjectDocument>(); result = projects.Insert(new ProjectDocument() { Name = projectName }); } return(result); }
//Deletes customer instance from the database public bool DeleteFromDatabase() { try { using (var db = new LiteDB.LiteDatabase(AppDomain.CurrentDomain.BaseDirectory + @"\uomi.db")) { var col = db.GetCollection <Customer>("customers"); col.Delete(this.Id); } return(true); } catch { return(false); } }
private void update() { reception_Frm = new Reception_frm(this); reception_Frm.clear(); reception_Frm.btnOk.Text = "Update"; using (var db = new LiteDB.LiteDatabase(@"database.db")) { var coll = db.GetCollection <Reserve>("Reserves"); var row = coll.FindById((int)dgReception.Rows[rowSelected].Cells[0].Value); reception_Frm.dtpReserveDate.Value = row.reserveDate; reception_Frm.tbName.Text = row.name; reception_Frm.tbMobile.Text = row.mobile; reception_Frm.cbJob.Text = row.job; reception_Frm.cbDept.Text = row.dept; } reception_Frm.Show(); }
public Task DeleteAsync <T>(string key) { if (string.IsNullOrEmpty(key)) { throw new ArgumentException("Key MUST have a value"); } using (var db = new LiteDB.LiteDatabase(dbPath)) { var collection = db.GetCollection <LiteDbDataStoreItem>(DataStoreCollectionName); var idKey = GenerateStoredKey(key, typeof(T)); collection.Delete(item => item.Id == idKey); } return(CompletedTask); }
public int Insert(int parentLaneId, string cardName, string cardDescription, int cardPoints, CardTypes parsedCardType) { int id; using (var database = new LiteDB.LiteDatabase(ConnectionString)) { var cards = database.GetCollection <CardDocument>(); id = cards.Insert(new CardDocument() { ParentLaneId = parentLaneId, CardName = cardName, CardDescription = cardDescription, CardPoints = cardPoints }); } return(id); }
/// <summary> /// Deletes a Bitmap from the database /// </summary> /// <param name="path">The database path and filename</param> /// <param name="id">The unique id identifying the bitmap</param> public static CallResult DeleteBitmap(this string path, string id) { var result = new CallResult(); try { using (var db = new LiteDB.LiteDatabase(path))// GetDatabase(path)) { db.FileStorage.Delete(id); result.Success = true; } } catch (Exception e) { result.Exception = e; Log.e(e); } return(result); }
/// <summary> /// Store a file to the database /// </summary> /// <param name="path">The database path and filename</param> /// <param name="id">The unique id for the filename. Can be the path and filename, or some other unique value.</param> /// <param name="filename">The path and name of the file to save</param> /// <returns>True if the data is saved, otherwise False</returns> public static CallResult Upload(this string path, string id, string filename) { var result = new CallResult(); using (var db = new LiteDB.LiteDatabase(path)) { try { db.FileStorage.Upload(id, filename); result.Success = true; } catch (Exception e) { result.Exception = e; Log.e(e); } } return(result); }
private void loadReserves() { var list = new List <Reserve>(); using (var db = new LiteDB.LiteDatabase(@"database.db")) { var col = db.GetCollection <Reserve>("Reserves"); var result = col.FindAll().Select(x => new { Code = x.ID, Name = x.name, Mobile = x.mobile, Job = x.job, Department = x.dept, Date = x.reserveDate.ToString("d/MM/yyyy") }); dgReception.DataSource = result.ToList(); } }
/// <summary> /// Retrieves a file from the database /// </summary> /// <param name="path">The database path and filename</param> /// <param name="id">The unique id used to identify the data</param> /// <param name="outputFilename">The path and filename to use when saving the file</param> /// <param name="overwrite">If true, any existing file will be overwritten</param> /// <returns>True if the file was retrieved and written to the file system. Otherwise False.</returns> public static CallResult Download(this string path, string id, string outputFilename, bool overwrite = true) { var result = new CallResult(); try { using (var db = new LiteDB.LiteDatabase(path)) { var li = db.FileStorage.FindById(id); li.SaveAs(outputFilename, overwrite); result.Success = true; } } catch (Exception e) { result.Exception = e; Log.e(e); } return(result); }