public Table ReadRecord() { FileDb _db = new FileDb(); _db.Open(DBFILE, false); // the easy way, using the expression parser // FilterExpressionGroup srchExpGrp = FilterExpressionGroup.Parse //("(FirstName ~= 'andrew' OR FirstName ~= 'nancy') AND LastName = 'Fuller'"); FilterExpressionGroup srchExpGrp = FilterExpressionGroup.Parse ("FirstName = 'Nancy'"); Table table = _db.SelectRecords(srchExpGrp, null, null, false); //// equivalent building it manually //var fname1Exp = new FilterExpression //("FirstName", "andrew", ComparisonOperatorEnum.Equal, MatchTypeEnum.IgnoreCase); //var fname2Exp = new FilterExpression //("FirstName", "nancy", ComparisonOperatorEnum.Equal, MatchTypeEnum.IgnoreCase); //var lnameExp = new FilterExpression //("LastName", "Fuller", ComparisonOperatorEnum.Equal, MatchTypeEnum.UseCase); //var fnamesGrp = new FilterExpressionGroup(); //fnamesGrp.Add(BoolOpEnum.Or, fname1Exp); //fnamesGrp.Add(BoolOpEnum.Or, fname2Exp); //var allNamesGrp = new FilterExpressionGroup(); //allNamesGrp.Add(BoolOpEnum.And, lnameExp); //allNamesGrp.Add(BoolOpEnum.And, fnamesGrp); //// should get the same records //table = _db.SelectRecords(allNamesGrp, null, null, false); _db.Dispose(); return(table); }
internal DbContext() { var config = new FileDbConfiguration() .SetDirectory(Paths.Get().DataDirectory) .DefineCollection<Game>("GameDatabase") .SetPart(x => x.Property(y => y.Id)) .SetPart(x => x.File("definition.xml")) .SetSerializer<GameSerializer>() .Conf() .DefineCollection<Set>("Sets") .OverrideRoot(x => x.Directory("GameDatabase")) .SetPart(x => x.Property(y => y.GameId)) .SetPart(x => x.Directory("Sets")) .SetPart(x => x.Property(y => y.Id)) .SetPart(x => x.File("set.xml")) .SetSerializer<SetSerializer>() .Conf() .DefineCollection<GameScript>("Scripts") .SetSteril() //.OverrideRoot(x => x.Directory("GameDatabase")) //.SetPart(x => x.Property(y => y.GameId)) .Conf() .DefineCollection<ProxyDefinition>("Proxies") .SetSteril() //.OverrideRoot(x => x.Directory("GameDatabase")) //.SetPart(x => x.Property(y=>y.Key)) .Conf() .SetCacheProvider<FullCacheProvider>(); Db = new FileDb(config); }
public frmMain() { InitializeComponent(); _columnSizer = new ListViewColumnSizer(lvResults); _cts = new CancellationTokenSource(); _db = new FileDb(); }
internal DbContext() { var config = new FileDbConfiguration() .SetDirectory(Paths.Get().DataDirectory) .DefineCollection <Game>("GameDatabase") .SetPart(x => x.Property(y => y.Id)) .SetPart(x => x.File("definition.xml")) .SetSerializer <GameSerializer>() .Conf() .DefineCollection <Set>("Sets") .OverrideRoot(x => x.Directory("GameDatabase")) .SetPart(x => x.Property(y => y.GameId)) .SetPart(x => x.Directory("Sets")) .SetPart(x => x.Property(y => y.Id)) .SetPart(x => x.File("set.xml")) .SetSerializer <SetSerializer>() .Conf() .DefineCollection <GameScript>("Scripts") .SetSteril() //.OverrideRoot(x => x.Directory("GameDatabase")) //.SetPart(x => x.Property(y => y.GameId)) .Conf() .DefineCollection <ProxyDefinition>("Proxies") .SetSteril() //.OverrideRoot(x => x.Directory("GameDatabase")) //.SetPart(x => x.Property(y=>y.Key)) .Conf() .SetCacheProvider <FullCacheProvider>(); Db = new FileDb(config); }
internal void CreateFieldNodes(FileDb fileDb, TreeNode dbNode) { dbNode.Nodes.Clear(); foreach (Field field in fileDb.Fields) { var sb = new StringBuilder(100); sb.Append(field.Name); sb.Append(" ["); sb.Append(field.DataType.ToString()); if (field.IsPrimaryKey) { sb.Append(' '); sb.Append("PK"); } if (field.IsAutoInc) { sb.Append(' '); sb.Append("AutoInc"); } if (field.IsArray) { sb.Append(' '); sb.Append("Array"); } sb.Append(']'); TreeNode fieldNode = dbNode.Nodes.Add(null, sb.ToString(), Img_Field, Img_Field); fieldNode.Tag = new NodeInfo(NodeType.Field, field.Name); fieldNode.ContextMenuStrip = MainFrm.TheAppWnd.CtxMnuField; } }
internal void CloseAll() { foreach (TreeNode node in _rootNode.Nodes) { NodeInfo nodeInfo = node.Tag as NodeInfo; FileDb fileDb = nodeInfo.Tag as FileDb; fileDb.Close(); } }
public void SaveTileAsfdb() { if (ImageBytes == null) { return; } FileDb.Set(FdbKey, ImageBytes); }
protected void btnUpload_Click(object sender, EventArgs e) { //Files is folder Name if (Page.IsValid) { Guid guid = Guid.NewGuid(); fuSample.SaveAs(Server.MapPath("~") + "/DataDirectory/" + guid + "_" + fuSample.FileName); lblMessage.Text = "File Successfully Uploaded"; lblMessage.ForeColor = System.Drawing.Color.FromArgb(54, 204, 43); var context = new FileDb(); // Uv db c'est la classe qui correspond à la table en bd File file = new File(fuSample.FileName, Server.MapPath("~") + "/DataDirectory/" + guid + "_" + fuSample.FileName, id, fileType); // On créé une nouvelle UV lblMessage.Text = ""; context.Files.Add(file); // On l'ajoute à la liste d'uv de UVDB try { context.SaveChanges(); // On sauvegarde les changements } catch (DbEntityValidationException ex) { foreach (DbEntityValidationResult item in ex.EntityValidationErrors) { // Get entry DbEntityEntry entry = item.Entry; string entityTypeName = entry.Entity.GetType().Name; // Display or log error messages foreach (DbValidationError subItem in item.ValidationErrors) { string message = string.Format("Error '{0}' occurred in {1} at {2}", subItem.ErrorMessage, entityTypeName, subItem.PropertyName); System.Diagnostics.Debug.WriteLine(message); } } } Response.Redirect(Request.RawUrl); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* ATTENTION : */ /* */ /* POUR QUE LES CHANGEMENTS SOIENT PRIS EN COMPTE : */ /* Il faut que le fichier LO54_DB.mdf du dossier "App_Data" */ /* ait dans la propriété : Copier dans le répertoire de sortie ----> Copier si plus récent */ /* */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ } }
private void showFileList() { var context = new FileDb(); foreach (File f in context.Files) { if (f.idUv == cUV.IdUv && f.fileType == FileType.UV) { showFile(f); } } }
private void showFileList() { var context = new FileDb(); foreach (File f in context.Files) { if (f.idUv == cProject.IdProject && f.fileType == FileType.Project) { showFile(f); } } }
public PageProcessor(int pageIndex, TargetRecord jobInfo, PageLoader pageLoader, FileDb db, MaxiPageMgr maxiPageMgr, Speaker speaker) { this.speaker = speaker; this.maxiPageMgr = maxiPageMgr; this.db = db; this.pageLoader = pageLoader; this.pageIndex = pageIndex; this.jobInfo = jobInfo; }
private int PostData(Book book, FileDb booksDb) { if (booksDb.IsOpen) { booksDb.Open("Books.fdb", false); var record = new FieldValues(); record.Add("AuthorsName", book.AuthorsName); record.Add("Mvp", book.Mvp); record.Add("Title", book.Title); return(booksDb.AddRecord(record)); } return(0); }
private void Initialize() { if (this.isInitialize) return; this.db = this.dbEngine.LoadFileDB(); this.container.RegisterInstance<FileDb>(db); this.timer = new Timer(this.db.TimerInterval); this.timer.Elapsed += new ElapsedEventHandler(TimerElapsedHandler); this.isInitialize = true; if(db.WebProxy.IsEnablded) Console.WriteLine("Web Proxy :" + db.WebProxy.ProxyServer); }
public void Clear_Test_ReturnsEmptyDbSetGivenPopulatedMetadataFileDbSet() { // with moq FileDb fileContext = new FileDb { MetadataFiles = GetQueryableMockDbSet( new MetadataFile(@"C:\Users\Ashie\Desktop\The Adventure.mp3"), new MetadataFile(@"C:\Users\Ashie\Desktop\Going Away to College.mp3")) }; Assert.IsTrue(fileContext.MetadataFiles.Count() > 0); fileContext.MetadataFiles.Clear(); Assert.IsTrue(fileContext.MetadataFiles.Count() == 0); }
internal void OpenDatabase(FileDb fileDb) { string dbFile = fileDb.DbFileName; string sDatabaseName = Path.GetFileName(dbFile); //Path.GetDirectoryName( dbFile ); TreeNode dbNode = _rootNode.Nodes.Add(null, sDatabaseName, Img_Db, Img_Db); dbNode.Tag = new NodeInfo(NodeType.Database, fileDb); dbNode.ContextMenuStrip = MainFrm.TheAppWnd.CtxMnuDatabase; _rootNode.Expand(); CreateFieldNodes(fileDb, dbNode); DbTree.SelectedNode = dbNode; //dbNode.Expand(); }
public int DeleteRecord() { FileDb _db = new FileDb(); _db.Open(DBFILE, false); // the easy way, using the expression parser // FilterExpressionGroup srchExpGrp = FilterExpressionGroup.Parse //("(FirstName ~= 'andrew' OR FirstName ~= 'nancy') AND LastName = 'Fuller'"); FilterExpressionGroup srchExpGrp = FilterExpressionGroup.Parse ("FirstName = 'Nancy'"); var ret = _db.DeleteRecords(srchExpGrp); _db.Dispose(); return(ret); }
public void CreateDb() { FileDb _db = new FileDb(); Field field; var fields = new List <Field>(20); field = new Field("ID", DataTypeEnum.Int32); field.AutoIncStart = 0; field.IsPrimaryKey = true; fields.Add(field); field = new Field("FirstName", DataTypeEnum.String); fields.Add(field); field = new Field("LastName", DataTypeEnum.String); fields.Add(field); field = new Field("BirthDate", DataTypeEnum.DateTime); fields.Add(field); field = new Field("IsCitizen", DataTypeEnum.Bool); fields.Add(field); field = new Field("DoubleField", DataTypeEnum.Double); fields.Add(field); field = new Field("ByteField", DataTypeEnum.Byte); fields.Add(field); // array types field = new Field("StringArrayField", DataTypeEnum.String); field.IsArray = true; fields.Add(field); field = new Field("ByteArrayField", DataTypeEnum.Byte); field.IsArray = true; fields.Add(field); field = new Field("IntArrayField", DataTypeEnum.Int32); field.IsArray = true; fields.Add(field); field = new Field("DoubleArrayField", DataTypeEnum.Double); field.IsArray = true; fields.Add(field); field = new Field("DateTimeArrayField", DataTypeEnum.DateTime); field.IsArray = true; fields.Add(field); field = new Field("BoolArrayField", DataTypeEnum.Bool); field.IsArray = true; fields.Add(field); _db.Create(DBFILE, fields.ToArray()); _db.Dispose(); }
public void CreateDb() { FileDb _db = new FileDb(); Field field; var fields = new List<Field>(20); field = new Field("ID", DataTypeEnum.Int32); field.AutoIncStart = 0; field.IsPrimaryKey = true; fields.Add(field); field = new Field("FirstName", DataTypeEnum.String); fields.Add(field); field = new Field("LastName", DataTypeEnum.String); fields.Add(field); field = new Field("BirthDate", DataTypeEnum.DateTime); fields.Add(field); field = new Field("IsCitizen", DataTypeEnum.Bool); fields.Add(field); field = new Field("DoubleField", DataTypeEnum.Double); fields.Add(field); field = new Field("ByteField", DataTypeEnum.Byte); fields.Add(field); // array types field = new Field("StringArrayField", DataTypeEnum.String); field.IsArray = true; fields.Add(field); field = new Field("ByteArrayField", DataTypeEnum.Byte); field.IsArray = true; fields.Add(field); field = new Field("IntArrayField", DataTypeEnum.Int32); field.IsArray = true; fields.Add(field); field = new Field("DoubleArrayField", DataTypeEnum.Double); field.IsArray = true; fields.Add(field); field = new Field("DateTimeArrayField", DataTypeEnum.DateTime); field.IsArray = true; fields.Add(field); field = new Field("BoolArrayField", DataTypeEnum.Bool); field.IsArray = true; fields.Add(field); _db.Create(DBFILE, fields.ToArray()); _db.Dispose(); }
protected void Delete_Click(object sender, EventArgs e) { var context = new FileDb(); // Uv db c'est la classe qui correspond à la table en bd // On créé une nouvelle UV foreach (LO54_Projet.Entities.File f in context.Files) { if (f.IdFile == fileID) { File.Delete(f.FilePath); try { context.Files.Remove(f); } catch { System.Diagnostics.Debug.WriteLine("DELETE"); } } } try { context.SaveChanges(); // On sauvegarde les changements } catch (DbEntityValidationException ex) { foreach (DbEntityValidationResult item in ex.EntityValidationErrors) { // Get entry DbEntityEntry entry = item.Entry; string entityTypeName = entry.Entity.GetType().Name; // Display or log error messages foreach (DbValidationError subItem in item.ValidationErrors) { string message = string.Format("Error '{0}' occurred in {1} at {2}", subItem.ErrorMessage, entityTypeName, subItem.PropertyName); System.Diagnostics.Debug.WriteLine(message); } } } Response.Redirect(Request.RawUrl); }
//--------------------------------------------------------------------- internal void OpenDatabase(string dbFile) { DbTree.SuspendLayout(); try { FileDb fileDb = new FileDb(); fileDb.Open(dbFile, false); OpenDatabase(fileDb); } catch (Exception ex) { MessageBox.Show(ex.Message, null, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } finally { DbTree.ResumeLayout(); } }
public FrmAddField(FileDb fileDb) { _fileDb = fileDb; InitializeComponent(); cmbDataTypes.Items.Add(DataTypeEnum.Bool.ToString()); cmbDataTypes.Items.Add(DataTypeEnum.Byte.ToString()); cmbDataTypes.Items.Add(DataTypeEnum.DateTime.ToString()); cmbDataTypes.Items.Add(DataTypeEnum.Decimal.ToString()); cmbDataTypes.Items.Add(DataTypeEnum.Double.ToString()); cmbDataTypes.Items.Add(DataTypeEnum.Float.ToString()); cmbDataTypes.Items.Add(DataTypeEnum.Int32.ToString()); cmbDataTypes.Items.Add(DataTypeEnum.Int64.ToString()); cmbDataTypes.Items.Add(DataTypeEnum.Single.ToString()); cmbDataTypes.Items.Add(DataTypeEnum.String.ToString()); cmbDataTypes.Items.Add(DataTypeEnum.UInt32.ToString()); cmbDataTypes.SelectedItem = DataTypeEnum.String.ToString(); }
protected override bool IsValid(SearchLocation record, out string message) { message = null; if (record == null) { return(true); } var folders = FileDb.ParseFolders(record.Path, validate: false); foreach (var folder in folders) { if (!Directory.Exists(folder)) { message = $"Directory {folder} does not exist"; return(false); } } return(true); }
public void AddRecords() { FileDb _db = new FileDb(); _db.Open(DBFILE, false); var record = new FieldValues(); record.Add("FirstName", "Nancy"); record.Add("LastName", "Davolio"); record.Add("BirthDate", new DateTime(1968, 12, 8)); record.Add("IsCitizen", true); record.Add("DoubleField", 1.23); record.Add("ByteField", 1); record.Add("StringArrayField", new string[] { "s1", "s2", "s3" }); record.Add("ByteArrayField", new Byte[] { 1, 2, 3, 4 }); record.Add("IntArrayField", new int[] { 100, 200, 300, 400 }); record.Add("DoubleArrayField", new double[] { 1.2, 2.4, 3.6, 4.8 }); record.Add("DateTimeArrayField", new DateTime[] { DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now }); record.Add("BoolArrayField", new bool[] { true, false, true, false }); _db.AddRecord(record); _db.Dispose(); }
private void DoSubmitBook(object sender, RoutedEventArgs e) { //Reload: //FileDb booksDb = new FileDb(); //booksDb.Open("Books.fdb", false); //if (booksDb.IsOpen) //{ // BookViewModel.BookList = booksDb.SelectAllRecords().ToList(); //} //else //{ //create database file CreateAnOpenDataBaseFile(); _booksDb = new FileDb(); _booksDb.Open("Books.fdb", false); Book book = new Book { AuthorsName = txtAuthorsName.Text, Mvp = txtMvp.Text, Title = txtTitle.Text }; int p = PostData(book, _booksDb); if (p > 0) { MessageBox.Show("Entry Successful!"); } if (_booksDb.IsOpen) { BookViewModel.BookList = _booksDb.SelectAllRecords().ToList(); } _booksDb.Close(); }
public void SpeedTesting() { LogManager.GetRepository().Threshold = Level.Off; ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level = Level.Off; ((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).RaiseConfigurationChanged(EventArgs.Empty); log4net.LogManager.ShutdownRepository(); log4net.LogManager.Shutdown(); if (X.Instance.Debug == false) { return; } var setGuid = Guid.Parse("844d5fe3-bdb5-4ad2-0702-000000000000"); FileDb con = null; //var con = DbContext.Get().Db; return; var byTime = Time(100, () => { //con.Query<Set>().By(x => x.Id, Op.Eq, setGuid); }); var createQueryTime = Time(100, () => { var q = new CollectionQuery <Set>(con.Config.Configurations); }); var siTime = Time(100, () => { con.Config.Configurations.First().CreateSearchIndex(); }); Console.WriteLine("Average By Time: " + byTime); Console.WriteLine("Average CreateSearchIndex Time: " + siTime); Console.WriteLine("Average Create Query Time: " + createQueryTime); }
private void CreateAnOpenDataBaseFile() { FileDb booksDb = new FileDb(); Field field; var fieldLst = new List <Field>(20); field = new Field("ID", DataTypeEnum.Int32) { AutoIncStart = 0, IsPrimaryKey = true }; fieldLst.Add(field); field = new Field("AuthorsName", DataTypeEnum.String); fieldLst.Add(field); field = new Field("Age", DataTypeEnum.String); fieldLst.Add(field); field = new Field("Title", DataTypeEnum.String); fieldLst.Add(field); field = new Field("Mvp", DataTypeEnum.String); fieldLst.Add(field); booksDb.Create("Books.fdb", fieldLst.ToArray()); booksDb.Close(); }
// Custom class version // void LinqSelect_Custom() { FileDb employeesDb = new FileDb(); string path = System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, StrNorthwindRelPath ); path = System.IO.Path.GetFullPath( path ); employeesDb.Open( path + "Employees.fdb", true ); try { FilterExpression filterExp = FilterExpression.Parse( "LastName in ('Fuller', 'Peacock')" ); IList<Employee> employees = employeesDb.SelectRecords<Employee>( filterExp ); var records = from e in employees select new { ID = e.EmployeeID, Name = e.FirstName + " " + e.LastName, Title = e.Title }; grid.Columns.Clear(); grid.ItemsSource = records.ToList(); } finally { employeesDb.Close(); } }
// Custom class version // void LinqJoin_Custom() { FileDb customersDb = new FileDb(), ordersDb = new FileDb(), orderDetailsDb = new FileDb(), productsDb = new FileDb(); string path = System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, StrNorthwindRelPath ); path = System.IO.Path.GetFullPath( path ); customersDb.Open( path + "Customers.fdb", true ); ordersDb.Open( path + "Orders.fdb", true ); orderDetailsDb.Open( path + "OrderDetails.fdb", true ); productsDb.Open( path + "Products.fdb", true ); try { // Step 1: Get the Tables we will use with Linq // Note: we only get the columns we will be using so as to keep the size of the table data small // get all Customer records FilterExpression filterExp; IList<Customer> customers = customersDb.SelectRecords<Customer>( "CustomerID = ALFKI", new string[] { "CustomerID", "CompanyName" } ); // now get only Order records for the target Customer records using FilterExpression.CreateInExpressionFromTable // this method creates a HastSet which is extremely efficient when used by FileDb.SelectRecords filterExp = FilterExpression.CreateInExpressionFromTable<Customer>( "CustomerID", customers, "CustomerID" ); IList<Order> orders = ordersDb.SelectRecords<Order>( filterExp, new string[] { "CustomerID", "OrderID", "OrderDate" } ); // now get only OrderDetails records for the target Order records filterExp = FilterExpression.CreateInExpressionFromTable<Order>( "OrderID", orders, "OrderID" ); IList<OrderDetail> orderDetails = orderDetailsDb.SelectRecords<OrderDetail>( filterExp, new string[] { "OrderID", "ProductID", "UnitPrice", "Quantity" } ); // now get only Product records for the target OrderDetails records filterExp = FilterExpression.CreateInExpressionFromTable<OrderDetail>( "ProductID", orderDetails, "ProductID" ); IList<Product> products = productsDb.SelectRecords<Product>( filterExp, new string[] { "ProductID", "ProductName" } ); // produces a flat/normalized sequence var custOrderDetails = from c in customers join o in orders on c.CustomerID equals o.CustomerID join od in orderDetails on o.OrderID equals od.OrderID join p in products on od.ProductID equals p.ProductID select new { ID = c.CustomerID, CompanyName = c.CompanyName, OrderID = o.OrderID, OrderDate = o.OrderDate, ProductName = p.ProductName, UnitPrice = od.UnitPrice, Quantity = od.Quantity }; grid.Columns.Clear(); grid.ItemsSource = custOrderDetails.ToList(); } finally { customersDb.Close(); ordersDb.Close(); orderDetailsDb.Close(); productsDb.Close(); } }
public void Enumerate() { FileDb dbconfig = null; return; foreach (var config in dbconfig.Config.Configurations) { var root = new DirectoryInfo(Path.Combine(dbconfig.Config.Directory, config.Root.PartString)); foreach (var r in root.SplitFull()) { if (!Directory.Exists(r.FullName)) { Directory.CreateDirectory(r.FullName); } } var searchList = new List <DirectoryInfo>(); searchList.Add(root); var done = false; foreach (var part in config.Parts) { if (done) { break; } switch (part.PartType) { case PartType.Directory: for (var i = 0; i < searchList.Count; i++) { searchList[i] = new DirectoryInfo(Path.Combine(searchList[i].FullName, part.PartString)); if (!Directory.Exists(searchList[i].FullName)) { Directory.CreateDirectory(searchList[i].FullName); } } break; case PartType.Property: //if next not file var newList = new List <DirectoryInfo>(); foreach (var i in searchList) { newList.AddRange(i.GetDirectories()); } searchList = newList; break; case PartType.File: var remList = new List <DirectoryInfo>(); foreach (var i in searchList) { if (i.GetFiles().Any(x => x.Name == part.PartString) == false) { remList.Add(i); } } foreach (var i in remList) { searchList.Remove(i); } break; default: throw new ArgumentOutOfRangeException(); } } //Console.WriteLine(timer.ElapsedMilliseconds); //foreach (var f in searchList) Console.WriteLine(f.FullName); } var timer = new Stopwatch(); timer.Start(); foreach (var g in dbconfig.Query <Game>()) { } timer.Stop(); Console.WriteLine("GameLoadTime: {0}", timer.ElapsedMilliseconds); timer.Reset(); timer.Start(); var cardCount = 0; foreach (var s in dbconfig.Query <Set>()) { cardCount += s.Cards.Count(); } foreach (var s in dbconfig.Query <GameScript>()) { Console.WriteLine(s.Path); } foreach (var p in dbconfig.Query <ProxyDefinition>()) { Console.WriteLine(p.Key); } timer.Stop(); Console.WriteLine("TotalCards: {0}", cardCount); Console.WriteLine("TotalLoadTime: {0}", timer.ElapsedMilliseconds); //Assert.Fail(); }
/// <summary> /// Pretty much SELECT * FROM [TABLE] WHERE id=id /// </summary> /// <param name="db">Table to search</param> /// <param name="id">id to search for</param> /// <returns></returns> public Table GetInfoByID(FileDb db, int id) { db.Open(Name, true); return(db.SelectRecords(new FilterExpression(db.Fields[0].Name, id, EqualityEnum.Equal))); }
// Custom class version // void LinqGroupBy_Custom() { FileDb employeesDb = new FileDb(); string path = System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, StrNorthwindRelPath ); path = System.IO.Path.GetFullPath( path ); employeesDb.Open( path + "Employees.fdb", true ); try { IList<Employee> employees = employeesDb.SelectAllRecords<Employee>(); var employeeGrps = from e in employees group e by e.Country into empGrp select new { Country = empGrp.Key, Employees = empGrp // this will contain a list of Employee objects }; MessageBox.Show( "Look in your debugger Output window to see the results" ); foreach( var grp in employeeGrps ) { Debug.WriteLine( grp.Country ); foreach( var employee in grp.Employees ) { Debug.WriteLine( employee.FirstName + " " + employee.LastName + " - " + employee.Title ); } } } finally { employeesDb.Close(); } }
void create( String fileName ) { // Database schema: // ID ParentID Name Type Value Values Field field; List<Field> fieldLst = new List<Field>( 10 ); field = new Field( StrID, DataTypeEnum.Int ); field.AutoIncStart = 0; field.IsPrimaryKey = true; fieldLst.Add( field ); field = new Field( StrParentID, DataTypeEnum.Int ); fieldLst.Add( field ); field = new Field( StrName, DataTypeEnum.String ); fieldLst.Add( field ); field = new Field( StrType, DataTypeEnum.Int ); fieldLst.Add( field ); field = new Field( StrDataType, DataTypeEnum.Int ); fieldLst.Add( field ); field = new Field( StrValue, DataTypeEnum.String ); fieldLst.Add( field ); field = new Field( StrValues, DataTypeEnum.String ); field.IsArray = true; fieldLst.Add( field ); _db = new FileDb(); _db.Create( fileName, fieldLst.ToArray() ); FieldValues fieldValues = new FieldValues(3); fieldValues.Add( StrParentID, (Int32) (-1) ); fieldValues.Add( StrName, "LocalMachine" ); fieldValues.Add( StrType, (Int32) KeyValueType.Key ); fieldValues.Add( StrDataType, (Int32) ConfigDbDataType.String ); _db.AddRecord( fieldValues ); fieldValues = new FieldValues(3); fieldValues.Add( StrParentID, (Int32) (-1) ); fieldValues.Add( StrName, "CurrentUser" ); fieldValues.Add( StrType, (Int32) KeyValueType.Key ); fieldValues.Add( StrDataType, (Int32) ConfigDbDataType.String ); _db.AddRecord( fieldValues ); }
public Table ReadRecord() { FileDb _db = new FileDb(); _db.Open(DBFILE, false); // the easy way, using the expression parser // FilterExpressionGroup srchExpGrp = FilterExpressionGroup.Parse //("(FirstName ~= 'andrew' OR FirstName ~= 'nancy') AND LastName = 'Fuller'"); FilterExpressionGroup srchExpGrp = FilterExpressionGroup.Parse ("FirstName = 'Nancy'"); Table table = _db.SelectRecords(srchExpGrp, null, null, false); //// equivalent building it manually //var fname1Exp = new FilterExpression //("FirstName", "andrew", ComparisonOperatorEnum.Equal, MatchTypeEnum.IgnoreCase); //var fname2Exp = new FilterExpression //("FirstName", "nancy", ComparisonOperatorEnum.Equal, MatchTypeEnum.IgnoreCase); //var lnameExp = new FilterExpression //("LastName", "Fuller", ComparisonOperatorEnum.Equal, MatchTypeEnum.UseCase); //var fnamesGrp = new FilterExpressionGroup(); //fnamesGrp.Add(BoolOpEnum.Or, fname1Exp); //fnamesGrp.Add(BoolOpEnum.Or, fname2Exp); //var allNamesGrp = new FilterExpressionGroup(); //allNamesGrp.Add(BoolOpEnum.And, lnameExp); //allNamesGrp.Add(BoolOpEnum.And, fnamesGrp); //// should get the same records //table = _db.SelectRecords(allNamesGrp, null, null, false); _db.Dispose(); return table; }
public OneFileDriverRepository(FileDb db) { _db = db; }
public AmazonRobot(FileDb db) : base(db) { }
public override void SetDatabaseFile(FileDb database) { FileDatabase = database; }
/// <summary> /// Add record to the DB /// </summary> /// <param name="db">The db to add to</param> /// <param name="values">The values to add to the table.</param> public void AddRecord(FileDb db, FieldValues values) { db.Open(Name, false); db.AddRecord(values); }
public Robot(FileDb db) { this.db = db; }
public async Task <MessageModel> SendMessage(MessageModel message) { var user = await _userManager.FindByNameAsync(Thread.CurrentPrincipal.Identity.Name); if (ReferenceEquals(message.ChatId, null)) { var companion = await _userManager.FindByNameAsync(message.ToChatName); if (!(await _chat.IsChatExist(user, companion, message))) { _chat.CreateNewChat(user, companion, message); } } FileDb fileDb = null; if (!ReferenceEquals(message.File, null)) { fileDb = new FileDb(); fileDb.FilePath = message.File.FileFullName; fileDb.IsImage = message.File.IsImage; fileDb.IsAudio = message.File.IsVoice; fileDb.IsVideo = message.File.IsVideo; _context.Files.Add(fileDb); _context.Entry(fileDb).State = EntityState.Added; } var dbMessage = new Message() { ChatId = message.ChatId, Content = message.Content, UserId = user.Id, File = ReferenceEquals(message.File, null) ? null : fileDb?.Id, Created = DateTime.Now }; _context.Messages.Add(dbMessage); _context.Entry(dbMessage).State = EntityState.Added; await _context.SaveChangesAsync(); message.MessageId = dbMessage.Id; message.DateCreate = dbMessage.Created; var dbCurrentStatusMessage = new MessageStatus() { MessageId = dbMessage.Id, IsRead = true, UserId = user.Id, }; _context.MessagesStatus.Add(dbCurrentStatusMessage); if ((await _context.Chats.FindAsync(message.ChatId)).ChatType == ChatEnum.ChatForTwo) { var chatForTwo = _context.ChatsForTwo.FirstOrDefault(x => String.Equals(x.ChatId, message.ChatId)); var dbCompanionStatusMessage = new MessageStatus() { MessageId = dbMessage.Id, UserId = String.Equals(Thread.CurrentPrincipal.Identity.Name, chatForTwo.FirstUser.UserName) ? chatForTwo.SecondUser.Id : chatForTwo.FirstUser.Id }; _context.MessagesStatus.Add(dbCompanionStatusMessage); message.ToChatName = String.Equals(user.UserName, chatForTwo.FirstUser.UserName) ? chatForTwo.FirstUser.UserName : chatForTwo.SecondUser.UserName; await _hubContext.Clients.User(dbCompanionStatusMessage.UserId).SendAsync("ReceiveMessage", message); message.ToChatName = user.UserName; } else { var chatForGroup = _context.ChatsForGroup.FirstOrDefault(x => String.Equals(x.ChatId, message.ChatId)); var sorted = chatForGroup.GroupsUsers.Where(x => !String.Equals(user.Id, x.UserId)).Select(x => x.UserId); if (!chatForGroup.GroupsUsers.Any(x => String.Equals(user.Id, x.UserId))) { _context.GroupsUsers.Add(new GroupsUsers() { GroupId = chatForGroup.Id, UserId = user.Id }); var newChat = new ChatListModel() { ChatId = chatForGroup.ChatId, ChatName = chatForGroup.Chat.ChatName, ChatEnum = ChatEnum.ChatForGroup }; await _hubContext.Clients.User(user.Id).SendAsync("NewChat", newChat); } foreach (var userId in sorted) { var dbCompanionStatusMessage = new MessageStatus() { MessageId = dbMessage.Id, UserId = userId }; _context.MessagesStatus.Add(dbCompanionStatusMessage); } await _hubContext.Clients.Users(sorted.ToList()).SendAsync("ReceiveMessage", message); } await _context.SaveChangesAsync(); message.IsMyMessage = true; return(message); }
public ZhaoCaiBaoRobot(FileDb db, PageProcessorFactory pageProcessorFactory,Speaker speaker) : base(db) { this.pageProcessorFactory = pageProcessorFactory; this.speaker = speaker; }
/// <summary> /// One very powerful feature of FileDb is the ability to select records /// from a Table object. This would be very handy if you have a Table /// and you want to perform Select operations against it directly rather /// than the database. /// </summary> /// private void BtnTableFromTable_Click( object sender, RoutedEventArgs e ) { try { FileDb customersDb = new FileDb(); string path = System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, StrNorthwindRelPath ); path = System.IO.Path.GetFullPath( path ); try { customersDb.Open( path + "Customers.fdb", true ); FileDbNs.Table customers = customersDb.SelectAllRecords(); FileDbNs.Table subCusts = customers.SelectRecords( "CustomerID <> 'ALFKI'", new string[] { "CustomerID", "CompanyName", "City" }, new string[] { "~City", "~CompanyName" } ); displayRecords( subCusts ); } finally { customersDb.Close(); } } catch( Exception ex ) { MessageBox.Show( ex.Message ); } }
/// <summary> /// Here we see how to convert a Table directly to a new database just by calling Table.SaveToDb. /// </summary> /// private void BtnTableToDB_Click( object sender, RoutedEventArgs e ) { try { FileDb employeesDb = new FileDb(); string path = System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, StrNorthwindRelPath ); path = System.IO.Path.GetFullPath( path ); try { employeesDb.Open( path + "Employees.fdb", true ); string searchVal = @"\bFull"; var fieldSearchExp = new FilterExpression( "LastName", searchVal, EqualityEnum.Like ); FileDbNs.Table table = employeesDb.SelectRecords( fieldSearchExp ); FileDb newDb = table.SaveToDb( "Employees2.fdb" ); table = newDb.SelectRecords( fieldSearchExp ); displayRecords( table ); newDb.Close(); } finally { employeesDb.Close(); } } catch( Exception ex ) { MessageBox.Show( ex.Message ); } }
public int DeleteRecord() { FileDb _db = new FileDb(); _db.Open(DBFILE, false); // the easy way, using the expression parser // FilterExpressionGroup srchExpGrp = FilterExpressionGroup.Parse //("(FirstName ~= 'andrew' OR FirstName ~= 'nancy') AND LastName = 'Fuller'"); FilterExpressionGroup srchExpGrp = FilterExpressionGroup.Parse ("FirstName = 'Nancy'"); var ret = _db.DeleteRecords(srchExpGrp); _db.Dispose(); return ret; }
// Custom class version // void LinqAggregates_Custom() { FileDb customersDb = new FileDb(), ordersDb = new FileDb(), orderDetailsDb = new FileDb(); string path = System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, StrNorthwindRelPath ); path = System.IO.Path.GetFullPath( path ); customersDb.Open( path + "Customers.fdb", true ); ordersDb.Open( path + "Orders.fdb", true ); orderDetailsDb.Open( path + "OrderDetails.fdb", true ); try { // Step 1: Get the Tables we will use with Linq // Note: we only get the columns we will be using so as to keep the size of the table data small // get all Customer records FilterExpression filterExp; IList<Customer> customers = customersDb.SelectAllRecords<Customer>( new string[] { "CustomerID", "CompanyName" } ); // now get only Order records for the target Customer records using FilterExpression.CreateInExpressionFromTable // this method creates a HastSet which is extremely efficient when used by FileDb.SelectRecords filterExp = FilterExpression.CreateInExpressionFromTable<Customer>( "CustomerID", customers, "CustomerID" ); IList<Order> orders = ordersDb.SelectRecords<Order>( filterExp, new string[] { "CustomerID", "OrderID", "OrderDate" } ); // now get only OrderDetails records for the target Order records filterExp = FilterExpression.CreateInExpressionFromTable<Order>( "OrderID", orders, "OrderID" ); IList<OrderDetail> orderDetails = orderDetailsDb.SelectRecords<OrderDetail>( filterExp, new string[] { "OrderID", "ProductID", "UnitPrice", "Quantity" } ); // Step 2: Use Linq to generate the objects for us var customerOrders = from c in customers join o in orders on c.CustomerID equals o.CustomerID into ordersGrp // "into" gives us hierarchical result sequence select new { CustomerId = c.CustomerID, CustomerName = c.CompanyName, Orders = from order in ordersGrp join od in orderDetails on order.OrderID equals od.OrderID into orderDetailsGrp // "into" gives us hierarchical result sequence select new { OrderId = order.OrderID, OrderDate = order.OrderDate, NumItems = orderDetailsGrp.Count(), TotalSale = orderDetailsGrp.Sum( od => od.UnitPrice * od.Quantity ), AverageSale = orderDetailsGrp.Average( od => od.UnitPrice * od.Quantity ) } }; MessageBox.Show( "Look in your debugger Output window to see the results" ); foreach( var custOrder in customerOrders ) { Debug.WriteLine( custOrder.CustomerName ); foreach( var order in custOrder.Orders ) { Debug.WriteLine( "\tOrder ID: {0}\t NumItems: {2}\t Total Sale: ${1:0.00}\t Average Sale: ${3:0.00}", order.OrderId, order.NumItems, order.TotalSale, order.AverageSale ); } Debug.WriteLine( string.Empty ); } } finally { customersDb.Close(); ordersDb.Close(); orderDetailsDb.Close(); } }
public void Open( String fileName ) { _db = new FileDb(); _db.Open( fileName, false ); }
// Custom class version // void LinqHierarchicalObjects_Custom() { FileDb customersDb = new FileDb(), ordersDb = new FileDb(), orderDetailsDb = new FileDb(), productsDb = new FileDb(); string path = System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, StrNorthwindRelPath ); path = System.IO.Path.GetFullPath( path ); customersDb.Open( path + "Customers.fdb", true ); ordersDb.Open( path + "Orders.fdb", true ); orderDetailsDb.Open( path + "OrderDetails.fdb", true ); productsDb.Open( path + "Products.fdb", true ); try { // Step 1: Get the Tables we will use with Linq // Note: we only get the columns we will be using so as to keep the size of the table data small // get all Customer records FilterExpression filterExp; IList<Customer> customers = customersDb.SelectRecords<Customer>( "CustomerID = ALFKI", new string[] { "CustomerID", "CompanyName" } ); // now get only Order records for the target Customer records using FilterExpression.CreateInExpressionFromTable // this method creates a HastSet which is extremely efficient when used by FileDb.SelectRecords filterExp = FilterExpression.CreateInExpressionFromTable( "CustomerID", customers, "CustomerID" ); IList<Order> orders = ordersDb.SelectRecords<Order>( filterExp, new string[] { "CustomerID", "OrderID", "OrderDate" } ); // now get only OrderDetails records for the target Order records filterExp = FilterExpression.CreateInExpressionFromTable( "OrderID", orders, "OrderID" ); IList<OrderDetail> orderDetails = orderDetailsDb.SelectRecords<OrderDetail>( filterExp, new string[] { "OrderID", "ProductID", "UnitPrice", "Quantity" } ); // now get only Product records for the target OrderDetails records filterExp = FilterExpression.CreateInExpressionFromTable( "ProductID", orderDetails, "ProductID" ); IList<Product> products = productsDb.SelectRecords<Product>( filterExp, new string[] { "ProductID", "ProductName" } ); // Step 2: Use Linq to generate the objects for us var customerOrders = from c in customers join o in orders on c.CustomerID equals o.CustomerID into ordersGrp // "into" gives us hierarchical result sequence select new { CustomerId = c.CustomerID, CustomerName = c.CompanyName, Orders = from order in ordersGrp join od in orderDetails on order.OrderID equals od.OrderID into orderDetailsGrp // "into" gives us hierarchical result sequence select new { OrderId = order.OrderID, OrderDate = order.OrderDate, OrderDetails = from ood in orderDetailsGrp join p in products on ood.ProductID equals p.ProductID // pull in the Product name select new { ProductName = p.ProductName, UnitPrice = ood.UnitPrice, Quantity = ood.Quantity } } }; MessageBox.Show( "Look in your debugger Output window to see the results" ); foreach( var custOrder in customerOrders ) { Debug.WriteLine( custOrder.CustomerName ); foreach( var order in custOrder.Orders ) { Debug.WriteLine( '\t' + order.OrderId.ToString() + " - " + order.OrderDate.ToString( "dd MMM yyy" ) ); foreach( var orderDetail in order.OrderDetails ) { Debug.WriteLine( "\t\t{0}\t Qty: {1}\t Unit Price: {2:0.00}\t Total Sale: ${3:0.00}", orderDetail.ProductName, orderDetail.Quantity, orderDetail.UnitPrice, (orderDetail.Quantity * orderDetail.UnitPrice) ); } Debug.WriteLine( string.Empty ); } } } finally { customersDb.Close(); ordersDb.Close(); orderDetailsDb.Close(); productsDb.Close(); } }
public abstract void SetDatabaseFile(FileDb database);
/// <summary> /// Return the field definition /// </summary> /// <param name="db">The DB/Table</param> /// <returns></returns> public Fields GetFieldDefinition(FileDb db) { db.Open(Name, true); return(db.Fields); }