public Action<Message> persistDB(DBEngine<int, DBElement<int, string>> db)
 {
     Action<Message> PersistDB = (msg) =>
     {
         IntAndString pe = new IntAndString(db);
         XDocument doc = XDocument.Parse(msg.content);
         string XmlFile = doc.Descendants("Msg").Descendants("Data").Descendants("FileName").ElementAt(0).Value;
         pe.writeToXML(XmlFile);
         msg.content = "Persist success";
         Utilities.swapUrls(ref msg);
         Console.Write("\n\n The database has been persisted");
     };
     return PersistDB;
 }
Exemplo n.º 2
0
        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());
        }
Exemplo n.º 4
0
        public Scheduler(DBEngine <int, DBElement <int, string> > db1, int time)
        {
            scheduler.Interval  = time;
            scheduler.AutoReset = true;

            // Note use of timer's Elapsed delegate, binding to subscriber lambda
            // This delegate is invoked when the internal timer thread has waited
            // for the specified Interval.

            scheduler.Elapsed += (object source, ElapsedEventArgs e) =>
            {
                c.writeToXML(db1);
                Console.Write("\n  an event occurred at {0}" + e.SignalTime);
            };
        }
 public Action<Message> restoreDB(DBEngine<string, DBElement<string, List<string>>> db)
 {
     Action<Message> RestoreDB = (msg) =>
     {
         StringAndStringList pe = new StringAndStringList(db);
         XDocument doc = XDocument.Parse(msg.content);
         string XmlFile = doc.Descendants("Msg").Descendants("Data").Descendants("FileName").ElementAt(0).Value;
         pe.writeToXML(XmlFile);
         Console.Write("\n\n ---The database has been restored ---");
         pe.persistDB.showEnumerableDB();
         msg.content = "Restore success";
         Utilities.swapUrls(ref msg);
     };
     return RestoreDB;
 }
Exemplo n.º 6
0
 //<-----------------Retrieves keys of all DBElements with pattern in metadata section.
 XElement keys_metada <Key, Data>(XElement request_msg, DBEngine <Key, DBElement <Key, Data> > db)
 {
     Console.Write("\n  Request to Query for DBElements");
     try
     {
         string pat = request_msg.Element("Pattern").Value;
         Console.WriteLine(" with pattern - \"{0}\" present in metadata.", pat);
         List <Key> result_list = sendQuery.get_keys_with_metadata <Key, DBElement <Key, Data>, Data>(db, pat);
         if (result_list == null)
         {
             XElement response_msg = new XElement("Query_Response");
             XElement type         = new XElement("Query_Type", "Get Keys metadata");
             string   rst          = "Could not find element with pattern - " + pat + " in metadata section";
             XElement result       = new XElement("Result", rst);
             response_msg.Add(type);
             response_msg.Add(result);
             return(response_msg);
         }
         else
         {
             XElement response_msg = new XElement("Query_Response");
             XElement type         = new XElement("Query_Type", "Get Keys metadata");
             XElement result       = new XElement("Result", "Success");
             string   list_num     = "  Number of DBElements with pattern - \"" + pat + "\" in metadat = " + result_list.Count;
             XElement par          = new XElement("Partial", list_num);
             XElement com          = new XElement("Complete");
             XElement data         = new XElement("Text", "  DBElements key list =");
             com.Add(data);
             foreach (Key child_k in result_list)
             {
                 string   child_space = " " + child_k.ToString();
                 XElement child_key   = new XElement("Key", child_space);
                 com.Add(child_key);
             }
             response_msg.Add(type);
             response_msg.Add(result);
             response_msg.Add(par);
             response_msg.Add(com);
             return(response_msg);
         }
     }
     catch (Exception)
     {
         Console.WriteLine("\n  XML file for request message is not in the expected format. A particular tag could not be found.");
         XElement response_msg = new XElement("Result", "Could not insert element into database");
         return(request_msg);
     }
 }
Exemplo n.º 7
0
        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();
        }
