public async Task LimparBaseDeDados() { using var db = new LiteDatabase(Startup._database); var cols = db.GetCollectionNames(); foreach (var item in db.GetCollectionNames()) { var col = db.GetCollection(item); await Task.FromResult(col.DeleteAll()); } }
private void RefreshCollections() { lb_Collections.Items.Clear(); foreach (var collection in _db.GetCollectionNames()) { if (!collection.Equals("_chunks") && !collection.Equals("_files")) { lb_Collections.Items.Add(collection); } } lb_Collections.Items.Add("[FILESTORAGE]"); }
public bool CollectionsExists() { var collectionNames = new List <string> { UserAuthCol, UserOAuthProviderCol }; var collections = _liteDatabase.GetCollectionNames(); return(collections.Any(document => collectionNames.Contains(document))); }
//Imports database from contractor app private void ImportButton_Click(object sender, EventArgs e) { //Opens a file explorer to grab the file OpenFileDialog fdlg = new OpenFileDialog(); fdlg.Title = "Roborts File Explorer"; fdlg.InitialDirectory = @"c:\"; fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"; fdlg.FilterIndex = 2; fdlg.RestoreDirectory = true; if (fdlg.ShowDialog() == DialogResult.OK) { try { //Deletes old database to get ready for a new one using (var db = new LiteDatabase(@"IQIncorporated.db")) { string[] tableNames = new string[db.GetCollectionNames().Count()]; for (int i = 0; i < db.GetCollectionNames().Count(); i++) { tableNames[i] = db.GetCollectionNames().ElementAt(i); } foreach (var name in tableNames) { System.Diagnostics.Debug.WriteLine(name); db.DropCollection(name); } } // import data FROM JSON using (var db = new LiteDatabase(@"IQIncorporated.db")) { var data = JsonSerializer.Deserialize(File.ReadAllText(fdlg.FileName)).AsDocument; foreach (var name in data.Keys) { db.GetCollection(name).Insert(data[name].AsArray.Select(x => x.AsDocument)); } } MessageBox.Show("Imported Successfully"); } catch (Exception excep) { MessageBox.Show("Invalid file, please try again "); } } }
private void Info_Click(object sender, EventArgs e) { var infos = new Dictionary <string, BsonValue> { { "DatabaseVersion", new BsonValue((int)_db.DbVersion) }, { "FileName", new BsonValue(_fileName) }, { "Encrypted", new BsonValue(_encrypted) } }; foreach (var collectionName in _db.GetCollectionNames()) { infos.Add($"[{collectionName}] Stats", _db.Run($"db.{collectionName}.stats")); } new DocumentViewForm(new BsonDocument(infos)).ShowDialog(); }
public MainWindow() { InitializeComponent(); var db = new LiteDatabase(new ConnectionString { Filename = "Test.MORISA-SETTING", Collation = new Collation(1033, System.Globalization.CompareOptions.IgnoreCase), }); var id = "{10F9CA2E-BCE3-4A48-93F6-A138D749A74C}"; var names = db.GetCollectionNames(); foreach (var name in names) { Debug.WriteLine(name); } // // remove this line and run again db.FileStorage.Upload(id, @"ico_512x512.ico"); var stream = db.FileStorage.OpenRead(id); var bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = stream; bi.EndInit(); PART_Image.Source = bi; }
public void DropDB() { foreach (String s in db.GetCollectionNames()) { db.DropCollection(s); } }
public void SeedDB() { using (var db = new LiteDatabase(Constants.DB_NAME)) { //clean up IEnumerable <string> collectionNames = db.GetCollectionNames().ToList(); foreach (string collectionName in collectionNames) { db.DropCollection(collectionName); } } //setup test data Employee nextMgr = new Employee() { Id = Guid.Empty }; for (int i = 0; i < 99; i++) { FakeName fname = GetAName(); DateTime onboardDate = DateTime.Now.AddMonths(random.Next(-100, -12)); DateTime recentPerfReviewDate = new DateTime(DateTime.Now.Year - 1, onboardDate.Month, 1); Employee theNextMgr = EmployeeFactory.CreateEmployee(fname.FirstName, fname.LastName, (Gender)GetValue(genders), fname.Email, nextMgr, (Title)GetValue(titles), (Level)GetValue(levels), random.Next(50000, 200000), random.Next(0, 10000), onboardDate); HistoryFactory.CreateHistory(theNextMgr, nextMgr, (Title)GetValue(titles), (Level)GetValue(levels), random.Next(50000, 200000), random.Next(0, 10000), ActionType.ANNUAL_PERFORMANCE_REVIEW, recentPerfReviewDate); nextMgr = theNextMgr; } }
public void Dump(TextWriter writer) { var mapper = new BsonMapper().UseCamelCase(); foreach (var name in _db.GetCollectionNames()) { var col = _db.GetCollection(name); var indexes = col.GetIndexes().Where(x => x.Field != "_id"); writer.WriteLine("-- Collection '{0}'", name); foreach (var index in indexes) { writer.WriteLine("db.{0}.ensureIndex {1} {2}", name, index.Field, JsonSerializer.Serialize(mapper.ToDocument <IndexOptions>(index.Options))); } foreach (var doc in col.Find(Query.All())) { writer.WriteLine("db.{0}.insert {1}", name, JsonSerializer.Serialize(doc, false, true)); } } }
// text - The current text entered in the console // index - The index of the terminal cursor within {text} public string[] GetSuggestions(string text, int index) { string cmdpattern = @"^db[.]\w*[.]"; if (text.StartsWith("\\")) { return new string[] { "a", "c", "h", "q", "s" } } ; else if (text.StartsWith("db.") && text.Count(x => x == '.') == 1) { string[] collections; try { using (var db = new LiteDatabase(SharedVariables.connectionString)) { collections = db.GetCollectionNames().ToArray(); } var result = collections.Where(c => c.StartsWith(text.Split('.')[1])).ToArray(); return(result); } catch { return(null); } } else if (Regex.Match(text, cmdpattern).Success) { string[] commands = new string[] { "insert", "bulk", "update", "delete", "ensureIndex", "indexes", "dropIndex", "drop", "rename", "count", "min", "max", "find", "select" }; var result = commands.Where(c => c.StartsWith(text.Split('.')[2])).ToArray(); return(result); } else { return(null); } }
public static void DropAllCollections(this LiteDatabase @this) { foreach (string col in @this.GetCollectionNames()) { @this.DropCollection(col); } }
public void Datafilev1_Test() { // try open a old datafile version to check if message are correct var v1 = Path.GetFullPath(@"..\..\v1.db"); try { using (var db = new LiteDatabase(v1)) { db.GetCollectionNames().ToList(); Assert.Fail("Version 1 must not work"); } } catch (LiteException ex) { if (ex.ErrorCode == LiteException.INVALID_DATABASE || ex.ErrorCode == LiteException.INVALID_DATABASE_VERSION) { // ok } else { Assert.Fail("Invalid exception for old v1 data format"); } } }
public void dbshow() { using (var db = new LiteDatabase(@"MyData.db")) { var names = db.GetCollectionNames(); foreach (var name in names) { var kk = db.GetCollection(name); var kvLst = new List <Tuple <string, object> >(); IEnumerable <BsonDocument> all = kk.FindAll(); foreach (var a in all) { var keys = a.Keys; foreach (var k in keys) { BsonValue v = a[k]; var v2 = v.RawValue; if (v.IsArray) { continue; } kvLst.Add(new Tuple <string, object>(k, v2)); } } collection.Add(name, kvLst); } // var tt = JsonConvert.SerializeObject(dict); } }
public MainForm(string fileName, string password = null, bool upgrade = false) { _encrypted = !string.IsNullOrWhiteSpace(password); _fileName = Path.GetFullPath(fileName); if (upgrade) { if (!LiteEngine.Upgrade(fileName, password, false)) { throw new NotSupportedException("File format do not support upgrade."); } } var args = new List <string> { $"filename=\"{_fileName}\"" }; if (_encrypted) { args.Add($"password=\"{password}\""); } _db = new LiteDatabase(string.Join(";", args)); InitializeComponent(); txt_filename.Text = _fileName + (_encrypted ? " [ENCRYPTED]" : string.Empty); foreach (var collection in _db.GetCollectionNames()) { if (!collection.Equals("_chunks") && !collection.Equals("_files")) { lb_Collections.Items.Add(collection); } } lb_Collections.Items.Add("[FILESTORAGE]"); }
public void Setup() { var collections = _db.GetCollectionNames().ToList(); foreach (var collection in collections) { _db.DropCollection(collection); } var data = new List <BsonDocument> { new BsonDocument { ["_id"] = "language", ["Value"] = "C#" }, new BsonDocument { ["_id"] = "cloud", ["Value"] = "Amazon" }, new BsonDocument { ["_id"] = "sql", ["Value"] = "Postgres" } }; var dataCollection = _db.GetCollection(DataCollectionName); dataCollection.InsertBulk(data); dataCollection.EnsureIndex("_id", true); }
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 IEnumerable <TaskProgress> GetProgress(Guid ticket) { var data = _db.GetCollection <TaskProgress>().FindAll(); var cols = _db.GetCollectionNames(); var progressEvents = _db.GetCollection <TaskProgress>().Find(p => p.TaskId == ticket).ToList(); return(progressEvents); }
public LiteDatabase OpenDatabase() { if (string.IsNullOrEmpty(Path)) { throw new Exception("Database path cannot be empty."); } var dbExists = File.Exists(Path); logger.Info("Opening db " + Path); CloseDatabase(); Database = new LiteDatabase($"Filename={Path};Mode=Exclusive"); // To force litedb to try to open file, should throw exceptuion if something is wrong with db file Database.GetCollectionNames(); if (!dbExists) { Database.Engine.UserVersion = DBVersion; } else { if (Database.Engine.UserVersion > DBVersion) { throw new Exception($"Database version {Database.Engine.UserVersion} is not supported."); } if (GetMigrationRequired(Database)) { throw new Exception("Database must be migrated before opening."); } } GamesCollection = Database.GetCollection <IGame>("games"); PlatformsCollection = Database.GetCollection <Platform>("platforms"); EmulatorsCollection = Database.GetCollection <Emulator>("emulators"); if (!dbExists) { GamesCollection.EnsureIndex(a => a.Id); PlatformsCollection.EnsureIndex(a => a.Id); EmulatorsCollection.EnsureIndex(a => a.Id); // Generate default platforms if (File.Exists(EmulatorDefinition.DefinitionsPath)) { var platforms = EmulatorDefinition.GetDefinitions() .SelectMany(a => a.Profiles.SelectMany(b => b.Platforms)).Distinct() .Select(a => new Platform(a)).ToList(); AddPlatform(platforms); } } DatabaseOpened?.Invoke(this, null); IsOpen = true; return(Database); }
public void ResetDatastore() { var collections = database.GetCollectionNames().ToList(); for (int i = 0; i < collections.Count; i++) { database.DropCollection(collections[i]); } }
public DatabaseViewModel(string fileName) { if (!File.Exists(fileName)) { return; } _db = new LiteDatabase(fileName); CollectionNames = _db.GetCollectionNames(); }
/// <summary> /// Creates a model for an opened database. /// </summary> public DatabaseModel(MainFormModel viewModel, LiteDatabase db, string filePath) { Database = db; FilePath = filePath; Parent = viewModel; Collections = new ObservableCollection <CollectionModel>(Database .GetCollectionNames() .Select(name => new CollectionModel(viewModel, this, name))); }
public void DropCollection() { using (var file = new TempFile()) using (var db = new LiteDatabase(file.Filename)) { db.GetCollectionNames().Should().NotContain("col"); var col = db.GetCollection("col"); col.Insert(new BsonDocument { ["a"] = 1 }); db.GetCollectionNames().Should().Contain("col"); db.DropCollection("col"); db.GetCollectionNames().Should().NotContain("col"); } }
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 void DropCollection() { using (var file = new TempFile()) using (var db = new LiteDatabase(file.Filename)) { Assert.IsFalse(db.GetCollectionNames().Any(x => x == "col")); var col = db.GetCollection("col"); col.Insert(new BsonDocument { ["a"] = 1 }); Assert.IsTrue(db.GetCollectionNames().Any(x => x == "col")); db.DropCollection("col"); Assert.IsFalse(db.GetCollectionNames().Any(x => x == "col")); } }
public ElevatorDbContext(IOptions <AppSettings> setting) { _database = new LiteDatabase(setting.Value.LiteDbConnectionString); Elevators = _database.GetCollection <ElevatorEntity>(Constants.ElevatorDbTables.Elevator); ElevatorLogs = _database.GetCollection <ElevatorLogEntity>(Constants.ElevatorDbTables.ElevatorLog); var count = _database.GetCollectionNames().Count(); if (count == 0) { this.Seed(); } }
public void Before() { var liteDatabase = new LiteDatabase("Filename=ComponentTests.db"); foreach (var collectionName in liteDatabase.GetCollectionNames()) { liteDatabase.DropCollection(collectionName); } _liteDbContext = new LiteDbContext(liteDatabase); _applicationService = new ApplicationService(_liteDbContext); }
public void CheckRequiredCollection() { // Validate if the required database structure is available var alltablesAreAvailable = _db.GetCollectionNames() .Count(n => n == "__FileLocks" || n == "__FileContents" || n == "__FileMetaData") == 3; if (false == alltablesAreAvailable) { throw new ConfigurationErrorsException($"The LiteDbCollections required for the LiteDbDirectory are not available in database"); } }
public static void DropDatabase(string secret) { if (Secret == secret) { using (var db = new LiteDatabase(DatabasePath)) { var collectionNames = db.GetCollectionNames().ToList(); foreach (var collectionName in collectionNames) { db.DropCollection(collectionName); } } } }
private void TestConnString() { try { using (var db = new LiteDatabase(this.connString)) { var collections = db.GetCollectionNames(); } } catch (Exception) { throw new Exception("Invalid database password."); } }
//Exports database ready to be taken in by homebase private void ExportButton_Click(object sender, EventArgs e) { // export data TO JSON using (var db = new LiteDatabase(@"IQIncorporated.db")) { var data = new BsonDocument(); foreach (var name in db.GetCollectionNames()) { data[name] = new BsonArray(db.GetCollection(name).FindAll()); } File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + "ContractorExport.json", JsonSerializer.Serialize(data)); } MessageBox.Show("Exported Successfully"); }
private void UpdateCollections() { Collections = new ObservableCollection <CollectionReference>(LiteDatabase.GetCollectionNames() .Where(a => a != @"_chunks").OrderBy(a => a).Select(a => { if (a == @"_files") { return(new FileCollectionReference(a, this)); } return(new CollectionReference(a, this)); })); OnPropertyChanged(nameof(Collections)); }