//----< process edit message request >----- public string processEditMessage(XDocument xdoc) { string content = ""; IEnumerable <string> keys = db.Keys(); List <string> keyList = keys.ToList(); string keyToEdit = getKey(xdoc); if (!keyList.Contains(keyToEdit)) { Console.WriteLine("Key {0} is not present in the DB", keyToEdit); } else { int type = getKeyValueType(xdoc); if (type == 1) { DBElement <string, List <string> > element = new DBElement <string, List <string> >(); string key = createAddDBElement(xdoc, out element); if (db.edit(key, element)) { content = key + " record is edited Successfully."; } else { content = key + " record is not edited."; } } } return(content); }
public void processDelMsg(XDocument xdoc, Sender sndr, Message msg) { IEnumerable <string> keys = db.Keys(); int numKeys = Convert.ToInt32(getNumberOfKeys(xdoc)); if (numKeys > keys.Count()) { numKeys = keys.Count() - 1; } List <string> keyList = keys.ToList(); for (int i = 0; i < numKeys; i++) { string keyToDeleted = keyList.ElementAt(i); if (db.delete(keyToDeleted)) { msg.content = "\n\n***************************\n" + keyToDeleted + " record is deleted.\n"; } else { msg.content = "\n*********************\n" + keyToDeleted + " record is not deleted."; } Message testMsg = new Message(); testMsg.toUrl = msg.fromUrl; testMsg.fromUrl = msg.toUrl; testMsg.content = msg.content; sndr.sendMessage(testMsg); } }
/*-------------------Query for particular pattern in keys------------------*/ public List <int> getListKeyPattern() { try { List <Key> keyList = new List <Key>(db.Keys()); List <int> ikeys = new List <int>(); List <int> kpKeys = new List <int>(); if (keyList != null) { foreach (var item in keyList) { ikeys.Add(Convert.ToInt32(item)); } foreach (int i in ikeys) { if (i % 2 == 0) //returning the keys which are even { kpKeys.Add(i); } } } else { WriteLine("\nKeys are not present in the dictionary\n"); } return(kpKeys); } catch (Exception e) { Console.WriteLine("\n" + e.Message + "\n"); return(default(List <int>)); } }
public string processDataRestoreMessageRequest() { string content = ""; try { PersistData <string, List <string> > persistEngine = new PersistData <string, List <string> >(); DBEngine <string, DBElement <string, List <string> > > restoreData = new DBEngine <string, DBElement <string, List <string> > >(); persistEngine.restoreData(restoreData, "PersistData.xml"); if (restoreData.Keys().Count() > 0) { content = "\nDatabase restored successfully from PersistData.xml"; } else { content = "\nDatabase restore failed"; } } catch (Exception e) { Console.Write(" Exception : " + e.StackTrace); content = "\nDatabase restore failed"; } return(content); }
public List <string> metaDataPattern(string pattern, DBEngine <string, DBElement <string, List <string> > > db) { List <string> foundKeys = new List <string>(); IEnumerable <string> keys = db.Keys(); foreach (string key in keys) { DBElement <string, List <string> > elem = new DBElement <string, List <string> >(); db.getValue(key, out elem); if (elem.name.Contains(pattern)) { foundKeys.Add(key); } else if (elem.descr.Contains(pattern)) { foundKeys.Add(key); } else if (elem.timeStamp.ToString().Contains(pattern)) { foundKeys.Add(key); } } if (foundKeys.Count == 0) { return(null); } else { return(foundKeys); } }
public List <string> dateTimeSearch(DateTime fromDate, DateTime toDate, DBEngine <string, DBElement <string, List <string> > > db) { if (toDate == default(DateTime)) { toDate = DateTime.Now; } List <string> foundKeys = new List <string>(); IEnumerable <string> keys = db.Keys(); foreach (string key in keys) { DBElement <string, List <string> > elem = new DBElement <string, List <string> >(); db.getValue(key, out elem); if (elem.timeStamp <= toDate && elem.timeStamp > fromDate) { foundKeys.Add(key); } } if (foundKeys.Count == 0) { return(null); } else { return(foundKeys); } }
//-------< Get keys of DBElements containing a pattern in the metadata section >------------- public List <Key> get_keys_with_metadata <Key, Value, Data>(DBEngine <Key, Value> db, string pat) { List <Key> key_collection = new List <Key>(); foreach (Key key in db.Keys()) { Value value; db.getValue(key, out value); DBElement <Key, Data> elem = value as DBElement <Key, Data>; if (elem.name.Contains(pat) || elem.descr.Contains(pat) || elem.timeStamp.ToString().Contains(pat)) { key_collection.Add(key); } else if (elem.children.Count() > 0) { foreach (Key x in elem.children) { if (x.ToString().Contains(pat)) { key_collection.Add(key); } } } } if (key_collection.Count > 0) { return(key_collection); } else { return(default(List <Key>)); } }
public List <Key> keyPattern(string pattern, DBEngine <string, DBElement <string, List <string> > > db) { List <Key> foundKeys = new List <Key>(); IEnumerable <string> keys = db.Keys(); foreach (string key in keys) { if (Regex.IsMatch(key, pattern)) { foundKeys.Add((Key)Convert.ChangeType(key, typeof(Key))); } } foreach (Key key1 in foundKeys) { if (foundKeys.Count == 0) { Key str = (Key)Convert.ChangeType("No match found - returning all keys", typeof(Key));//"No match found - returning all keys"; foundKeys.Insert(0, str); return(foundKeys); } } return(foundKeys); }
public static void restoreDatabase(this DBEngine <string, DBElement <string, List <string> > > dbEngine) { XDocument xmlDoc = XDocument.Load(xmlLocation + restoreXmlName + ".xml"); "XML to be augumented".title('_'); Console.WriteLine("{0}", xmlDoc.ToString()); var results = xmlDoc.Descendants("element").Select(p => new DBElement <string, List <string> > { name = p.Descendants("name").FirstOrDefault().Value, descr = p.Descendants("description").FirstOrDefault().Value, payload = p.Descendants("payload").Select(q => { return(q.Value); }).ToList(), children = p.Descendants("children").Descendants("child").Select(q => { return(q.Value); }).ToList(), key = p.Descendants("key").FirstOrDefault().Value, dbOperation = p.Descendants("dbOperation").FirstOrDefault().Value }); var keys = dbEngine.Keys(); foreach (var result in results) { //ToDo: Check if already present in DB dbEngine.insert(result.key, result); //toDo: Update the persisted file with new DB contents } //Update Xml with new DB toXml(dbEngine); }
/* * Persist data which resides in db engine that would be save in xml as per scheduler configuation. */ public void persistDatatoXML(ref DBEngine <Key, DBElement <Key, Value> > dbEngine) { IEnumerable <Key> keysCollection = dbEngine.Keys().ToList(); foreach (Key item in keysCollection) { addRecord(item, dbEngine.Dictionary[item]); } }
/// <summary> /// To the XML string. /// </summary> /// <param name="dbEngine">The database engine.</param> /// <returns></returns> private String ToXmlString(DBEngine <string, DBElement <string, List <String> > > dbEngine) { dynamic dict = dbEngine.Keys(); XDocument xmlDoc = new XDocument(); XElement root = new XElement("noSqlDb"); xmlDoc.Add(root); return(xmlDoc.ToString()); }
private static string schedulerXmlFilename = "schedulerXml.xml"; //constant defined for scheduled saved XML file name. //<----------method to write an XML for <int,string> database-------------> public void createStringXML(DBEngine <int, DBElement <int, string> > db, bool isScheduledCall) { XDocument xml = new XDocument(); xml.Declaration = new XDeclaration("1.0", "utf-8", "yes"); XComment xmlComment = new XComment("XML document of type int-string"); xml.Add(xmlComment); XElement root = new XElement("noSqlInput"); xml.Add(root); XElement keyType = new XElement("keytype"); keyType.SetValue("int"); XElement payloadType = new XElement("payloadtype"); payloadType.SetValue("string"); root.Add(keyType); root.Add(payloadType); string absolutePath = Path.GetFullPath(xmlFilename); foreach (int key in db.Keys()) { XElement node = new XElement("node"); XElement keynode = new XElement("key", key.ToString()); node.Add(keynode); XElement name = new XElement("name", db.Dictionary[key].name); XElement desc = new XElement("desc", db.Dictionary[key].descr); XElement timestamp = new XElement("timestamp", db.Dictionary[key].timeStamp.ToString()); XElement payload = new XElement("payload", db.Dictionary[key].payload); XElement element = populateElementForXML(db, key, name, desc, timestamp, payload); node.Add(element); root.Add(node); } try { if (isScheduledCall) { absolutePath = Path.GetFullPath(schedulerXmlFilename); xml.Save(schedulerXmlFilename); } else { xml.Save(xmlFilename); } WriteLine("\nFile saved at: " + absolutePath); } catch (DirectoryNotFoundException ex) { WriteLine("Directory not found. Provided path is incorrect" + ex.Message); } catch (Exception ex) { WriteLine("Error occured while saving the XML on file system" + ex.Message); } }
//<----------method to write an XML for <string,List<string>> database-------------> public bool createListStringXML(DBEngine <string, DBElement <string, List <string> > > dbl) { XDocument xml = new XDocument(); xml.Declaration = new XDeclaration("1.0", "utf-8", "yes"); XComment xmlComment = new XComment("XML document of type int-string"); xml.Add(xmlComment); XElement root = new XElement("noSqlInput"); xml.Add(root); XElement keyType = new XElement("keytype"); keyType.SetValue("string"); XElement payloadType = new XElement("payloadtype"); payloadType.SetValue("list of strings"); root.Add(keyType); root.Add(payloadType); string absolutePath = Path.GetFullPath(listStringXmlFilename); //WriteLine("\nFile saved at: " + absolutePath); foreach (string key in dbl.Keys()) { XElement node = new XElement("node"); XElement keynode = new XElement("key", key.ToString()); node.Add(keynode); XElement name = new XElement("name", dbl.Dictionary[key].name); XElement desc = new XElement("desc", dbl.Dictionary[key].descr); XElement timestamp = new XElement("timestamp", dbl.Dictionary[key].timeStamp.ToString()); XElement payload = new XElement("payload"); foreach (string load in dbl.Dictionary[key].payload) { XElement item = new XElement("item", load); payload.Add(item); } XElement element = populateElementForStringXml(dbl, key, name, desc, timestamp, payload); node.Add(element); root.Add(node); } try { xml.Save(listStringXmlFilename); return(true); } catch (DirectoryNotFoundException ex) { WriteLine("Directory not found. Provide path is incorrect" + ex.Message); } catch (Exception ex) { WriteLine("Error occured while saving the XML on file system" + ex.Message); } return(false); }
//----< write simple db elements out to Console >------------------ public static void show <Key, Value, Data>(this DBEngine <Key, Value> db) { foreach (Key key in db.Keys()) { Value value; db.getValue(key, out value); DBElement <Key, Data> elem = value as DBElement <Key, Data>; Write("\n\n -- key = {0} --", key); Write(elem.showElement()); } }
// delegate for keypattern query. public Func <Key, bool> defineQueryKeyPatternSearch(string str = ".*") { Func <Key, bool> queryPredicate = (Key key) => { if (!db.Keys().Contains(key)) { return(false); } else { try { if (Regex.IsMatch(key.ToString(), str)) { return(true); } } catch (Exception ex) { WriteLine("\n Invalid Regular Expression. Error Message : {0}\n", ex.Message); return(false); } } return(false); }; return(queryPredicate); }
//this function is generic for querying values or keys or timestamps //you just need to define a rule or predicate public List <Key> processMatchQuery(Func <Key, bool> queryPredicate, DBEngine <Key, DBElement <Key, Data> > dbEngine) { List <Key> keys = new List <Key>(); IEnumerable <Key> keysCollection = dbEngine.Keys(); foreach (var item in keysCollection) { if (queryPredicate(item)) { keys.Add(item); } } return(keys); }
//----< write simple db elements out to Console >------------------ public static void show <Key, Value, Data>(this DBEngine <Key, Value> db) { "Displaying DB contents :".title('_'); foreach (Key key in db.Keys()) { Value value; db.getValue(key, out value); DBElement <Key, Data> elem = value as DBElement <Key, Data>; Write("\n\n -- key = {0} --", key); Write(elem.showElement()); Write("\n -- key = {0} --", key); } "".demarcation(); }
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:"); } }
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"); } }
//----< write enumerable db elements out to Console >-------------- public static string show <Key, Value, Data, T>(this DBEngine <Key, Value> db) where Data : IEnumerable <T> { StringBuilder displayString = new StringBuilder(); foreach (Key key in db.Keys()) { Value value; db.getValue(key, out value); DBElement <Key, Data> elem = value as DBElement <Key, Data>; displayString.Append("\n\n -- key = " + key + " --"); displayString.Append(elem.showElement <Key, Data, T>()); } return(displayString.ToString()); }
/*----------------------------------Category implementation----------------------------*/ public List <string> getKeyForCategory(DBEngine <string, DBElement <string, List <string> > > dbCat, List <string> category) { dynamic keys = dbCat.Keys(); List <string> matchedKeys = new List <string>(); foreach (var cat in category) { foreach (var key in keys) { if (cat == key) { matchedKeys.Add(key); } } } return(matchedKeys); }
public static List <Key> searchForKeyPattern <Key, Value>(this DBEngine <Key, DBElement <Key, Value> > dbEngine, string keyPattern) { List <Key> matchedKeys = new List <Key>(); dynamic keys = dbEngine.Keys(); DBElement <Key, Value> val; foreach (var key in keys) { dbEngine.getValue(key, out val); if ((Regex.IsMatch(key, keyPattern))) { matchedKeys.Add(key); } } return(matchedKeys); }
public static List <Key> searchMetadata <Key, Value>(this DBEngine <Key, DBElement <Key, Value> > dbEngine, string searchString) { List <Key> matchedKeys = new List <Key>(); dynamic keys = dbEngine.Keys(); DBElement <Key, Value> val; foreach (var key in keys) { dbEngine.getValue(key, out val); if (Regex.IsMatch(val.name, searchString) || Regex.IsMatch(val.descr, searchString)) { matchedKeys.Add(key); } } return(matchedKeys); }
public static List <string> searchForKeysInCategory(this DBEngine <string, DBElement <string, List <string> > > dbEngine, List <string> category) { List <string> matchedKeys = new List <string>(); dynamic keys = dbEngine.Keys(); foreach (var cat in category) { //dbEngine.getValue(cat, out val); foreach (var key in keys) { if (category.Contains(key)) { matchedKeys.Add(key); } } } return(matchedKeys); }
//persists data into XML by taking DBengine and file as argument public bool persistXML(DBEngine <Key, DBElement <Key, Data> > dbEngine) { fileName = @".\" + inputFile; string valueType = "ListOfStrings"; string keyType = "string"; loadXmlFile(); addKeyAndPayloadType(keyType, valueType); IEnumerable <Key> enums = dbEngine.Keys(); foreach (Key key in enums) { if (!addRecord(key, dbEngine.Dictionary[key])) { return(false); } } return(true); }
public static void toXml(this DBEngine <string, DBElement <string, List <string> > > dbEngine) { dynamic dict = dbEngine.Keys(); DBElement <string, List <string> > result; XDocument xmlDoc = new XDocument(); XElement root = new XElement("noSqlDb"); xmlDoc.Add(root); foreach (var key in dict) { dbEngine.getValue(key, out result); XElement element = new XElement("element"); root.Add(element); XElement keyValue = new XElement("key", key); element.Add(keyValue); XElement value = new XElement("value"); element.Add(value); XElement children = new XElement("children"); value.Add(children); foreach (var item in result.children) { XElement child = new XElement("child", item); children.Add(child); } XElement description = new XElement("description", result.descr); XElement name = new XElement("name"); name.SetValue(result.name); XElement timestamp = new XElement("timestamp", result.timeStamp); XElement payLoad = new XElement("payload"); value.Add(description); value.Add(name); value.Add(timestamp); value.Add(payLoad); foreach (var item in result.payload) { XElement load = new XElement("load", item); payLoad.Add(load); } } saveXml(xmlDoc); }
//-------< Get keys of DBElements written within a specified time interval >------------- public List <Key> get_keys_within_timeInterval <Key, Value, Data>(DBEngine <Key, Value> db, DateTime t1, DateTime t2 = default(DateTime)) { List <Key> key_collection = new List <Key>(); if (t2 == default(DateTime)) { t2 = DateTime.Now; } foreach (Key key in db.Keys()) { Value value; db.getValue(key, out value); DBElement <Key, Data> elem = value as DBElement <Key, Data>; if (DateTime.Compare(elem.timeStamp, t1) >= 0 && DateTime.Compare(elem.timeStamp, t2) <= 0) { key_collection.Add(key); } } return(key_collection); }
/*-------------------Function to implement scheduled save of database after every 5 seconds-------------------*/ public void scheduledSaveDatabase() { try { TimerDemo timer = new TimerDemo(); timer.schedular.Enabled = true; //Elapsed event is triggered Console.Write("\n\n Press any key to stop database persistence\n"); timer.schedular.Elapsed += (object source, ElapsedEventArgs e) => //persist database to xml every 5 sec { var keys = db.Keys(); persistToXML(keys); }; Console.ReadKey(); //persisted until a key is pressed by user timer.schedular.Enabled = false; } catch (Exception e) { WriteLine("\n" + e.Message + "\n"); } }
public void processAugmentedMsg(XDocument xdoc, Sender sndr, Message msg, Server srvr) { DBEngine <string, DBElement <string, List <string> > > dbEngine = new DBEngine <string, DBElement <string, List <string> > >(); srvr.getDatafromXML(dbEngine, "augment.xml"); Message testMsg = new Message(); testMsg.toUrl = msg.fromUrl; testMsg.fromUrl = msg.toUrl; if (dbEngine.Keys().Count() > 0) { //dbEngine.showEnumerableDB(); testMsg.content = "\n*****************************************\n" + "\nDatabase augmented successfully in Database instance: name - dbEngine "; } else { testMsg.content = "\nDatabase augmentation failed"; } sndr.sendMessage(testMsg); }
public static List <Key> searchForTimeStamp <Key, Value>(this DBEngine <Key, DBElement <Key, Value> > dbEngine, DateTime from, DateTime?to) { List <Key> matchedKeys = new List <Key>(); dynamic keys = dbEngine.Keys(); DBElement <Key, Value> val; if (!to.HasValue) { to = DateTime.Now; } foreach (var key in keys) { dbEngine.getValue(key, out val); if (val.timeStamp >= from && val.timeStamp <= to) { matchedKeys.Add(key); } } return(matchedKeys); }