Exemplo n.º 8
0
 //<-------------------Retrieves child keys of a DBElement from database.
 XElement get_children <Key, Data>(XElement request_msg, DBEngine <Key, DBElement <Key, Data> > db)
 {
     Console.Write("\n  Request to Query for children of DB Element ");
     try
     {
         Key k = (Key)Convert.ChangeType(request_msg.Element("Key").Value, typeof(Key));
         Console.WriteLine(" with key - {0}", k);
         List <Key> result_list = sendQuery.getChildren <Key, DBElement <Key, Data>, Data>(db, k);
         if (result_list == null)
         {
             XElement response_msg = new XElement("Query_Response");
             XElement type         = new XElement("Query_Type", "Get Children");
             string   rst          = "Could not find element with key - " + k.ToString() + " in database.";
             XElement result       = new XElement("Result", rst);
             response_msg.Add(type);
             response_msg.Add(result);
             return(response_msg);
         }
         else
         {
             XElement response_msg = new XElement("Query_Response");
             XElement type         = new XElement("Query_Type", "Get Children");
             XElement result       = new XElement("Result", "Success");
             string   list_num     = "  Number of keys present in children list of DBelement with key - " + k.ToString() + " = " + result_list.Count;
             XElement par          = new XElement("Partial", list_num);
             XElement com          = new XElement("Complete");
             XElement data         = new XElement("Text", "  Key list =");
             com.Add(data);
             foreach (Key child_k in result_list)
             {
                 string   child_space = " " + child_k.ToString();
                 XElement child_key   = new XElement("Key", child_space);
                 com.Add(child_key);
             }
             response_msg.Add(type);
             response_msg.Add(result);
             response_msg.Add(par);
             response_msg.Add(com);
             return(response_msg);
         }
     }
     catch (Exception)
     {
         Console.WriteLine("\n  XML file for request message is not in the expected format. A particular tag could not be found.");
         XElement response_msg = new XElement("Result", "Could not insert element into database");
         return(request_msg);
     }
 }
        private void test2()
        {
            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);
            };
            int        key    = 0;
            Func <int> keyGen = () => { ++key; return(key); };
            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();
        }
        public static List <Key> searchChildren <Key, Value>(this DBEngine <Key, DBElement <Key, Value> > dbEngine, Key key)
        {
            List <Key>             children = new List <Key>();
            DBElement <Key, Value> val;

            if (dbEngine.containsKey(key))
            {
                dbEngine.getValue(key, out val);
                foreach (var child in val.children)
                {
                    children.Add(child);
                }
                return(children);
            }
            return(children);
        }
