public void testDBlement() { Write("\n --- Test DBElement<int,string> ---"); DBElement<int, string> elem1 = new DBElement<int, string>(); elem1.payload = "a payload"; Write(elem1.showElement<int, string>()); WriteLine(); DBElement<int, string> elem2 = new DBElement<int, string>("Darth Vader", "Evil Overlord"); elem2.payload = "The Empire strikes back!"; Write(elem2.showElement<int, string>()); WriteLine(); var elem3 = new DBElement<int, string>("Luke Skywalker", "Young HotShot"); elem3.children.AddRange(new List<int> { 1, 5, 23 }); elem3.payload = "X-Wing fighter in swamp - Oh oh!"; Write(elem3.showElement<int, string>()); WriteLine(); Write("\n --- Test DBEngine<int,DBElement<int,string>> ---"); int key = 0; Func<int> keyGen = () => { ++key; return key; }; // anonymous function to generate keys DBEngine<int, DBElement<int, string>> db = new DBEngine<int, DBElement<int, string>>(); bool p1 = db.insert(keyGen(), elem1); bool p2 = db.insert(keyGen(), elem2); bool p3 = db.insert(keyGen(), elem3); if (p1 && p2 && p3) Write("\n all inserts succeeded"); else Write("\n at least one insert failed"); db.show<int, DBElement<int, string>, string>(); WriteLine(); }
/* Defining a query using lambda function to search specific key */ public void key_value_search(DBEngine<int, DBElement<int, string>> db, IQuery<int, DBElement<int, string>> i_query, QueryEngine<int, DBElement<int, string>> qe ) { "Query for value with specified key (key = 2):".title(); WriteLine(); int key_to_search = 2; Func<int, string, bool> keyValueSearch = (int key, string search) => //lambda function { if (!db.Keys().Contains(key)) return false; else { if (key == int.Parse(search)) { DBElement<int, string> ele = new DBElement<int, string>(); db.getValue(key, out ele); return true; } else { return false; } } }; // pass query to query engine and call simpleQuery to make query on DBEngine qe.simpleQuery(keyValueSearch, key_to_search.ToString(), out i_query); WriteLine(); foreach (var key in i_query.Keys()) { DBElement<int, string> temp = new DBElement<int, string>(); i_query.getValue(key, out temp); WriteLine("key : {0}", key); temp.showElement(); WriteLine(); } }
public void XMLWrite(DBEngine<int, DBElement<int, string>> db, out string pathname) { pathname = "xmlDoc.xml"; // The root element is nosqldb or nosqldbLOS, which we can say, is the name // of the database of the corresponding type. The declaration is important // from an XML parser point of view. DBElement<int, string> Val = new DBElement<int, string>(); XDocument doc = new XDocument(new XElement("nosqldb")); doc.Declaration = new XDeclaration("1.0", "utf - 8", "yes"); XElement keyType = new XElement("keytype", "int"); XElement payloadType = new XElement("payloadtype", "string"); doc.Root.Add(keyType); doc.Root.Add(payloadType); foreach (var key in db.Keys()) { XElement keyNode = new XElement("key", key); db.getValue(key, out Val); XElement elementNode = new XElement("element"); elementNode.Add(new XElement("name", Val.name)); elementNode.Add(new XElement("descr", Val.descr)); elementNode.Add(new XElement("timeStamp", Val.timeStamp.ToString())); XElement childrenNode = new XElement("children"); //since children is List<Key> foreach (var item in Val.children) { childrenNode.Add(new XElement("key", item)); } elementNode.Add(childrenNode); elementNode.Add(new XElement("payload", Val.payload)); //since payload is string for this type of database doc.Root.Add(keyNode); doc.Root.Add(elementNode); } doc.Save(pathname); }
static void Main(string[] args) { WriteLine("Testing DBExtensions Package\n"); WriteLine(); //Insert first element Write("\n --- Test DBElement<int,string> ---"); DBElement<int, string> elem1 = new DBElement<int, string>(); elem1.payload = "a payload"; Write(elem1.showElement<int, string>()); //Insert first element into DB DBEngine<int, DBElement<int, string>> dbs = new DBEngine<int, DBElement<int, string>>(); dbs.insert(1, elem1); dbs.show<int, DBElement<int, string>, string>(); WriteLine(); //Insert first element into String Key/Value DB Write("\n --- Test DBElement<string,List<string>> ---"); DBElement<string, List<string>> newelem1 = new DBElement<string, List<string>>(); newelem1.name = "newelem1"; newelem1.descr = "test new type"; newelem1.children = new List<string> { "Key1", "Key2" }; newelem1.payload = new List<string> { "one", "two", "three" }; Write(newelem1.showElement<string, List<string>, string>()); DBEngine<string, DBElement<string, List<string>>> dbe = new DBEngine<string, DBElement<string, List<string>>>(); dbe.insert("key1", newelem1); dbe.show<string, DBElement<string, List<string>>, List<string>, string>(); Write("\n\n"); }
static void Main(string[] args) { Test1(); //Load the first element DBElement<string, string> newelem1, newerelem1, newerelem2; Test2(out newelem1, out newerelem1, out newerelem2); Write("\n --- Test DBEngine<string,DBElement<string,List<string>>> ---"); //Anonymous function to get the string key int seed = 0; string skey = seed.ToString(); Func<string> skeyGen = () => { ++seed; skey = "string" + seed.ToString(); skey = skey.GetHashCode().ToString(); return skey; }; //Insert into DB and show the DB DBEngine<string, DBElement<string, string>> newdb = new DBEngine<string, DBElement<string, string>>(); newdb.insert(skeyGen(), newelem1); newdb.insert(skeyGen(), newerelem1); newdb.insert(skeyGen(), newerelem2); newdb.showEnumerableDB(); Write("\n\n"); }
// function to insert into database public XElement insert(XElement dbe, DBEngine<int, DBElement<int, string>> db) { DBElement<int, string> elem = new DBElement<int, string>(); Console.WriteLine("\n"); Console.WriteLine("\n----------Insert operation----------"); elem.name = dbe.Element("name").Value; elem.descr = dbe.Element("descr").Value; elem.payload = dbe.Element("payload").Value; List<int> childrenlist = new List<int>(); XElement db1 = dbe.Element("children"); foreach (var v in db1.Elements("dbkey")) childrenlist.Add(Int32.Parse(v.Value)); elem.children = childrenlist; bool result = db.insert(Int32.Parse((dbe.Element("key").Value)), elem); db.showDB(); if (result == true) { XElement s = new XElement("result", "\n element inserted successfully "); return s; } else { XElement f = new XElement("result", "Failure"); return f; } }
public LoadXML(DBEngine<int, DBElement<int, string>> database, string path) { db = database; xml = XDocument.Load(path); //Console.Write("\n{0}\n", xml.Declaration); //Console.Write(xml.ToString()); //Console.Write("\n\n"); }
public RequestHandler() { sb = new StringBuilder(); db = new DBEngine<int, DBElement<int, string>>(); query = new QueryEngine<int, DBElement<int, string>>(); dbString = new DBEngine<string, DBElement<string, List<string>>>(); strElem = new DBElement<string, List<string>>(); }
public static void ConnectDatabase() { if (File.Exists(Properties.Settings.Default.PathToDatabase)) { _dbe = new DBEngine(); try { _db = _dbe.OpenDatabase(Properties.Settings.Default.PathToDatabase, false, false); } catch { throw; } } else throw new FileNotFoundException("База данных по указанному пути не найдена"); }
public Scheduler(DBEngine<int, DBElement<int, string>> db) { schedular.Interval = 1000; // save interval is 1 second schedular.AutoReset = true; schedular.Elapsed += (object source, ElapsedEventArgs e) => { PersistToXML toxml = new PersistToXML(db); Console.Write("\n myDBXml.xml was saved at {0}", e.SignalTime); toxml.writeXML("myDBXml.xml"); }; }
//--------< Parser class to parse content from received messages //-------- and generate NoSQLDatabase calls>-------------------------- /////////////////////////////////////////////////////////////////////// // for Database with Key as string and Value as List<string> // // public string parse(ref IEnumerator<string> msg_enumerator, DBEngine<string, DBElement<string, List<string>>> db) { string str = ""; while (msg_enumerator.MoveNext()) { if(msg_enumerator.Current == "querytype" && msg_enumerator.MoveNext()) switch (msg_enumerator.Current) { case "Insert Element": insert_element(out str, ref msg_enumerator, db); break; case "Delete Element": delete_element(out str, ref msg_enumerator, db); break; case "Edit Element Metadata": edit_element(out str, ref msg_enumerator, db, "edit metadata"); break; case "Edit Element Metadata and Add Children": edit_element(out str, ref msg_enumerator, db, "add children"); break; case "Edit Element Metadata and Remove Children": edit_element(out str, ref msg_enumerator, db, "remove children"); break; case "Edit Element Metadata and Edit Payload": edit_element(out str, ref msg_enumerator, db, "edit payload"); break; case "Persist Database": persist_database(out str, ref msg_enumerator, db); break; case "Restore Database": restore_database(out str, ref msg_enumerator, db); break; case "Search Key-Value": search_key_value(out str, ref msg_enumerator, db); break; case "Search Children": search_children(out str, ref msg_enumerator, db); break; case "Pattern Matching": pattern_matching(out str, ref msg_enumerator, db); break; case "String in Metadata": string_metadata(out str, ref msg_enumerator, db); break; case "Time-Date Interval": time_date_inerval(out str, ref msg_enumerator, db); break; } } return str; }
/// <summary> /// Editing Data while updating.This returns element to be modified /// </summary> /// <param name="dbStore"></param> /// <param name="key"></param> /// <param name="element"></param> /// <param name="Operation"></param> /// <param name="error"></param> /// <returns></returns> public bool EditData(ref DBEngine<int, DBElement<int, string>> dbStore, int key, out DBElement<int, string> element, string Operation, out string error) { try { DBElement<int, string> elem = new DBElement<int, string>(); error = "success"; bool success = true; success = dbStore.getValue(key, out element); if (success != true) { error = "Key not found in DB"; return false; } elem = element; switch (Operation) { case "EditName": //Modify Name { element.name = elem.name; break; } case "EditDescription": //Modify Description { element.descr = elem.descr; break; } case "EditPayload": //Modify Payload { element.payload = elem.payload; break; } case "EditChildren": //Modify Children { element.children = new List<int>(); element.children = elem.children; break; } case "EditKeyNotValid": //Key editing is not valid { error = "Editing of Key is not allowed"; return false; } default: break; } return true; } catch (Exception ex) { throw new CustomException("error at itemeditor editdata", ex); } }
public static IDbCommand GetCommand(DBEngine db) { switch (db) { case DBEngine.MSSQL: return(new SqlCommand()); case DBEngine.MYSQL: return(new MySqlCommand()); default: return(new SqlCommand()); } }
static void Main(string[] args) { "Testing ItemEditor Package".title('='); WriteLine(); ItemEditorTest iET = new ItemEditorTest(); iET.insertData(db); DBEngine<int,DBElement<int,string>> db = new DBEngine<int, DBElement<int, string>>(); ItemEditor<int, DBElement<int,string>> iEditor = new ItemEditor<int, DBElement<int,string>>(db); "\n1) Editing metadata".title(); "\nBefore editing metadata for key 1".title(); db.showDB(); "\nAfter editing metadata for key 1".title(); iEditor = new ItemEditor<int, DBElement<int, string>>(db); iEditor.editMetaData(1, "Sachin Tendulkar", "Cricket player"); //send the values to be edited to the editMetaData() function db.showDB(); WriteLine(); "\n2) Adding children".title(); "\nBefore adding relationship(children) for key 1".title(); db.showDB(); "\nAfter adding relationship(children) for Key 1".title(); iEditor.addrelationships(1, new List<int> { 3 }); //send a new list with children to be added to a key db.showDB(); WriteLine(); "\n3) Deleting children".title(); "\nBefore deleting relationship(children) for key 1".title(); db.showDB(); WriteLine(); "\nAfter deleting relationship(children) to Key 1".title(); //send a new list with children to be deleted from a key iEditor.deleteRelationships(1, new List<int> { 3 }); db.showDB(); WriteLine(); "\n4) Replacing value instance".title(); DBElement<int, string> elem = new DBElement<int, string>(); //create a new element for replacing value elem.name = "Messi"; elem.payload = "Plays for Argentina"; elem.descr = "Football player"; elem.children.AddRange(new List<int> { 2 }); elem.timeStamp = DateTime.Now; "\nBefore replacing the value instance for key 2".title(); db.showDB(); WriteLine(); "\nAfter replacing the value instance for key 2".title(); iEditor.replaceValueInstance(2, elem); //send value to be replaced for a key db.showDB(); }
public void performOperations(DBEngine<string, DBElement<string, List<string>>> testDict, DBElement<string, List<string>> value) { /*----------Perform operations as per the input given in the XML document--------------*/ if (value.operation == "addition") { testDict.insert(value.key, value); //insert the key/value pairs to the main database string s = "Database after inserting key " + value.key + " is"; printDatabase(testDict, s); } if (value.operation == "edit") { testDict.saveValue(value.key, value); //edit the value for the given key string s = "Database after editing key " + value.key + " is"; printDatabase(testDict, s); } if (value.operation == "delete") { testDict.delete(value.key); //delete the key/value pair string s = "Database after deleting key " + value.key + " is"; printDatabase(testDict, s); } if (value.operation == "persist database") { PersistEngine<string, DBElement<string, List<string>>> persist = new PersistEngine<string, DBElement<string, List<string>>>(testDict); var keys = testDict.Keys(); persist.persistToXMLListPayload(keys); printDatabase(testDict, "Persisted database is:"); } if (value.operation == "Query value") { DBElement<string, List<string>> valueOfKey = testDict.getValueOfKey(value.key); printQuery("Querying the database for value of key " + value.key + " is"); Console.WriteLine("\n\nThe value of the Key {0} is:\n", value.key); valueOfKey.showEnumerableElement(); } if (value.operation == "Query children") { QueryEngine<string, DBElement<string, List<string>>> qEngine = new QueryEngine<string, DBElement<string, List<string>>>(testDict); printQuery("Querying the database for value of key " + value.key + " is"); List<string> children = qEngine.getChildrenOfKey(value.key); Console.WriteLine("\nThe children of the Key {0} are:\n", value.key); displayChildren(children); } if (value.operation == "Augment database") { PersistEngine<string, DBElement<string, List<string>>> persist = new PersistEngine<string, DBElement<string, List<string>>>(testDict); string fileName = "C:\\Users\\rakeshh91\\Documents\\Rakesh Documents\\Class Materials\\SMA\\Assignments\\Assignment 4 - Implementation\\CommPrototype\\augmentDatabase.xml"; persist.augmentDatabaseFromXMLStringList(testDict, fileName); printDatabase(testDict, "Database after augmenting is:"); } }
/* Defining a query using lambda function to search children of specific element */ public void key_children_search(DBEngine<int, DBElement<int, string>> db, IQuery<int, DBElement<int, string>> i_query, QueryEngine<int, DBElement<int, string>> qe) { int specific_key = 2; "Query for children of specified key (key = 2):".title(); WriteLine(); Func<int, string, bool> childrenQuery = (int key, string search) => //lambda function { if (!db.Keys().Contains(key)) return false; if (key == int.Parse(search)) { DBElement<int, string> ele = new DBElement<int, string>(); db.getValue(key, out ele); return true; } else return false; }; // pass query to query engine and call simpleQuery to make query on DBEngine qe.simpleQuery(childrenQuery, specific_key.ToString(), out i_query); WriteLine(); foreach (var key in i_query.Keys()) { DBElement<int, string> temp = new DBElement<int, string>(); i_query.getValue(key, out temp); WriteLine("children of element with key {0} :", key); WriteLine(); if (temp.children != null) { int i = 0; foreach (int child in temp.children) { WriteLine("Children {0}", i++); DBElement<int, string> temp_child = new DBElement<int, string>(); if (db.Keys().Contains(child)) { db.getValue(child, out temp_child); WriteLine("key : {0}", child); temp_child.showElement(); WriteLine(); } else { WriteLine("no value with key {0} is present in database", child); WriteLine(); } } } } }
public static bool ResetReferenceNumbers() { var dbe = new DBEngine(); dao.Database db = dbe.OpenDatabase(global.MDBPath); try { try { db.QueryDefs.Delete("qry_tempResetRefNo1"); } catch { } try { db.QueryDefs.Delete("qry_tempResetRefNo2"); } catch { } string sql = @"SELECT Left([RefNo],InStr(InStr(1,[RefNo],'-')+1,[RefNo],'-')-1) AS code, CLng(Right([RefNo],Len(Left([RefNo],InStr(InStr(1,[RefNo],'-')+1,[RefNo],'-')-1))-3)) AS [counter] FROM tblSampling"; db.CreateQueryDef("qry_tempResetRefNo1", sql); sql = @"SELECT qry_tempResetRefNo1.code, Max(qry_tempResetRefNo1.counter) AS [max] From qry_tempResetRefNo1 GROUP BY qry_tempResetRefNo1.code"; db.CreateQueryDef("qry_tempResetRefNo2", sql); sql = "Delete * from tblRefCodeCounter"; db.Execute(sql); sql = @"INSERT INTO tblRefCodeCounter ( GearRefCode, [Counter] ) SELECT qry_tempResetRefNo2.code, [Max]+1 AS countermax FROM qry_tempResetRefNo2"; db.Execute(sql); db.QueryDefs.Delete("qry_tempResetRefNo1"); db.QueryDefs.Delete("qry_tempResetRefNo2"); return(true); } catch (Exception ex) { Logger.LogError(ex); return(false); } }
public static void SendEmail(string ReceiverEmailID, string EmailSubject, string MessageBody, string application = "") { string connectionString = ConfigurationManager.ConnectionStrings["NHSConStr"].ConnectionString; DBEngine dBEngine = new DBEngine(connectionString); WebsiteSetting setting = dBEngine.GetWebsiteSettings(0); #region Email string SMTPCLIENT = setting.SMTPServer; string EMAILID = setting.EmailID; string PASSWORD = setting.Password; int PORT = setting.Port; bool ENABLESSL = false; string EMAIL_DISPLAYNAME = "CORS"; #endregion try { MailMessage mail = new MailMessage(); string smtp = SMTPCLIENT; //ServerSettings.SMTPCLIENT; SmtpClient SmtpServer = new SmtpClient(SMTPCLIENT); //new SmtpClient(ServerSettings.SMTPCLIENT); //mail.From = new MailAddress(ServerSettings.EMAILID, ServerSettings.EMAIL_DISPLAYNAME); mail.From = new MailAddress(EMAILID, EMAIL_DISPLAYNAME); mail.To.Add(ReceiverEmailID); mail.Subject = HttpUtility.HtmlDecode(EmailSubject); String emailBody = MessageBody; mail.Body = HttpUtility.HtmlDecode(emailBody); mail.IsBodyHtml = true; //SmtpServer.Port = ServerSettings.PORT; SmtpServer.Port = PORT; //SmtpServer.Credentials = new System.Net.NetworkCredential(ServerSettings.EMAILID, ServerSettings.PASSWORD); SmtpServer.UseDefaultCredentials = false; SmtpServer.Credentials = new System.Net.NetworkCredential(EMAILID, PASSWORD); //SmtpServer.EnableSsl = ServerSettings.ENABLESSL; SmtpServer.EnableSsl = ENABLESSL; SmtpServer.Send(mail); } catch (Exception ex) { dBEngine.LogException(ex.Message, "HomeController", "SendEmail", System.DateTime.Now, 0); } }
public void InsertInteropDao() { object objOpt = System.Reflection.Missing.Value; var dbEngine = new DBEngine(); Database cdb = dbEngine.OpenDatabase(@"dbproba.mdb", objOpt, false, objOpt); Microsoft.Office.Interop.Access.Dao.Recordset rec = cdb.OpenRecordset("Tabl1", RecordsetTypeEnum.dbOpenDynaset, RecordsetOptionEnum.dbSeeChanges, Microsoft.Office.Interop.Access.Dao.LockTypeEnum.dbOptimistic); rec.MoveFirst(); MessageBox.Show(rec.Fields["s1"].Value.ToString()); rec.AddNew(); rec.Fields["s1"].Value = "ssssss"; rec.Update(); rec.Close(); cdb.Close(); }
//Function that create the relation private Database CreateRelation() { MyDB.Close(); DBEngine Dbe = new DBEngine(); MyDB = Dbe.OpenDatabase(FrmMain.GetPath); Field MyFL; Relation MyRL = MyDB.CreateRelation(txtRelationName.Text, CBOParentTable.SelectedItem, CBOForeignTable.SelectedItem); MyFL = MyRL.CreateField(CBOPrimaryKey.SelectedItem.ToString()); MyFL.ForeignName = CBOForeignKey.SelectedItem.ToString(); MyRL.Fields.Append(MyFL); MyDB.Relations.Append(MyRL); return(MyDB); }
private static string GetKeyName(string TableName) { if (TableName.Equals(string.Empty)) { return(""); } DataTable m_dtPrimaryKeys = DBEngine.execReturnDataTable("sp_TableEditor_GetPrimaryKeys", "@Tablename", TableName); string retVal = string.Empty; foreach (DataRow dr in m_dtPrimaryKeys.Rows) { retVal += dr[0] + " ; "; } return(retVal.Substring(0, retVal.Length - 3)); }
/// <summary> /// Persisting XML after a specified time interval /// </summary> public void PersistXML(DBEngine<int, DBElement<int, string>> db) { try { schedular.Interval = 3000; //Set timer to 3 seconds schedular.AutoReset = false; schedular.Enabled = true; // Anonymous function called after 3 sec schedular.Elapsed += (object source, ElapsedEventArgs e) => ScheduleXML(source, e, db); Thread.Sleep(3000); } catch (Exception ex) { throw new CustomException("error at scheduler persistxml", ex); } }
public bool Buy(string strWKN) { WorkDate today = this.RuleEngineInfo.Today; Depot depot = this.RuleEngineInfo.Depot; double dPrice = DBEngine.GetInstance().GetPrice(strWKN, today); int nQuantity = (int)(depot.Cash * 0.5 / dPrice); if (nQuantity > 100) { depot.Buy(strWKN, nQuantity, today, dPrice); return(true); } return(false); }
private void grvShiftSetting_Click(object sender, EventArgs e) { string strShiftCode = ""; strShiftCode = grvShiftSetting.GetDataRow(grvShiftSetting.FocusedRowHandle)[ShiftCode].ToString(); // Load Detail shift info dtShiftDetail = DBEngine.execReturnDataTable("sp_Shift_ListDetail", "@ShiftCode", strShiftCode); if (dtShiftDetail != null && dtShiftDetail.Rows.Count <= 0) { CRowUtility.addNewRow(dtShiftDetail, DayOff1, 0); } BidingShiftDetail(); DirtyData = false; txtShiftCode.Focus(); txtShiftCode.SelectAll(); }
public JsonResult GetModules(ChartLoadRequestObject reqObj) { DateTime startDate = string.IsNullOrEmpty(reqObj.StartDate) ? System.DateTime.Now.AddDays(-365) : DateTime.ParseExact(reqObj.StartDate, "dd/MM/yyyy", CultureInfo.InvariantCulture); DateTime endDate = string.IsNullOrEmpty(reqObj.EndDate) ? System.DateTime.Now : DateTime.ParseExact(reqObj.EndDate, "dd/MM/yyyy", CultureInfo.InvariantCulture); string connectionString = ConfigurationManager.ConnectionStrings["NHSConStr"].ConnectionString; DBEngine dBEngine = new DBEngine(connectionString); List <UserModuleDetails> userModuleDetails = dBEngine.GetUserModuleDetails(startDate, endDate, Convert.ToInt32(Session["LoginUserID"])); var moduleList = userModuleDetails.GroupBy(x => x.ModuleName).Select(x => new ModuleInformation() { ModuleId = x.Key, ModuleName = x.Key }).ToList(); return(Json(moduleList, JsonRequestBehavior.AllowGet)); }
public JsonResult AssignedLicenseBarChartResult(ChartLoadRequestObject reqObj) { DateTime startDate = System.DateTime.Now.AddDays(-365); DateTime endDate = System.DateTime.Now; string connectionString = ConfigurationManager.ConnectionStrings["NHSConStr"].ConnectionString; DBEngine dBEngine = new DBEngine(connectionString); List <NHS.Common.LicenseUsage> usage = dBEngine.GetUserCount(startDate, endDate, Convert.ToInt32(Session["LoginUserID"])); var filteredUsages = new List <LicenseUsage>(); var noOfTotalUsedLicense = 0; foreach (var data in usage.GroupBy(x => x.DistinctYear).ToList()) { noOfTotalUsedLicense += data.Sum(x => x.UsedLicense); var licenseData = new LicenseUsage() { DistinctYear = data.Key, LicenseCount = data.GroupBy(z => z.LicenseCount).FirstOrDefault().Key, UnusedLicense = data.GroupBy(z => z.LicenseCount).FirstOrDefault().Key - noOfTotalUsedLicense, UsedLicense = data.Sum(x => x.UsedLicense) }; filteredUsages.Add(licenseData); } var licenseInfo = new LicenseInformation { //TotalNodLicenseAllocated = yearlyResult.LicenseCount.ToString(), NoOfUsedLicense = filteredUsages.Sum(x => x.UsedLicense).ToString(), NoOfUnusedLicense = (filteredUsages.FirstOrDefault().LicenseCount - filteredUsages.Sum(x => x.UsedLicense)).ToString(), }; var serisData = new[] { Convert.ToInt32(licenseInfo.NoOfUsedLicense), Convert.ToInt32(licenseInfo.NoOfUnusedLicense) }; var LabelData = new[] { "Used", "Unused" }; var result = new { serisData, LabelData, licenseInfo }; return(Json(result, JsonRequestBehavior.AllowGet)); }
//---------< Call QueryEngine based on the query type >----------- public bool call(DBEngine <string, DBElement <string, List <string> > > db, string request) { if (db.Keys() == null) { return(false); } switch (request) { case "value": if (qe.getValue(query, db, out elem)) { return(true); } break; case "children": if (qe.getChildren(query, db, out replyList)) { return(true); } break; case "pattern": if (qe.searchPattern(query, db, out replyList)) { return(true); } break; case "string": if (qe.searchString(query, db, out replyList)) { return(true); } break; case "interval": if (qe.searchInterval(query, "", db, out replyList)) { return(true); } break; default: return(false); } return(false); }
private void frmShowTable_Load(object sender, EventArgs e) { string tblName = Variables.ShowTableName; txtTableName.Text = tblName; this.Text = "Database: " + dbPath; dbe = new DBEngine(); try { myDB = dbe.OpenDatabase(dbPath); txtTableName.Enabled = false; txtRecordsCount.Enabled = false; gridTable.Rows.Clear(); int numFld = 0; //show table info TableDef myTable = myDB.TableDefs[tblName]; foreach (Field fldExtItem in ((Fields)myTable.Fields)) { gridTable.Columns.Add(fldExtItem.Name.ToString(), fldExtItem.Name.ToString()); numFld++; } //recTblData = myDB.OpenRecordset("SELECT * FROM " + myTable.Name, DAO.RecordsetTypeEnum.dbOpenForwardOnly); recTblData = myDB.OpenRecordset("SELECT * FROM " + myTable.Name, DAO.RecordsetTypeEnum.dbOpenDynaset); recTblData.MoveLast(); recTblData.MoveFirst(); txtRecordsCount.Text = recTblData.RecordCount.ToString(); for (int i = 0; i < recTblData.RecordCount; i++) { gridTable.Rows.Add(1); for (int j = 0; j < numFld; j++) { gridTable.Rows[i].Cells[j].Value = (recTblData.Fields[j].Value.ToString()); } recTblData.MoveNext(); } myDB.Close(); } catch (Exception ex) { MessageBox.Show("Error openning database! \n" + ex.Message + "\n" + ex.HResult.ToString(), "Failed to open data", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); return; } }
public void bazaCompact() { string sciezka = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); string oldFileName = sciezka + "\\SIS_DB.accdb"; string newFileName = sciezka + "\\_SIS_DB.accdb"; DBEngine db = new DBEngine(); db.CompactDatabase(sciezka + "\\SIS_DB.accdb", sciezka + "\\_SIS_DB.accdb"); File.Delete(oldFileName); // Move (rename) the temporary compacted database to // the original filename File.Move(newFileName, oldFileName); // The operation was successful }
//Сжатие базы данных public static void Compress(string file, //файл базы int size, //размер а байтах, после которого нужно сжимать string tmpDir = null, //каталог временных фалов int timeout = 0) //время ожидания после сжатия в мс { if (file.IsEmpty()) { throw new NullReferenceException("Файл сжимаемой базы данных не может быть пустой строкой или null"); } var fdb = new FileInfo(file); if (fdb.Length < size) { return; } string sdir = fdb.Directory.FullName; if (tmpDir != null) { var dir = new DirectoryInfo(tmpDir); if (!dir.Exists) { dir.Create(); } sdir = tmpDir; } var ftmp = new FileInfo(sdir + @"\Tmp" + fdb.Name); if (ftmp.Exists) { ftmp.Delete(); } fdb.MoveTo(ftmp.FullName); new FileInfo(file).Delete(); var en = new DBEngine(); en.CompactDatabase(ftmp.FullName, file); en.FreeLocks(); en = null; GC.Collect(); if (timeout > 0) { Thread.Sleep(timeout); } }
/// <summary> /// Schedule XML persisting by calling the utlity function /// </summary> /// <param name="source"></param> /// <param name="e"></param> /// <param name="db"></param> /// <returns></returns> static bool ScheduleXML(object source, ElapsedEventArgs e, DBEngine<int, DBElement<int, string>> db) { try { string error = ""; string path = "";string xml = ""; XMLUtility.XMLUtilitySpace.PersistToXML(db, out error, out path,out xml); error = "Success"; Scheduler s = new Scheduler(); s.SetResetOff(); //Disable the scheduler return true; } catch (Exception ex) { throw new CustomException("error at scheduler persistxml", ex); } }
public static bool Diagnose(string mdbPath, string productVersion) { var dbe = new DBEngine(); var dbTemplate = dbe.OpenDatabase(global.ApplicationPath + "\\template.mdb"); var dbData = dbe.OpenDatabase(mdbPath); var count = 0; var os = Environment.OSVersion; Logger.LogSimple(""); Logger.Log("start FADDiagnostics"); Logger.LogSimple($"OS: {Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName", "")} {os.Version.Major}.{os.Version.Minor} {os.ServicePack}"); Logger.LogSimple($"FAD version: {productVersion}"); Logger.LogSimple($"Application path: {GetAppPath()}"); Logger.LogSimple($"Logged in user: {Environment.UserName}"); Logger.LogSimple($"Machine name: {Environment.MachineName}"); Logger.LogSimple($"RAM: {((int)(new ComputerInfo().TotalPhysicalMemory / (Math.Pow(1024, 3)) + 0.5)).ToString()} GB"); Logger.LogSimple($"CPU: {GetProcessor()}"); Logger.LogSimple(""); Logger.LogSimple("------------------------------------------------------------"); Logger.LogSimple("Database tables"); Logger.LogSimple($"Row\t{string.Format("{0,-40}", "Template table")}\tData table"); Logger.LogSimple("------------------------------------------------------------"); count = 0; foreach (TableDef tdTemplate in dbTemplate.TableDefs) { if (tdTemplate.Name.Substring(0, 4) != "MSys" && tdTemplate.Name.Substring(0, 5) != "temp_") { count++; Logger.LogSimpleEx($"{count}\t{string.Format("{0,-40}", tdTemplate.Name)}"); foreach (TableDef tdData in dbData.TableDefs) { if (tdData.Name == tdTemplate.Name) { Logger.LogSimpleEx("\tx\r\n"); break; } } } } Logger.LogSimple("------------------------------------------------------------"); Logger.LogSimple(""); Logger.Log("end FADDiagnostics"); return(count > 0); }
public override bool InitializeData() { try { //Load FunctionList dtFunctionList = DBEngine.execReturnDataTable("SC_FunctionList", "@LanguageID", UIMessage.languageID); cbxFunctionName.Properties.DataSource = dtFunctionList; cbxFunctionName.EditValue = "-1"; } catch (Exception e) { HPA.Common.Helper.ShowException(e, this.Name + ".InitializeData()", null); return(false); } return(true); }
void AttManager_OnAttTransactionEx(string EnrollNumber, int IsInValid, int AttState, int VerifyMethod, int Year, int Month, int Day, int Hour, int Minute, int Second, int WorkCode) { int iMachineNumber = MachineNumber; string strDateTime; DateTime logTime; string strQuery; try { //Show record DataRow drAdd = MachineManagement.dtLogList.NewRow(); drAdd[CommonConst.USER_ID] = EnrollNumber; drAdd[CommonConst.VERIFY_MODE] = VerifyMethod; // get Log time strDateTime = string.Format("{0}-{1}-{2} {3}:{4}:{5}", Year, Month, Day, Hour, Minute, Second); logTime = Convert.ToDateTime(strDateTime); drAdd[CommonConst.LOG_TIME] = logTime; DataTable dtUserInfo = DBEngine.execReturnDataTable("zk_UserInfo", "@UserID", EnrollNumber); if (dtUserInfo.Rows.Count <= 0) { // get privilage of new user // normal is 0: user strQuery = string.Format("INSERT INTO userinfo (Name,badgenumber,Privilege,SSN) VALUES ('{0}','{1}',{2},'{3}')", EnrollNumber, EnrollNumber, 0, EnrollNumber); DBEngine.exec(strQuery); dtUserInfo = DBEngine.execReturnDataTable("zk_UserInfo", "@UserID", EnrollNumber); } drAdd[CommonConst.MACHINE_ALIAS] = MachineName; drAdd[CommonConst.NAME_ON_MACHINE] = dtUserInfo.Rows[0][CommonConst.NAME_ON_MACHINE]; drAdd[CommonConst.FullName] = dtUserInfo.Rows[0][CommonConst.FullName]; drAdd[CommonConst.EmployeeID] = dtUserInfo.Rows[0][CommonConst.EmployeeID]; drAdd[CommonConst.PHOTO] = MachineManagement.dtUserList.Select(string.Format("Badgenumber = '{0}'", EnrollNumber))[0][CommonConst.PHOTO]; MachineManagement.dtLogList.Rows.Add(drAdd); //MachineManagement.dtLogList = DBEngine.execReturnDataTable("zk_UserInfo", "@UserID", EnrollNumber); //drAdd drAdd[CommonConst.MACHINE_NUMBER] = iMachineNumber; //Save to DataBase DBEngine.exec("sp_Checkinout_Save", "@UserID", drAdd[CommonConst.USER_ID], "@ChectTime", strDateTime, "@MachineNumber", drAdd[CommonConst.MACHINE_NUMBER], "@AttState", AttState, "@VERIFYCODE", VerifyMethod, "@WorkCode", WorkCode); } catch (Exception ex) { Helper.LogError(ex, ex.Message, "AttManager_OnAttTransactionEx"); } }
static void Main(string[] args) { "Testing PersistEngine Package".title('='); WriteLine(); DBEngine<int, DBElement<int, string>> db = new DBEngine<int, DBElement<int, string>>(); "\nSave to an XML file".title(); PersistEngineTest p1 = new PersistEngineTest(); p1.insertData(db); dynamic allKeys = db.Keys(); PersistEngine<int,DBElement<int,string>> pEngine = new PersistEngine<int, DBElement<int, string>>(db); pEngine.persistToXML(allKeys); WriteLine("\n\nAbove database is stored as XML file in local machine"); WriteLine(); WriteLine("\nThe persisted XML file along with new key/value pairs are augmented to the database.\n"); WriteLine("Below shown key/value pairs are augmented to the database.\n"); pEngine.augmentDatabaseFromXML(db); //Augment the persisted database along with new values to the main database pEngine.persistToXML(allKeys); db.showDB(); WriteLine(); WriteLine(); "\nPersist database every 5 seconds until its cancelled".title(); WriteLine(); pEngine.scheduledSaveDatabase(); WriteLine(); WriteLine(); "\nProject dependancy and realtionships".title(); WriteLine(); DBEngine<string, DBElement<string, List<string>>> dependancyDb = new DBEngine<string, DBElement<string, List<string>>>(); PersistEngine<string, DBElement<string, List<string>>> pEngineString = new PersistEngine<string, DBElement<string, List<string>>>(dependancyDb); try { Console.WriteLine("\nBelow details provide information on dependancy of every package in the project\n"); pEngine.displayDependancy(); dependancyDb.showEnumerableDB(); WriteLine(); } catch (Exception e) { WriteLine("\n" + e.Message + "\n"); } }
private void txtEmployeeID_Leave(object sender, EventArgs e) { if (!txtEmployeeID.Text.Trim().Equals("")) { DataTable dtFullName = DBEngine.execReturnDataTable("sp_hr_get_fullname", CommonConst.A_EmployeeID, txtEmployeeID.Text, CommonConst.A_LoginID, UserID); if (dtFullName != null && dtFullName.Rows.Count > 0) { txtFullName.Text = dtFullName.Rows[0][0].ToString(); ckbAllEmployees.Checked = false; } else { txtFullName.Text = ""; txtEmployeeID.SelectAll(); txtEmployeeID.Focus(); } } }
//static void ctr_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) //{ // if (e.KeyCode == System.Windows.Forms.Keys.Enter) // { // e.Handled = true; // System.Windows.Forms.SendKeys.Send("{TAB}"); // } //} public static string Get_InformInfo() { string strRetval = ""; DataTable dtInfo = DBEngine.execReturnDataTable("sp_GetInformInfor"); if (dtInfo.Rows.Count <= 0) { return(""); } else { foreach (DataRow dr in dtInfo.Rows) { strRetval += dr["Content"] + "\n\r"; } } return(strRetval); }
private void metroTile1_Click(object sender, EventArgs e) { //Checks if the textbox for database name is empty if (metroTextBoxDatabaseName.Text == "") { MetroFramework.MetroMessageBox.Show(this, "Enter the database name in textbox", "Important", MessageBoxButtons.OK, MessageBoxIcon.Hand); return; } else if (metroLabelPath.Text == "") { MetroFramework.MetroMessageBox.Show(this, "Specify a path for database", "Important", MessageBoxButtons.OK, MessageBoxIcon.Hand); return; } DBEngine dbe = new DBEngine(); Database myDB = dbe.CreateDatabase(metroLabelPath.Text + "\\" + metroTextBoxDatabaseName.Text + ".accdb", LanguageConstants.dbLangGeneral); }
private static void RemoveGearInventoryBarangayDataAltKey(string mdbPath) { var dbe = new DBEngine(); var dbData = dbe.OpenDatabase(mdbPath); var sql = "DROP INDEX AltKey ON tblGearInventoryBarangayData"; try { dbData.Execute(sql); } catch (Exception ex) { Logger.Log(ex.Message, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name); } dbData.Close(); dbData = null; }
//без статик // все что понадобится и может быть связано с папкой lucene private void btnSearch_Click(object sender, RoutedEventArgs e) { btnPlagCheck.IsEnabled = false; DownloadWork.IsEnabled = false; var engine = new DBEngine(); try { if (engine.CheckWorks()) { txtAuth.Text = ""; txtDis.Text = ""; txtName.Text = ""; txtDes.Text = ""; LuceneEngine le = new LuceneEngine(); //var c = le.CountDocs(); int number;//количество результатов string field = ""; IEnumerable <FileToIndex> results; if (txtboxSearch.Text.StartsWith("#")) { field = "Hashtags"; results = le.Search(txtboxSearch.Text.Substring(1, txtboxSearch.Text.Length - 1), out number, field); } else { results = le.Search(txtboxSearch.Text, out number); } lstboxResult.Items.Clear(); foreach (var doc in results) { lstboxResult.Items.Add(doc.Id + " " + doc.Title); } } } catch (Exception ex) { MessageBox.Show("Поиск не может быть проведен.\n" + ex, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } }
private static void CleanOutputDb() { string query = null; var file = input.CombinedOutputFileName; if (File.Exists(file)) { Console.Write($"Cleaning Up Output Db {file}"); string connetionString = null; connetionString = @"Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + file; OdbcConnection odbcConnection = new OdbcConnection(connetionString); try { odbcConnection.Open(); List <string> tableNames = input.TableNames.ToList(); Console.Write(" Deleted "); foreach (var tableName in tableNames) { query = "Delete * From " + tableName + ";"; OdbcCommand command = new OdbcCommand(query); command.Connection = odbcConnection; int result = command.ExecuteNonQuery(); Console.Write($"{result} {tableName} records..."); } Console.Write("\n"); odbcConnection.Close(); } catch (Exception ex) { Console.WriteLine(ex.Message); } //Call compact and repair after cleaning the tables. CompactAndRepair(file); } else { var engine = new DBEngine(); var dbs = engine.CreateDatabase(input.CombinedOutputFileName, ";LANGID=0x0409;CP=1252;COUNTRY=0", DatabaseTypeEnum.dbVersion150); dbs.Close(); dbs = null; Console.WriteLine($"Created {input.CombinedOutputFileName}."); } }
public static ECollectionLoggerType GetList() { SqlDataReader oReader = null; try { //Initialize the return object ECollectionLoggerType oCollData = new ECollectionLoggerType(); //Call the request using (DBEngine DBInstance = CCstData.GetInstance("").DatabaseEngine) { oReader = DBInstance.ExecuteReader(CommandType.StoredProcedure, CCstDatabase.SP_LoggerType_GetList); } //If there is a result (not null) if (oReader != null) { while (oReader.Read()) { ELoggerType oData = new ELoggerType(); //Read the data and convert the SqlDataReader in the waiting object oData = ReadData(oReader); //Add the data to the return list oCollData.Add(oData); } } return(oCollData); } catch (Exception e) { throw e; } finally { if (oReader != null && !oReader.IsClosed) { oReader.Close(); } } }
private void menuOpen_Click(object sender, EventArgs e) { try { DBEngine dbeng = new DBEngine(); openDiagDBFile.ShowDialog(); Database mydb = dbeng.OpenDatabase(openDiagDBFile.FileName); wizardTable openTables = new wizardTable(openDiagDBFile.FileName, mydb, true); openTables.MdiParent = this; openTables.Show(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private static void EZLog(string Action, string keyName, string oldValue, string newValue, string TableName, string ASSEMBLY_NAME, string formName, object userID, string strEmployeeID) { try { DBEngine.exec("sp_EZLogMasterData", "@Action", Action, "@KeyName", keyName, "@EmployeeID", strEmployeeID, "@OldValue", oldValue, "@NewValue", newValue, "@FunctionClassName", string.Format("{0}.{1}", ASSEMBLY_NAME, TableName), "@ScreenName", formName, "@LoginID", userID); } catch (Exception ex) { throw ex; } }
public void insertData(DBEngine<int, DBElement<int, string>> db) { DBElement<int, string> elem1 = new DBElement<int, string>(); elem1.name = "Usain Bolt"; elem1.descr = "Athelte"; elem1.timeStamp = DateTime.Now; elem1.children.AddRange(new List<int> { 2 }); elem1.payload = "Fastest in the world"; db.insert(1, elem1); DBElement<int, string> elem2 = new DBElement<int, string>(); elem2.name = "Saina Nehwal"; elem2.descr = "Badminton Player"; elem2.timeStamp = DateTime.Now; elem2.children.AddRange(new List<int> { 1 }); elem2.payload = "Famous badminton player"; db.insert(2, elem2); db.showDB(); WriteLine(); }
private void 压缩数据库ToolStripMenuItem_Click(object sender, EventArgs e) { string accessFile = "iReminder.mdb"; string tempFile = Path.Combine(Path.GetDirectoryName(accessFile), Path.GetRandomFileName() + Path.GetExtension(accessFile)); var dbe = new DBEngine(); try { dbe.CompactDatabase(accessFile, tempFile); FileInfo temp = new FileInfo(tempFile); temp.CopyTo(accessFile, true); temp.Delete(); } catch (Exception e1) { Console.WriteLine("Error: " + e1.Message); } MessageBox.Show("完成压缩!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); }
public Login() { InitializeComponent(); //Show last user name txtUserName.Text = StaticVars.UserName; if (!txtUserName.Text.Trim().Equals(string.Empty)) { try { DataTable dtLoginImage = DBEngine.execReturnDataTable("SC_GetLoginImage", "@LoginName", txtUserName.Text.Trim()); picLoginPic.DataBindings.Clear(); picLoginPic.DataBindings.Add(CommonConst.EDIT_VALUE, dtLoginImage, "PhotoImage"); } catch (Exception ex) { Methods.ShowError(ex); } } txtPassword.Focus(); }
public static string Get_Message(object ID) { object obj; try { DBEngine.exec(StoreProcName, StoreProcParamMessageID, ID.ToString(), StoreProcParamLanguage, UIMessage.languageID); obj = DBEngine.getParamValue(StoreProcParamOutName); if (obj.ToString().Trim().Equals(string.Empty)) { return(string.Format("{0}: LangID = {1}", ID, UIMessage.languageID)); } } catch (Exception ex) { throw ex; } return(obj.ToString()); }
private void button2_Click(object sender, RoutedEventArgs e) { // preview data query test // save some content data DBEngine _dbEngine = App.EngineInstance.GetDBEngine; var q = from p in _dbEngine.CmtvDBContext.PreviewData_items from c in _dbEngine.CmtvDBContext.Content_items where p.FragmentID == c.ID select p; string str = ""; foreach (var v in q) { str += "||" + v.Text + " " + v.ID; } MessageBox.Show(str); }
/* Defining a query using lambda function to search specific key */ public bool key_value_search(DBEngine<string, DBElement<string, List<string>>> db, out IQuery<string, DBElement<string, List<string>>> i_query, QueryEngine<string, DBElement<string, List<string>>> qe, string key_to_search = "12345") { "Query for value with specified key (key = element2):".title(); WriteLine(); Func<string, string, bool> keyValueSearch = (string key, string search) => //lambda function { if (!db.Keys().Contains(key)) return false; else { if (key == (search)) { DBElement<string, List<string>> ele = new DBElement<string, List<string>>(); db.getValue(key, out ele); return true; } else { return false; } } }; // pass query to query engine and call simpleQuery to make query on DBEngine if (qe.simpleQuery(keyValueSearch, key_to_search.ToString(), out i_query)) { WriteLine(); foreach (var key in i_query.Keys()) { DBElement<string, List<string>> temp = new DBElement<string, List<string>>(); i_query.getValue(key, out temp); WriteLine("key : {0}", key); temp.showEnumerableElement(); WriteLine(); } return true; } else { return false; } }
static void Main(string[] args) { /* * Create and edit a DBEngine first. * Then create a DBFactory using the DBEngine. */ "Testing DBEngine Package".title('='); WriteLine(); Write("\n --- Test DBElement<int,string> ---"); DBElement<int, string> elem1 = new DBElement<int, string>(); elem1.payload = "a payload"; Write(elem1.showElement<int, string>()); WriteLine(); DBElement<int, string> elem2 = new DBElement<int, string>("Darth Vader", "Evil Overlord"); elem2.payload = "The Empire strikes back!"; Write(elem2.showElement<int, string>()); WriteLine(); int key = 0; Func<int> keyGen = () => { ++key; return key; }; // anonymous function to generate keys DBEngine<int, DBElement<int, string>> db = new DBEngine<int, DBElement<int, string>>(); bool p1 = db.insert(keyGen(), elem1); bool p2 = db.insert(keyGen(), elem2); Write("\n --- Create DBFactory<int, DBElement<int, string>> from DBEngine<int,DBElement<int, string>> ---"); DBFactory<int, DBElement<int, string>> dbFactory = new DBFactory<int, DBElement<int, string>>(db); foreach (int dbKey in dbFactory.Keys()) { DBElement<int, string> value; dbFactory.getValue(dbKey, out value); value.showElement(); } dbFactory.showDB(); Write("\n\n"); }
public void XMLWriteLOS(DBEngine<string, DBElement<string, List<string>>> dbLOS, out string pathnameLOS) { pathnameLOS = "xmlDocLOS.xml"; XDocument docLOS = new XDocument(new XElement("nosqldbLOS")); docLOS.Declaration = new XDeclaration("1.0", "utf - 8", "yes"); XElement keyTypeLOS = new XElement("keytype", "string"); XElement payloadTypeLOS = new XElement("payloadtype", "ListOfString"); docLOS.Root.Add(keyTypeLOS); docLOS.Root.Add(payloadTypeLOS); DBElement<string, List<string>> ValLOS = new DBElement<string, List<string>>(); foreach (var keyLOS in dbLOS.Keys()) { XElement keyNodeLOS = new XElement("key", keyLOS); dbLOS.getValue(keyLOS, out ValLOS); XElement elementNodeLOS = new XElement("element"); elementNodeLOS.Add(new XElement("name", ValLOS.name)); elementNodeLOS.Add(new XElement("descr", ValLOS.descr)); elementNodeLOS.Add(new XElement("timeStamp", ValLOS.timeStamp.ToString())); XElement childrenNodeLOS = new XElement("children"); foreach (var item in ValLOS.children) { childrenNodeLOS.Add(new XElement("key", item)); } elementNodeLOS.Add(childrenNodeLOS); XElement payloadNodeLOS = new XElement("payload"); //since payload is List<string> for this type of database foreach (var item in ValLOS.payload) { payloadNodeLOS.Add(new XElement("item", item)); } elementNodeLOS.Add(payloadNodeLOS); docLOS.Root.Add(keyNodeLOS); docLOS.Root.Add(elementNodeLOS); } docLOS.Save(pathnameLOS); }
public Schedular(DBEngine<int, DBElement<int, string>> db) { //setting time interval for persisting of data schedular.Interval = 2000; schedular.AutoReset = true; schedular.Enabled = true; //defining method to be called when elapsed event occurs //this method persists data into xml file from DBEngine. schedular.Elapsed += (object source, ElapsedEventArgs e) => { if (count++ < 5) { "Persisting to Test_DB.xml file".title(); db.create_xml_from_db(true); } else { "Stopped persisting to test_DB.xml file".title(); schedular.Enabled = false; } }; }
public void insertData(DBEngine<int, DBElement<int, string>> db) { DBElement<int, string> elem1 = new DBElement<int, string>(); elem1.name = "India"; elem1.descr = "Country"; elem1.timeStamp = DateTime.Now; elem1.children.AddRange(new List<int> { 2, 3 }); elem1.payload = "Famous cricket player"; db.insert(1, elem1); DBElement<int, string> elem2 = new DBElement<int, string>(); elem2.name = "Roger federer"; elem2.descr = "Tennis player"; elem2.timeStamp = DateTime.Now.AddDays(-15); elem2.children.AddRange(new List<int> { 3 }); elem2.payload = "Famous tennis player"; db.insert(2, elem2); DBElement<int, string> elem3 = new DBElement<int, string>(); elem3.name = "Usain Bolt"; elem3.descr = "Athelte"; elem3.timeStamp = DateTime.Now; elem3.children.AddRange(new List<int> { 1 }); elem3.payload = "Fastest in the world"; db.insert(3, elem3); DBElement<int, string> elem4 = new DBElement<int, string>(); elem4.name = "Saina Nehwal"; elem4.descr = "Badminton Player"; elem4.timeStamp = DateTime.Now; elem4.children.AddRange(new List<int> { 2 }); elem4.payload = "Famous badminton player"; db.insert(4, elem4); db.showDB(); WriteLine(); }
static void Main(string[] args) { "Demonstrate Timer - needed for scheduled persistance in Project #2".title('='); Console.Write("\n\n press any key to exit\n"); DBEngine<int, DBElement<int, string>> db = new DBEngine<int, DBElement<int, string>>(); for (int i = 0; i < 3; i++) { DBElement<int, string> elem = new DBElement<int, string>(); elem.name = "element"; elem.descr = "test element"; elem.timeStamp = DateTime.Now; elem.children.AddRange(new List<int> { 1, 2, 3 }); elem.payload = "elem's payload"; elem.showElement(); db.insert(i, elem); } db.showDB(); WriteLine(); Schedular td = new Schedular(db); td.schedular.Enabled = true; Console.ReadKey(); Console.Write("\n\n"); }
static void Main(string[] args) { "Testing DBEngine Package".title('='); WriteLine(); Write("\n --- Test DBElement<int,string> ---"); DBElement<int, string> elem1 = new DBElement<int, string>(); elem1.payload = "a payload"; Write(elem1.showElement<int, string>()); WriteLine(); DBElement<int, string> elem2 = new DBElement<int, string>("Darth Vader", "Evil Overlord"); elem2.payload = "The Empire strikes back!"; Write(elem2.showElement<int, string>()); WriteLine(); var elem3 = new DBElement<int, string>("Luke Skywalker", "Young HotShot"); elem3.children.AddRange(new List<int> { 1, 5, 23 }); elem3.payload = "X-Wing fighter in swamp - Oh oh!"; Write(elem3.showElement<int, string>()); WriteLine(); Write("\n --- Test DBEngine<int,DBElement<int,string>> ---"); int key = 0; Func<int> keyGen = () => { ++key; return key; }; // anonymous function to generate keys DBEngine<int, DBElement<int, string>> db = new DBEngine<int, DBElement<int, string>>(); bool p1 = db.insert(keyGen(), elem1); bool p2 = db.insert(keyGen(), elem2); bool p3 = db.insert(keyGen(), elem3); if (p1 && p2 && p3) Write("\n all inserts succeeded"); else Write("\n at least one insert failed"); db.show<int, DBElement<int, string>, string>(); WriteLine(); Write("\n --- Test DBElement<string,List<string>> ---"); DBElement<string, List<string>> newelem1 = new DBElement<string, List<string>>(); newelem1.name = "newelem1"; newelem1.descr = "test new type"; newelem1.payload = new List<string> { "one", "two", "three" }; Write(newelem1.showElement<string, List<string>>()); WriteLine(); Write("\n --- Test DBElement<string,List<string>> ---"); DBElement<string, List<string>> newerelem1 = new DBElement<string, List<string>>(); newerelem1.name = "newerelem1"; newerelem1.descr = "better formatting"; newerelem1.payload = new List<string> { "alpha", "beta", "gamma" }; newerelem1.payload.Add("delta"); newerelem1.payload.Add("epsilon"); Write(newerelem1.showElement<string, List<string>, string>()); WriteLine(); DBElement<string, List<string>> newerelem2 = new DBElement<string, List<string>>(); newerelem2.name = "newerelem2"; newerelem2.descr = "better formatting"; newerelem1.children.AddRange(new[] { "first", "second" }); newerelem2.payload = new List<string> { "a", "b", "c" }; newerelem2.payload.Add("d"); newerelem2.payload.Add("e"); Write(newerelem2.showElement<string, List<string>, string>()); WriteLine(); Write("\n --- Test DBEngine<string,DBElement<string,List<string>>> ---"); int seed = 0; string skey = seed.ToString(); Func<string> skeyGen = () => { ++seed; skey = "string" + seed.ToString(); skey = skey.GetHashCode().ToString(); return skey; }; DBEngine<string, DBElement<string, List<string>>> newdb = new DBEngine<string, DBElement<string, List<string>>>(); newdb.insert(skeyGen(), newerelem1); newdb.insert(skeyGen(), newerelem2); newdb.show<string, DBElement<string, List<string>>, List<string>, string>(); WriteLine(); "testing edits".title(); db.show<int, DBElement<int, string>, string>(); DBElement<int, string> editElement = new DBElement<int, string>(); db.getValue(1, out editElement); editElement.showElement<int, string>(); editElement.name = "editedName"; editElement.descr = "editedDescription"; db.show<int, DBElement<int, string>, string>(); Write("\n\n"); }
static void Main(string[] args) { "Testing DBEngine Package".title('='); ; WriteLine(); "Test db of scalar elements".title(); WriteLine(); //creation of new elements DBElement<int, string> elem1 = new DBElement<int, string>(); elem1.payload = "a payload"; DBElement<int, string> elem2 = new DBElement<int, string>("Darth Vader", "Evil Overlord"); elem2.payload = "The Empire strikes back!"; var elem3 = new DBElement<int, string>("Luke Skywalker", "Young HotShot"); elem3.payload = "X-Wing fighter in swamp - Oh oh!"; if (verbose) { Write("\n --- Test DBElement<int,string> ---"); WriteLine(); elem1.showElement(); WriteLine(); elem2.showElement(); WriteLine(); elem3.showElement(); WriteLine(); } Write("\n --- Test DBEngine<int,DBElement<int,string>> ---"); WriteLine(); int key = 0; Func<int> keyGen = () => { ++key; return key; }; // function to generate keys // new database created DBEngine<int, DBElement<int, string>> db = new DBEngine<int, DBElement<int, string>>(); bool p1 = db.insert(keyGen(), elem1); bool p2 = db.insert(keyGen(), elem2); bool p3 = db.insert(keyGen(), elem3); if (p1 && p2 && p3) Write("\n all inserts succeeded"); else Write("\n at least one insert failed"); db.showDB(); WriteLine(); "Test db of enumerable elements".title(); WriteLine(); //new element created DBElement<string, List<string>> newelem1 = new DBElement<string, List<string>>(); newelem1.name = "newelem1"; newelem1.descr = "test new type"; newelem1.payload = new List<string> { "one", "two", "three" }; //new element created DBElement<string, List<string>> newerelem1 = new DBElement<string, List<string>>(); newerelem1.name = "newerelem1"; newerelem1.descr = "better formatting"; newerelem1.payload = new List<string> { "alpha", "beta", "gamma" }; newerelem1.payload.Add("delta"); newerelem1.payload.Add("epsilon"); //new element created DBElement<string, List<string>> newerelem2 = new DBElement<string, List<string>>(); newerelem2.name = "newerelem2"; newerelem2.descr = "better formatting"; newerelem2.children.AddRange(new List<string> { "first", "second" }); newerelem2.payload = new List<string> { "a", "b", "c" }; newerelem2.payload.Add("d"); newerelem2.payload.Add("e"); if (verbose) { Write("\n --- Test DBElement<string,List<string>> ---"); WriteLine(); newelem1.showEnumerableElement(); WriteLine(); newerelem1.showEnumerableElement(); WriteLine(); newerelem2.showEnumerableElement(); WriteLine(); } Write("\n --- Test DBEngine<string,DBElement<string,List<string>>> ---"); int seed = 0; string skey = seed.ToString(); Func<string> skeyGen = () => { ++seed; skey = "string" + seed.ToString(); skey = skey.GetHashCode().ToString(); return skey; }; DBEngine<string, DBElement<string, List<string>>> newdb = new DBEngine<string, DBElement<string, List<string>>>(); newdb.insert(skeyGen(), newelem1); newdb.insert(skeyGen(), newerelem1); newdb.insert(skeyGen(), newerelem2); newdb.showEnumerableDB(); Write("\n\n"); }
// function to delete from database public XElement Delete(XElement dbe, DBEngine<int, DBElement<int, string>> db) { DBElement<int, string> elem = new DBElement<int, string>(); Console.WriteLine("\n----------Delete Operation----------"); Console.Write("\n Now deleting the element with key=3"); bool result = db.remove(Int32.Parse((dbe.Element("key").Value))); db.showDB(); if (result == true) { XElement s = new XElement("result", "\n Element deleted successfully "); return s; } else { XElement f = new XElement("result", "Failure"); return f; } }
// test stub for processor // main function static void Main(string[] args) { DBEngine<int, DBElement<int, string>> db = new DBEngine<int, DBElement<int, string>>(); "Testing the Package".title('='); Console.WriteLine(); Console.WriteLine("\n remote operations are done are and tested"); Console.Write("\n"); DBElement<int, string> elem = new DBElement<int, string>(); Console.WriteLine("\n----------Delete Operation----------"); Console.Write("\n Now deleting the element with key=3"); bool result = db.remove(2); db.showDB(); if (result == true) { XElement s = new XElement("result", "\n Element deleted successfully "); } else { XElement f = new XElement("result", "Failure"); } }
// function to getchildren public XElement getchildren(XElement dbe, DBEngine<int, DBElement<int, string>> db, QueryEngine QE) { Console.WriteLine("\n The children List is obtained "); QE.querychildren<int, DBElement<int, string>, string>(db, 1); if (QE.Equals(null)) { XElement f = new XElement("result", " no children in list "); return f; } else { XElement s = new XElement("result", " children obtained from the specified key "); return s; } }