Exemplo n.º 11
0
        //-------< Edit description of a particular DB-element >--------------------
        public static bool editDescr <Key, Value, Data>(this DBEngine <Key, Value> db_edit, Key key1, string new_descr)
        {
            Value value;

            if (db_edit.getValue(key1, out value))
            {
                DBElement <Key, Data> elem = value as DBElement <Key, Data>;
                elem.descr     = new_descr;
                elem.timeStamp = DateTime.Now;
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 12
0
        //-------< Replace payload of a particular DB-element with a new payload.>--------------------
        public static bool editInstance <Key, Value, Data>(this DBEngine <Key, Value> db_edit, Key key1, Data new_instance)
        {
            Value value;

            if (db_edit.getValue(key1, out value))
            {
                DBElement <Key, Data> elem = value as DBElement <Key, Data>;
                elem.payload   = new_instance;
                elem.timeStamp = DateTime.Now;
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            "Testing DBFactory Package".title('=');
            WriteLine();
            DBFactoryTest dbft = new DBFactoryTest();

            "\nCreation of immutable database".title();
            WriteLine();

            "\nOriginal database".title();
            DBEngine <int, DBElement <int, string> > db = new DBEngine <int, DBElement <int, string> >();

            dbft.insertData(db);


            "\n Fetch all the keys which are even from the above database".title();
            try
            {
                QueryEngine <int, DBElement <int, string> > qEngine     = new QueryEngine <int, DBElement <int, string> >(db);
                Dictionary <int, DBElement <int, string> >  dictFactory = new Dictionary <int, DBElement <int, string> >();
                DBFactory <int, DBElement <int, string> >   dbFactory;
                var keys = qEngine.getListKeyPattern();
                if (keys != null)
                {
                    foreach (var key in keys)
                    {
                        var val = db.getValueOfKey(key);
                        dictFactory.Add(key, val);                                                              //add keys and values to the dictionary
                    }
                    dbFactory = new DBFactory <int, DBElement <int, string> >(dictFactory);                     //store the dictionary in the
                    WriteLine("\nThe below key/value pairs with even keys pattern are saved as an immutable database\n");
                    dbFactory.showDB();                                                                         //display the immutable database
                    WriteLine();
                    WriteLine();
                }
                else
                {
                    WriteLine("\nNo keys are obtained from a query for creation of immutable database\n");
                }
                WriteLine();
                WriteLine();
            }
            catch (Exception e)
            {
                Console.WriteLine("\n" + e.Message + "\n");
            }
        }
Exemplo n.º 14
0
        /*
         * Retrive data from xml file. augmented in DBEngine.
         */
        public void retrieveDataFromXML(DBEngine <int, DBElement <int, ListOfStrings> > dbEngine, String inputFile)
        {
            fileName = inputFile;
            var elem = from c in document.Descendants("elements") select c;

            for (int i = 0; i < elem.Elements().Count(); i++)
            {
                DBElement <int, ListOfStrings> dbElement = new DBElement <int, ListOfStrings>();
                int key = Int32.Parse(elem.Elements().Attributes().ElementAt(i).Value);

                for (int count = 0; count < elem.Elements().Attributes().ElementAt(i).Parent.Descendants().Count(); count++)
                {
                    XElement elementRecord = elem.Elements().Attributes().ElementAt(i).Parent.Descendants().ElementAt(count);
                    if (elementRecord.Name.ToString().Equals("name"))
                    {
                        dbElement.name = elementRecord.Value;
                    }
                    else if (elementRecord.Name.ToString().Equals("desc"))
                    {
                        dbElement.descr = elementRecord.Value;
                    }
                    else if (elementRecord.Name.ToString().Equals("time"))
                    {
                        dbElement.timeStamp = DateTime.Parse(elementRecord.Value);
                    }
                    else if (elementRecord.Name.ToString().Equals("children"))
                    {
                        List <int> children = new List <int>();
                        for (int j = 0; j < elementRecord.Descendants().Count(); j++)
                        {
                            children.Add(Int32.Parse(elementRecord.Descendants().ElementAt(j).Value));
                        }
                        dbElement.children = children;
                    }
                    else if (elementRecord.Name.ToString().Equals("payload"))
                    {
                        ListOfStrings payload = new ListOfStrings();
                        for (int j = 0; j < elementRecord.Descendants().Count(); j++)
                        {
                            payload.theWrappedData.Add(elementRecord.Descendants().ElementAt(j).Value);
                        }
                        dbElement.payload = payload;
                    }
                }
                dbEngine.Dictionary.Add(key, dbElement);
            }
        }
        static void Main(string[] args)
        {
            DBEngine <string, DBElement <string, List <string> > > db = new DBEngine <string, DBElement <string, List <string> > >();
            ItemFactory <int, string> itemFactory = new ItemFactory <int, string>();

            "Demonstrating Requirement #2".title();
            DBElement <string, List <string> > elem = new DBElement <string, List <string> >();

            elem.name      = "element";
            elem.descr     = "test element";
            elem.timeStamp = DateTime.Now.AddDays(-4);
            elem.children.AddRange(new List <string> {
                "1", "2", "3 "
            });
            elem.payload = new List <string> {
                "elem's payload"
            };
            WriteLine("\n Item to be inserted.. \n");
            elem.showEnumerableElement();
            db.insert("1", elem);
            db.showEnumerableDB();
            WriteLine();

            WriteLine("\n Inserting second element into DB :");
            DBElement <string, List <string> > elem2 = new DBElement <string, List <string> >();

            elem2.name      = "element2";
            elem2.descr     = "test element2";
            elem2.timeStamp = DateTime.Now;
            elem2.children.AddRange(new List <string> {
                "1", "2", "3", "4"
            });
            elem2.payload = new List <string> {
                "elem's payload"
            };
            WriteLine("\nItem to be inserted.. \n");
            elem2.showElement();
            db.insert("2", elem2);
            WriteLine("\n\n DB after insertion:");
            db.showEnumerableDB();

            "Persisting the database to XML:".title('_');
            db.toXml();
            "Augumenting database from XML".title('_');
            db.restoreDatabase();
            db.showEnumerableDB();
        }
Exemplo n.º 16
0
        /*----------------------------------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> 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 <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);
        }
        private void test1()
        {
            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();
        }
Exemplo n.º 20
0
        //defining delegate for querying key patterns
        public Func <Key, bool> defineQueryKeySearch(string search, DBEngine <Key, DBElement <Key, Data> > dbEngine)
        {
            Func <Key, bool> queryPredicate = null;

            //lambda that checks whether the key pattern matches
            queryPredicate = (Key key) =>
            {
                if (dbEngine.Dictionary != null)
                {
                    if (key.ToString().Contains(search))
                    {
                        return(true);
                    }
                }
                return(false);
            };
            return(queryPredicate);
        }
Exemplo n.º 21
0
        public static bool removeRelationship <Key, Value>(this DBEngine <Key, DBElement <Key, Value> > dbEngine, Key key, List <Key> children)
        {
            DBElement <Key, Value> elem;

            if (dbEngine.containsKey(key))
            {
                dbEngine.getValue(key, out elem);
                foreach (var child in children)
                {
                    if (elem.children.Contains(child))
                    {
                        elem.children.Remove(child);
                    }
                }
                return(true);
            }
            return(false);
        }
        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);
        }
Exemplo n.º 23
0
        private void test3()
        {
            DBEngine <int, DBElement <int, string> > db = new DBEngine <int, DBElement <int, string> >();
            DBEngine <string, DBElement <string, List <string> > > dbString = new DBEngine <string, DBElement <string, List <string> > >();
            ItemFactory <int, string> itemFactory = new ItemFactory <int, string>();

            //---------------Search for data with specified time interval---------------
            "Search for data with specified time interval:".title('.');
            WriteLine("\n\n Elements in DB :");
            var elem = new DBElement <int, string>();

            elem.name      = "old element";
            elem.descr     = "old test element";
            elem.timeStamp = DateTime.Now.AddDays(-3);
            elem.children.AddRange(new List <int> {
                85, 27, 65
            });
            elem.payload = "old elem's payload";

            DBElement <int, string> elem1 = new DBElement <int, string>();

            elem1.name      = "old2 element";
            elem1.descr     = "old2 test element";
            elem1.timeStamp = DateTime.Now.AddDays(-2);
            elem1.children.AddRange(new List <int> {
                11, 12, 13
            });
            elem1.payload = "old2 elem's payload";

            WriteLine("\n\n Search for Key which is created between {0} and {1}:\n\n", DateTime.Now.AddDays(-5).Date, DateTime.Now.AddDays(-1).Date);
            db.insert(99, elem);
            db.insert(50, elem1);
            db.showDB();
            WriteLine();
            var resultkeys = db.searchForTimeStamp(DateTime.Now.AddDays(-5), DateTime.Now.AddDays(-1));

            WriteLine("\n\nThe result is:\n\n");
            foreach (var item in resultkeys)
            {
                Write("{0}, ", item);
            }
            //---------------Search for data with specified time interval---------------
        }
Exemplo n.º 24
0
        //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);
        }
Exemplo n.º 25
0
        static void Main(string[] args)
        {
            //test stun for persist engine
            "Testing PersistEngine Package".title();
            WriteLine();
            PersistEngine <int, string> persistEngine = new PersistEngine <int, string>();

            "Testing Persist Engine Package".title('=');
            DBElement <int, string> elem = new DBElement <int, string>();
            DBEngine <int, DBElement <int, string> > dbEngine = new DBEngine <int, DBElement <int, string> >();

            //creating metdata
            "Metadata with data dictionary is ".title();
            elem.name      = "X";
            elem.descr     = "description";
            elem.timeStamp = DateTime.Parse("09/20/2015 11:36:58 PM");
            elem.children  = new List <int> {
                2, 3, 4
            };
            elem.payload = "payload";
            dbEngine.insert(1, elem);
            elem           = new DBElement <int, string>();
            elem.name      = "XX";
            elem.descr     = "description";
            elem.timeStamp = DateTime.Now;
            elem.children  = new List <int> {
                5, 6, 7
            };
            elem.payload = "payload";
            dbEngine.insert(12, elem);
            dbEngine.showDB();
            //persisting metadata into XML
            "Write in-memory database in XML file, please check DataPersistTest.xml file in Path:./PersistEngine/bin/debug.".title('-');
            persistEngine.persistXML(dbEngine);
            "Deleting in-memory database".title('-');
            dbEngine.Dictionary.Clear();
            "Database restored or augmented from an existing XML (DataPersistTest.xml) file".title('-');
            persistEngine.retrieveDataFromXMLTypeTwo(dbEngine, "DataPersistTest.xml", 10);
            dbEngine.showDB();
            WriteLine();
            Write("\n\n");
        }
        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);
        }
Exemplo n.º 27
0
        //<-------------------Adds child relation to a DBElement
        XElement add_children <Key, Data>(XElement request_msg, DBEngine <Key, DBElement <Key, Data> > db)
        {
            Console.Write("\n  Request to Add child relation for DB Element");
            XElement response_msg = new XElement("Query_Response");
            XElement type         = new XElement("Query_Type", "Add Children");
            XElement result       = new XElement("Result", "Could not Add children to DBElement");

            try
            {
                Key k = (Key)Convert.ChangeType(request_msg.Element("Key").Value, typeof(Key));
                Console.WriteLine(" with key - {0}", k);
                bool final_res = true;
                foreach (var new_key in request_msg.Element("Children").Elements("Key"))
                {
                    Key  child_key = (Key)Convert.ChangeType(new_key.Value, typeof(Key));
                    bool res       = db.addRelation <Key, DBElement <Key, Data>, Data>(k, child_key);
                    if (!res)
                    {
                        final_res = false;
                    }
                }

                if (final_res)
                {
                    result = new XElement("Result", "Child Relation added successfully to DB Element.");
                }
                else
                {
                    result = new XElement("Result", "Could not add Child Relation to DB Element.");
                }
                response_msg.Add(type);
                response_msg.Add(result);
                return(response_msg);
            }
            catch (NullReferenceException ex)
            {
                Console.WriteLine("\n  XML file for request message is not in the expected format. A particular tag could not be found.\n  Exception = {0}", ex);
                response_msg.Add(type);
                response_msg.Add(result);
                return(response_msg);
            }
        }
Exemplo n.º 28
0
        //-------< 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);
        }
Exemplo n.º 29
0
 public Action<Message>delete(DBEngine<int, DBElement<int, string>> db)
 {
     Action<Message> Delete = (msg) =>
        {
            XDocument doc = XDocument.Parse(msg.content.ToString());
            int key = int.Parse(doc.Descendants("Msg").Descendants("Data").Descendants("key").ElementAt(0).Value);
            Console.Write("\n\n delete an element which key = {0}", key);
            Write("\n\n --- Database before delete ---");
            db.showDB();
            if (db.delete(key))
            {
                msg.content = "Delete success";
                Console.Write("\n\n --- Database after delete---", key);
                db.showDB();
            }                       
            else
                msg.content = "Delete fail";
            Utilities.swapUrls(ref msg);                  
        };
     return Delete;
 }
Exemplo n.º 30
0
        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);
        }