Exemple #1
0
        private async void PeriodicLinkData()
        {
            while (!_disposed)
            {
                Console.Clear();
                using (var db = new ODatabase("localhost", 2424, "txgraph", ODatabaseType.Graph, "admin", "admin"))
                {
                    var nodes = db.Query <OVertex>($"SELECT * FROM Transaction WHERE Unlinked = true LIMIT 100000");
                    foreach (var node in nodes)
                    {
                        var transaction = db.Transaction;
                        if (IsCoinbaseTx(node))
                        {
                            node.SetField("Unlinked", false);
                            transaction.AddOrUpdate(node);
                            transaction.Commit();
                            continue;
                        }
                        try
                        {
                            transaction.AddOrUpdate(node);
                            for (var i = 0; i < GetInputCount(node); i++)
                            {
                                var inputString = node.GetField <string>($"INPUT{i}");
                                var prevHash    = inputString.Split(':')[0];
                                var prevN       = Int64.Parse(inputString.Split(':')[1]);
                                var prevTx      = db.Query <OVertex>($"SELECT * FROM Transaction WHERE Hash = \"{prevHash}\"").FirstOrDefault();
                                if (prevTx != null)
                                {
                                    transaction.AddOrUpdate(prevTx);
                                    var prevOutString = prevTx.GetField <string>($"OUTPUT{prevN}");
                                    var prevOutN      = prevOutString?.Split(':')[0];
                                    var outAddr       = prevOutString?.Split(':')[1];
                                    var outAmount     = prevOutString != null?Int64.Parse(prevOutString?.Split(':')[2]) : 0;

                                    var edge = new OEdge()
                                    {
                                        OClassName = "Link"
                                    };
                                    edge.SetField("sTx", prevHash);
                                    edge.SetField("sN", prevN);
                                    edge.SetField("amount", outAmount);
                                    edge.SetField("tTx", node.GetField <string>("Hash"));
                                    edge.SetField("tAddr", outAddr ?? "");
                                    transaction.AddEdge(edge, prevTx, node);
                                }
                            }
                            node.SetField("Unlinked", false);
                            transaction.Update(node);
                            transaction.Commit();
                        }
                        catch (Exception e)
                        {
                            transaction.Reset();
                        }
                    }
                }
                await Task.Delay(60000);
            }
        }
        public void ShouldCreateProperty()
        {
            using (TestDatabaseContext testContext = new TestDatabaseContext())
            {
                using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
                {
                    // prerequisites
                    database
                    .Create.Class("TestClass")
                    .Extends <OVertex>()
                    .Run();
                }

                using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
                {
                    // Basic Test
                    foreach (var item in Enum.GetNames(typeof(OType)))
                    {
                        database.Create
                        .Property("_" + item.ToLower(), (OType)Enum.Parse(typeof(OType), item))
                        .Class("TestClass")
                        .Run();
                    }

                    var document = database.Query(_metadataQuery);

                    foreach (var item in Enum.GetNames(typeof(OType)))
                    {
                        var metadata = document.Find(d => d.GetField <string>("name") == "_" + item.ToLower());
                        validateMetadata(metadata, (OType)Enum.Parse(typeof(OType), item));
                    }

                    // Complex Test
                    database
                    .Create
                    .Property("_embededlist_with_type", OType.EmbeddedList)
                    .LinkedType(OType.Integer)
                    .Class("TestClass")
                    .Run();

                    database
                    .Create
                    .Property("_embededlist_with_class", OType.EmbeddedList)
                    .LinkedClass("OUser")
                    .Class("TestClass")
                    .Run();

                    document = database.Query(_metadataQuery);

                    var elwtMetadata = document.Find(d => d.GetField <string>("name") == "_embededlist_with_type");
                    validateMetadata(elwtMetadata, OType.EmbeddedList);
                    Assert.AreEqual(OType.Integer, (OType)elwtMetadata.GetField <int>("linkedType"));

                    var elwcMetadata = document.Find(d => d.GetField <string>("name") == "_embededlist_with_class");
                    validateMetadata(elwtMetadata, OType.EmbeddedList);
                    Assert.AreEqual("OUser", elwcMetadata.GetField <string>("linkedClass"));
                }
            }
        }
Exemple #3
0
        public IReadOnlyList <TBO> Execute <TBO>(string query) where TBO : IBusinessObject
        {
            var items = database.Query(query);

            var result = ConvertItems <TBO>(items, BoActivator.GetImplementationType(typeof(TBO)));

            return(new ReadOnlyCollection <TBO>(result));
        }
        public void ShouldCreateProperty()
        {
            using (TestDatabaseContext testContext = new TestDatabaseContext())
            {
                using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
                {
                    // prerequisites
                    database
                        .Create.Class("TestClass")
                        .Extends<OVertex>()
                        .Run();


                    // Basic Test
                    foreach (var item in Enum.GetNames(typeof(OType)))
                    {
                        database.Create
                            .Property("_" + item.ToLower(), (OType)Enum.Parse(typeof(OType), item))
                            .Class("TestClass")
                            .Run();
                    }

                    var document = database.Query(_metadataQuery);

                    foreach (var item in Enum.GetNames(typeof(OType)))
                    {
                        var metadata = document.Find(d => d.GetField<string>("name") == "_" + item.ToLower());
                        validateMetadata(metadata, (OType)Enum.Parse(typeof(OType), item));
                    }

                    // Complex Test
                    database
                        .Create
                        .Property("_embededlist_with_type", OType.EmbeddedList)
                        .LinkedType(OType.Integer)
                        .Class("TestClass")
                        .Run();

                    database
                        .Create
                        .Property("_embededlist_with_class", OType.EmbeddedList)
                        .LinkedClass("OUser")
                        .Class("TestClass")
                        .Run();

                    document = database.Query(_metadataQuery);

                    var elwtMetadata = document.Find(d => d.GetField<string>("name") == "_embededlist_with_type");
                    validateMetadata(elwtMetadata, OType.EmbeddedList);
                    Assert.AreEqual(OType.Integer, (OType)elwtMetadata.GetField<int>("linkedType"));

                    var elwcMetadata = document.Find(d => d.GetField<string>("name") == "_embededlist_with_class");
                    validateMetadata(elwtMetadata, OType.EmbeddedList);
                    Assert.AreEqual("OUser", elwcMetadata.GetField<string>("linkedClass"));

                }
            }
        }
        public List <string> GetAddresses(ConnectionOptions dbOptions)
        {
            List <string> result = null;

            using (var db = new ODatabase(dbOptions))
            {
                switch (_options.Type)
                {
                case LimitType.DEPTH:
                    result = db.Command($"SELECT list(inE().tAddr) as addresses FROM (TRAVERSE out() FROM (SELECT * FROM Transaction WHERE Hash = '{_options.StartTx}') WHILE $depth <= {_options.Limit} STRATEGY BREADTH_FIRST)").ToList().FirstOrDefault().GetField <List <string> >("addresses").Where(x => !string.IsNullOrEmpty(x)).Distinct().ToList();
                    break;

                case LimitType.DATE:
                    var start = db.Query <ODocument>($"SELECT BlockTime AS value FROM Transaction WHERE Hash = '{_options.StartTx}'").Select(x => x.GetField <DateTime>("value")).FirstOrDefault().ToLocalTime();
                    var end   = start.AddMinutes(_options.Limit);
                    result = db.Command($"SELECT list(inE().tAddr) as addresses FROM Transaction WHERE BlockTime >= '{start.ToString("yyyy-MM-dd HH:mm:ss")}' AND BlockTime <= '{end.ToString("yyyy-MM-dd HH:mm:ss")}'").ToList().FirstOrDefault().GetField <List <string> >("addresses").Where(x => !string.IsNullOrEmpty(x)).Distinct().ToList();
                    break;

                case LimitType.COUNT:
                    result = db.Command($"SELECT list(inE().tAddr) as addresses FROM (TRAVERSE out() FROM (SELECT * FROM Transaction WHERE Hash = '{_options.StartTx}') LIMIT {_options.Limit} STRATEGY BREADTH_FIRST)").ToList().FirstOrDefault().GetField <List <string> >("addresses").Where(x => !string.IsNullOrEmpty(x)).Distinct().ToList();
                    break;

                default:
                    result = new List <string>();
                    break;
                }
                return(result);
            }
        }
        public static Router RouterByName(String name, String SerialNumber)
        {
            ODatabase database = InitDB();
            string    query    = String.Format("SELECT * FROM Router WHERE name=\"" + name + "\" AND SerialNumber=\""
                                               + SerialNumber + "\"");
            List <ODocument> resultset = database.Query(query).ToList();

            JavaScriptSerializer converter = new JavaScriptSerializer();

            List <Router> AllRouters = new List <Router>();

            foreach (ODocument doc in resultset)
            {
                var    json = converter.Serialize(doc);
                String a    = json.ToString();
                Router d    = converter.Deserialize <Router>(a);
                AllRouters.Add(d);
            }

            Router router = null;

            if (AllRouters != null)
            {
                router = AllRouters[0];
            }
            database.Close();

            return(router);
        }
        public static Server ServerByName(String name, String LanMacAddress)
        {
            ODatabase database = InitDB();
            string    query    = String.Format("SELECT * FROM Server WHERE name=\"" + name + "\" AND LanMacAddress=\""
                                               + LanMacAddress + "\"");
            List <ODocument> resultset = database.Query(query).ToList();

            JavaScriptSerializer converter = new JavaScriptSerializer();

            List <Server> AllServerss = new List <Server>();

            foreach (ODocument doc in resultset)
            {
                var    json = converter.Serialize(doc);
                String a    = json.ToString();
                Server d    = converter.Deserialize <Server>(a);
                AllServerss.Add(d);
            }

            Server server = null;

            if (AllServerss != null)
            {
                server = AllServerss[0];
            }
            database.Close();

            return(server);
        }
Exemple #8
0
        static void CreateDatabasePoolTest()
        {
            var serverConnInfo = Configuration.GetSection("ConnectionStrings:DefaultConnection").GetChildren().ToDictionary(x => x.Key);

            OClient.CreateDatabasePool(
                serverConnInfo["Server"].Value,
                int.Parse(serverConnInfo["Port"].Value),
                serverConnInfo["DefaultDB"].Value,
                ODatabaseType.Graph,
                serverConnInfo["Username"].Value,
                serverConnInfo["Password"].Value,
                10,
                "AppConnection"
                );

            using (var database = new ODatabase("AppConnection"))
            {
                var documents = database.Query("select from v");
                foreach (var item in documents)
                {
                    System.Console.WriteLine("Name: {0} Type: {1}",
                                             item.GetField <string>("name"), item.GetField <string>("type"));
                }
            }

            OClient.DropDatabasePool("AppConnection");
        }
        public override void Run(ConnectionOptions mainOptions, IEnumerable <string> addresses)
        {
            var inGroups = new List <List <string> >();

            using (var mainDB = new ODatabase(mainOptions))
            {
                foreach (var address in addresses)
                {
                    var groups = mainDB.Query($"SELECT inE().tAddr AS address FROM (SELECT expand(inV) FROM (SELECT inV() FROM Link WHERE tAddr = '{address}' LIMIT 10000))").SelectMany(x => x.GetField <List <string> >("address")).Where(y => !string.IsNullOrEmpty(y)).Where(x => x.Count() > 1).Distinct().ToList();
                    try
                    {
                        inGroups.Add(groups);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(address + " not in DB?");
                    }
                    Console.WriteLine(address + " done.");
                }
            }
            var cc = new ClusteringCollapser();

            cc.Collapse(inGroups);
            _result = cc.Clustering;
        }
Exemple #10
0
        static void CreateDatabasePoolTest()
        {
            OClient.CreateDatabasePool(
                "localhost",
                2424,
                "GratefulDeadConcerts",
                ODatabaseType.Graph,
                "root",
                "root",
                10,
                "AppConnection"
                );

            using (var database = new ODatabase("AppConnection"))
            {
                var documents = database.Query("select from v");
                foreach (var item in documents)
                {
                    System.Console.WriteLine("Name: {0} Type: {1}",
                                             item.GetField <string>("name"), item.GetField <string>("type"));
                }
            }

            OClient.DropDatabasePool("AppConnection");
        }
        public void ShouldFetchLinkedDocumentsFromSimpleQuery()
        {
            using (TestDatabaseContext testContext = new TestDatabaseContext())
                using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
                {
                    database.Create.Class("Owner").Extends("V").Run();
                    database.Create.Class("Computer").Extends("V").Run();
                    var owner = new ODocument {
                        OClassName = "Owner"
                    };

                    owner.SetField <String>("name", "Shawn");

                    owner = database.Create.Vertex(owner).Run();

                    var computer = new ODocument {
                        OClassName = "Computer"
                    };

                    computer.SetField <ORID>("owner", owner.ORID);
                    database.Create.Vertex(computer).Run();

                    computer = database.Query("SELECT FROM Computer", "*:-1").FirstOrDefault();

                    Assert.True(database.ClientCache.ContainsKey(computer.GetField <ORID>("owner")));

                    var document = database.ClientCache[computer.GetField <ORID>("owner")];
                    Assert.Equal(document.GetField <string>("name"), "Shawn");
                }
        }
        public static Switch SwitchByNameOnly(String name)
        {
            ODatabase        database  = InitDB();
            string           query     = String.Format("SELECT * FROM Switch WHERE name=\"" + name + "\"");
            List <ODocument> resultset = database.Query(query).ToList();

            JavaScriptSerializer converter = new JavaScriptSerializer();

            List <Switch> AllSwitches = new List <Switch>();

            foreach (ODocument doc in resultset)
            {
                var    json = converter.Serialize(doc);
                String a    = json.ToString();
                Switch d    = converter.Deserialize <Switch>(a);
                AllSwitches.Add(d);
            }

            Switch router = null;

            if (AllSwitches != null)
            {
                router = AllSwitches[0];
            }
            database.Close();

            return(router);
        }
        public void ShouldFetchLinkedDocumentsFromSimpleQuery()
        {
            using (TestDatabaseContext testContext = new TestDatabaseContext())
            using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
            {
                database.Create.Class("Owner").Extends("V").Run();
                database.Create.Class("Computer").Extends("V").Run();
                var owner = new ODocument { OClassName = "Owner" };

                owner.SetField<String>("name", "Shawn");

                owner = database.Create.Vertex(owner).Run();

                var computer = new ODocument { OClassName = "Computer" };

                computer.SetField<ORID>("owner", owner.ORID);
                database.Create.Vertex(computer).Run();

                computer = database.Query("SELECT FROM Computer", "*:-1").FirstOrDefault();

                Assert.That(database.ClientCache.ContainsKey(computer.GetField<ORID>("owner")));

                var document = database.ClientCache[computer.GetField<ORID>("owner")];
                Assert.That(document.GetField<string>("name"), Is.EqualTo("Shawn"));
            }
        }
Exemple #14
0
        /// <summary>
        /// Fills out a collection of models of type <typeparamref name="T"/> using <c>traverse</c>. <paramref name="db"/> must be open.
        /// </summary>
        /// <remarks>
        /// <para>Note that <c>traverse</c> can be slow, and <c>select</c> may be more appropriate. See
        /// http://www.orientechnologies.com/docs/last/orientdb.wiki/SQL-Traverse.html#should-i-use-traverse-or-select
        /// </para>
        /// <para>Lightweight edges are not followed when populating model properties. Make sure to use "heavyweight" edges with either
        /// <c>alter property MyEdgeClass.out MANDATORY=true</c> and <c>alter property MyEdgeClass.in MANDATORY=true</c>, or else
        /// use <c>alter database custom useLightweightEdges=false</c>.</para>
        /// </remarks>
        /// <typeparam name="T">The model type. Must extend <see cref="ABaseModel"/>, have a parameterless constructor, and most importantly it must be in the same
        /// namespace as <see cref="ABaseModel"/>.</typeparam>
        /// <param name="db">The database to query</param>
        /// <param name="from">A class, cluster, RID list, or RID to traverse. RIDs are in the form <c>#clusterId:clusterPosition</c>. Lists are in the form
        /// <c>[RID,RID,...]</c> with one or more elements (whitespace is ignored). Clusters are in the form <c>cluster:clusterName</c> or <c>cluster:clusterId</c>.</param>
        /// <exception cref="System.ArgumentException">If <paramref name="from"/> is an invalid format</exception>
        /// <returns>An enumerable collection of models of type <typeparamref name="T"/>. Public instance properties of the models will have their values populated
        /// based on all non-lightweight edges in the traversal.</returns>
        public static IEnumerable <T> Traverse <T>(this ODatabase db, string from) where T : ABaseModel, new()
        {
            // Sanity check on target
            bool matches = false;

            foreach (string pattern in legalTargets)
            {
                if (Regex.IsMatch(from, pattern))
                {
                    matches = true;
                    break;
                }
            }
            if (!matches)
            {
                throw new ArgumentException("Traverse target must be a class, cluster, RID list, or single RID.", "from");
            }
            bool fromSingleRecord = Regex.IsMatch(from, legalTargets[SINGLE_RID_TARGET_PATTERN_INDEX]);
            // Traverse DB
            string            sql       = string.Format("traverse * from {0}", from);
            List <ODocument>  result    = db.Query(sql);
            DatabaseTraversal traversal = new DatabaseTraversal(db, result);
            // Process result
            IEnumerable <T> models = traversal.ToModel <T>();

            if (fromSingleRecord)
            {
                // Either Traverse(ORID) was called, or client code called Traverse with an RID string -- return a single element
                models = models.Where(m => m.ORID.ToString().Equals(from));
            }
            return(models);
        }
        public static Desktop DesktopByNameOnly(String name)
        {
            ODatabase        database  = InitDB();
            string           query     = String.Format("SELECT * FROM Desktop WHERE name=\"" + name + "\"");
            List <ODocument> resultset = database.Query(query).ToList();

            JavaScriptSerializer converter = new JavaScriptSerializer();

            List <Desktop> AllDesktops = new List <Desktop>();

            foreach (ODocument doc in resultset)
            {
                var     json = converter.Serialize(doc);
                String  a    = json.ToString();
                Desktop d    = converter.Deserialize <Desktop>(a);
                AllDesktops.Add(d);
            }

            Desktop desktop = null;

            if (AllDesktops != null)
            {
                desktop = AllDesktops[0];
            }
            database.Close();

            return(desktop);
        }
        public static Laptop LaptopByName(String name, String LanMacAddress, String WiFiMacAddress)
        {
            ODatabase database = InitDB();
            string    query    = String.Format("SELECT * FROM Laptop WHERE name=\"" + name + "\" AND LanMacAddress=\""
                                               + LanMacAddress + "\" AND WiFiMacAddress=\"" + WiFiMacAddress + "\"");
            List <ODocument> resultset = database.Query(query).ToList();

            JavaScriptSerializer converter = new JavaScriptSerializer();

            List <Laptop> AllLaptops = new List <Laptop>();

            foreach (ODocument doc in resultset)
            {
                var    json = converter.Serialize(doc);
                String a    = json.ToString();
                Laptop d    = converter.Deserialize <Laptop>(a);
                AllLaptops.Add(d);
            }

            Laptop laptop = null;

            if (AllLaptops != null)
            {
                laptop = AllLaptops[0];
            }
            database.Close();

            return(laptop);
        }
        public static List <ODocument> FindServerConnections(String name, String LanMacAddress)
        {
            ODatabase database = InitDB();
            string    query    = String.Format("SELECT * FROM Server WHERE name=\"" + name + "\" AND LanMacAddress=\""
                                               + LanMacAddress + "\"");
            List <ODocument> result = database.Query(query).ToList();

            ODocument o = result[0];
            ORID      z = o.GetField <ORID>("@ORID");


            String           querry    = "TRAVERSE * FROM " + z + " WHILE $depth<=2";
            List <ODocument> resultset = database.Query(querry).ToList <ODocument>();

            database.Close();
            return(resultset);
        }
 public void QueryMetadataNotSupported()
 {
     using (var context = new TestDatabaseContext())
         using (var database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
         {
             var document = database
                            .Query("select expand(indexes) from metadata:blaaa");
         }
 }
        static void CreateDatabaseTestManualy()
        {
            using (var server = new OServer("127.0.0.1", 2424, "root", "root"))
            {
                var created = false;
                try
                {
                    created = server.CreateDatabase("TestManualy", ODatabaseType.Document, OStorageType.PLocal);

                    if (!created)
                        throw new Exception("Database not created");

                    var exists = server.DatabaseExist("TestManualy", OStorageType.PLocal);

                    if (!exists)
                        throw new Exception("Database not exists");

                    System.Console.WriteLine("Database created - get server configuration");

                    var config = server.ConfigList();
                    foreach (var item in config)
                    {
                        System.Console.WriteLine("{0} : {1}",
                            item.Key, item.Value);
                    }

                    System.Console.WriteLine("try connect to the database and query");

                    OClient.CreateDatabasePool(
                            "localhost",
                            2424,
                            "TestManualy",
                            ODatabaseType.Graph,
                            "root",
                            "root",
                            10,
                            "AppConnection"
                        );
                    using (var database = new ODatabase("AppConnection"))
                    {
                        var documents = database.Query("select from OUser");
                        foreach (var item in documents)
                        {
                            System.Console.WriteLine("Name: {0} Status: {1}",
                                item.GetField<string>("name"), item.GetField<string>("status"));
                        }
                    }
                    OClient.DropDatabasePool("AppConnection");
                }
                finally
                {
                    if (created)
                        server.DropDatabase("TestManualy", OStorageType.PLocal);
                }
            }
        }
        public override void Run(ConnectionOptions mainOptions, IEnumerable <string> addresses)
        {
            var groups = new List <List <string> >();

            using (var mainDB = new ODatabase(mainOptions))
            {
                foreach (var address in addresses)
                {
                    var record = mainDB.Query($"SELECT $i as inputs, $o as outputs FROM (SELECT expand(inV) FROM (SELECT inV() FROM Link WHERE tAddr = '{address}' LIMIT 10000)) LET $i = set(inE().tAddr), $o = set(outE().tAddr) WHERE Coinbase = false").Select(x => new KeyValuePair <string, List <List <string> > >(x.GetField <ORID>("tx").ToString(), new List <List <string> >()
                    {
                        x.GetField <List <string> >("source"), x.GetField <List <string> >("target")
                    })).First();
                    // clean the record
                    record.Value[0] = record.Value[0].Distinct().ToList();
                    record.Value[1] = record.Value[0].Distinct().ToList();
                    record.Value[0].RemoveAll(x => x == null);
                    record.Value[1].RemoveAll(x => x == null);
                    // can we identify a return address?
                    var occurrences = new Dictionary <string, int>();
                    foreach (var outAddr in record.Value[1])
                    {
                        var count = mainDB.Query($"SELECT COUNT(*) FROM Link WHERE tAddr = '{outAddr}'").SingleOrDefault()?.GetField <long>("count");
                        if (count != null)
                        {
                            occurrences.Add(outAddr, (int)count);
                        }
                    }
                    var addr = GetChangeAddress(record, occurrences, mainOptions);
                    if (addr != null)
                    {
                        // add a new group
                        var group = record.Value.First();
                        group.Add(addr);
                        group.RemoveAll(x => string.IsNullOrEmpty(x));
                        groups.Add(group);
                    }
                }
            }
            var cc = new ClusteringCollapser();

            cc.Collapse(groups);
            _result = cc.Clustering;
        }
        public void ShouldExeccutePreparedQueryByPossition()
        {
            var query      = new PreparedQuery("select from Profile where name = ? and surname = ?");
            var docMichael = _database
                             .Query(query)
                             .Run("Michael", "Blach").SingleOrDefault();

            Assert.That(docMichael, Is.Not.Null);
            Assert.That(docMichael.GetField <string>("name"), Is.EqualTo("Michael"));
            Assert.That(docMichael.GetField <string>("surname"), Is.EqualTo("Blach"));

            var docLuca = _database
                          .Query(query)
                          .Run("Luca", "Garulli").SingleOrDefault();

            Assert.That(docLuca, Is.Not.Null);
            Assert.That(docLuca.GetField <string>("name"), Is.EqualTo("Luca"));
            Assert.That(docLuca.GetField <string>("surname"), Is.EqualTo("Garulli"));
        }
 public void QueryIndexes()
 {
     using (var context = new TestDatabaseContext())
         using (var database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
         {
             var document = database
                            .Query("select expand(indexes) from metadata:indexmanager");
             Assert.IsTrue(document.Count > 0);
         }
 }
 public void QuerySchemaProperties()
 {
     using (var context = new TestDatabaseContext())
         using (var database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
         {
             var document = database
                            .Query("select expand(properties) from (select expand(classes) from metadata:schema) where name = 'OUser'");
             Assert.IsTrue(document.Count > 0);
         }
 }
Exemple #24
0
 static void CreateDatabaseTestUsingContext()
 {
     using (var context = new TestDatabaseContext())
         using (var database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
         {
             var documents = database.Query("select from OUser");
             foreach (var item in documents)
             {
                 System.Console.WriteLine("Name: {0} Status: {1}",
                                          item.GetField <string>("name"), item.GetField <string>("status"));
             }
         }
 }
 static void CreateDatabaseTestUsingContext()
 {
     using (var context = new TestDatabaseContext())
     using (var database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
     {
         var documents = database.Query("select from OUser");
         foreach (var item in documents)
         {
             System.Console.WriteLine("Name: {0} Status: {1}",
                 item.GetField<string>("name"), item.GetField<string>("status"));
         }
     }
 }
        public static void UpdateDesktop(String name, String OS, String LanMacAddress, String nameOld, String LanMacAddressOld)
        {
            ODatabase database = InitDB();

            string query = String.Format("SELECT * FROM Desktop WHERE name=\"" + nameOld + "\" AND LanMacAddress=\""
                                         + LanMacAddressOld + "\"");
            List <ODocument> result = database.Query(query).ToList();

            ODocument o = result[0];
            ORID      z = o.GetField <ORID>("@ORID");

            database.Update(z).Set("name", name).Set("OS", OS).Set("LanMacAddress", LanMacAddress).Run();
        }
 public void ShouldConvertSQLQueryResultsToClass()
 {
     using (TestDatabaseContext testContext = new TestDatabaseContext())
         using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
         {
             database.Create.Class <TestVertex>().Run();
             database.Create.Vertex(new TestVertex
             {
                 Name = "Shawn",
                 Age  = 37
             }).Run();
             List <TestVertex> result = database.Query <TestVertex>("SELECT FROM TestVertex");
             Assert.Equal(result[0].Name, "Shawn");
             Assert.Equal(result[0].Age, 37);
         }
 }
 public void ShouldConvertSQLQueryResultsToClass()
 {
     using (TestDatabaseContext testContext = new TestDatabaseContext())
     using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
     {
         database.Create.Class<TestVertex>().Run();
         database.Create.Vertex(new TestVertex
             {
                 Name = "Shawn",
                 Age = 37
             }).Run();
         List<TestVertex> result = database.Query<TestVertex>("SELECT FROM TestVertex");
         Assert.That(result[0].Name, Is.EqualTo("Shawn"));
         Assert.That(result[0].Age, Is.EqualTo(37));
     }
 }
Exemple #29
0
        /// <summary>
        /// Записать в базу друзей пользователя
        /// </summary>
        /// <param name="rootUser">Главнвый пользователь</param>
        /// <param name="Users">Его друзья</param>
        /// <returns></returns>
        public bool WriteVKUserFriends(VK.VKMan rootUser, List <VK.VKMan> Users)
        {
            using (ODatabase database = new ODatabase(opts))
            {
                foreach (VK.VKMan User in Users)
                {
                    /*
                     * byte[] bytes = Encoding.C.GetBytes();
                     * Encoding win1251 = Encoding.GetEncoding(1251);
                     * string text = win1251.GetString(bytes);
                     */
                    /*
                     * string queryString = String.Format("INSERT INTO user (first_name,last_name,sex,bday,country," +
                     *      "city,interests,music,movies,games,about)" +
                     *      " values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}')",
                     *      User.first_name, User.last_name, User.sex, DateTimeAdapter(User.bday), User.country, User.city, User.interests,
                     *      User.music, User.movies, User.games, "");
                     */

                    string queryString = String.Format("UPDATE user set first_name='{0}', last_name='{1}', sex='{2}',bday='{3}',country='{4}'," +
                                                       "city='{5}',interests='{6}',music='{7}',movies='{8}',games='{9}',about='{10}', vkid='{11}'" +
                                                       " UPSERT WHERE vkid='{11}'",
                                                       User.first_name, User.last_name, User.sex, DateTimeAdapter(User.bday), User.country, User.city, User.interests,
                                                       User.music, User.movies, User.games, "", User.id);

                    string queryStringSelectORID = string.Format("SELECT FROM user WHERE vkid={0}", User.id);

                    try {
                        /* OCommandResult commandResult = database.Command(queryString);
                         * OCommandResult commandSelectORIDResult = database.Command(queryStringSelectORID);
                         * User.ORID = commandSelectORIDResult.ToDocument().GetField<ODocument>("Content").GetField<ORID>("@ORID").ToString();
                         * database.Command(string.Format("CREATE EDGE FROM {0} TO {1} SET weight={2}", rootUser.ORID, User.ORID, calculateWeigth()));
                         */
                        List <ODocument> result = database.Query(queryStringSelectORID);
                        foreach (ODocument document in result)
                        {
                            User.ORID = document.ORID.ToString();
                        }
                    } catch (OException ex)
                    {
                        Console.WriteLine(String.Format("There are problems with {0} {1}", User.first_name, User.last_name));
                    }
                }
                return(true);
            }
        }
Exemple #30
0
        public void writeRecursiveUsers(VK.VKMan rootUser, VK.VKObjects vkInstance, int currDepth, int depth, List <MainWindow.conditionArr> listConditions)
        {
            using (ODatabase database = new ODatabase(opts))
            {
                var Users = vkInstance.getFriendsListFromXML(rootUser.id, listConditions);
                Statistic.Statistic.LogVertex(depth, Users.Count);
                foreach (VK.VKMan User in Users)
                {
                    string queryString = String.Format("UPDATE user set first_name='{0}', last_name='{1}', sex='{2}',bday='{3}',country='{4}'," +
                                                       "city='{5}',interests='{6}',music='{7}',movies='{8}',games='{9}',about='{10}', vkid='{11}'" +
                                                       " UPSERT WHERE vkid='{11}'",
                                                       User.first_name, User.last_name, User.sex, DateTimeAdapter(User.bday), User.country, User.city, User.interests,
                                                       User.music, User.movies, User.games, "", User.id);

                    string queryStringSelectORID = string.Format("SELECT FROM user WHERE vkid={0}", User.id);

                    try
                    {
                        OCommandResult commandResult           = database.Command(queryString);
                        OCommandResult commandSelectORIDResult = database.Command(queryStringSelectORID);
                        User.ORID = commandSelectORIDResult.ToDocument().GetField <ODocument>("Content").GetField <ORID>("@ORID").ToString();

                        List <ODocument> result = database.Query(queryStringSelectORID);
                        foreach (ODocument document in result)
                        {
                            User.ORID = document.ORID.ToString();
                        }
                        //Логируем
                        var comupsert = string.Format("CREATE EDGE Friend FROM {0} TO {1} SET weight={2}", rootUser.ORID, User.ORID, User.rootEdgeWeigth);
                        database.Command(string.Format("CREATE EDGE Friend FROM {0} TO {1} SET weight={2}", rootUser.ORID, User.ORID, User.rootEdgeWeigth));
                        //Statistic.Statistic.LogEdge(depth,);//Логгируем
                        if (currDepth < depth)
                        {
                            currDepth++;
                            writeRecursiveUsers(User, vkInstance, currDepth, depth, listConditions);
                            currDepth--;
                        }
                    }
                    catch (OException ex)
                    {
                        Statistic.Statistic.logError(ex.ToString());
                        Console.WriteLine(String.Format("There are problems with {0} {1}", User.first_name, User.last_name));
                    }
                }
            }
        }
        public static void UpdateRouter(String name, String OS, String SerialNumber, String Manufacturer,
                                        int NumberOfPorts, int NumberOfTakenPorts, String WiFiNetworkName,
                                        List <String> MacAddressList, String RouterNameOld, String SerialNumberOld)
        {
            ODatabase database = InitDB();

            string query = String.Format("SELECT * FROM Router WHERE name=\"" + RouterNameOld + "\" AND SerialNumber=\""
                                         + SerialNumberOld + "\"");
            List <ODocument> result = database.Query(query).ToList();

            ODocument o = result[0];
            ORID      z = o.GetField <ORID>("@ORID");

            database.Update(z).Set("name", name).Set("OS", OS).Set("SerialNumber", SerialNumber)
            .Set("Manufacturer", Manufacturer).Set("NumberOfPorts", NumberOfPorts)
            .Set("NumberOfTakenPorts", NumberOfTakenPorts).Set("WiFiNetworkName", WiFiNetworkName)
            .Set("MacAddressList", MacAddressList).Run();
        }
Exemple #32
0
 public override void Run(ConnectionOptions mainOptions, IEnumerable <string> addresses)
 {
     using (var mainDB = new ODatabase(mainOptions))
     {
         foreach (var address in addresses)
         {
             var kvp = new KeyValuePair <string, double>(address, mainDB.Query($"SELECT avg(inE().amount).asLong() as total FROM (SELECT expand(inV) FROM (SELECT inV() FROM Link WHERE tAddr = '{address}' LIMIT 500))").First().GetField <long>("total"));
             try
             {
                 _result.Add(kvp.Key, kvp.Value);
             }
             catch (Exception e)
             {
                 Console.WriteLine(address + " not in DB?");
             }
             Console.WriteLine(address + " done.");
         }
     }
 }
Exemple #33
0
 public override void Run(ConnectionOptions mainOptions, IEnumerable <string> addresses)
 {
     using (var mainDB = new ODatabase(mainOptions))
     {
         foreach (var address in addresses)
         {
             var kvp = mainDB.Query($"SELECT list($hour) as hour FROM (SELECT * FROM Link WHERE tAddr = '{address}' LIMIT 500) LET $hour = outV().BlockTime.format('k').asLong()").Select(x => new KeyValuePair <string, BitArray>(address, ToBitArray(x.GetField <List <long> >("hour")))).First();
             try
             {
                 _result.Add(kvp.Key, kvp.Value);
             }
             catch (Exception e)
             {
                 Console.WriteLine(address + " not in DB?");
             }
             Console.WriteLine(address + " done.");
         }
     }
 }
Exemple #34
0
 public override void Run(ConnectionOptions mainOptions, IEnumerable <string> addresses)
 {
     using (var mainDB = new ODatabase(mainOptions))
     {
         foreach (var address in addresses)
         {
             var kvp = new KeyValuePair <string, List <string> >(address, mainDB.Query($"SELECT set(network) as network FROM (SELECT unionAll($a, $b, $c) as network FROM Link LET $a = inV().inE().tAddr, $b = inV().outE().tAddr, $c = outV().inE().tAddr WHERE tAddr = '{address}' LIMIT 10)").First().GetField <List <string> >("network"));
             try
             {
                 _result.Add(kvp.Key, kvp.Value);
             }
             catch (Exception e)
             {
                 Console.WriteLine(address + " not in DB?");
             }
             Console.WriteLine(address + " done.");
         }
     }
 }
        public void ShouldCreateNonPrimitiveProperties()
        {
            using (TestDatabaseContext testContext = new TestDatabaseContext())
            using (var db = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
            {
                if (!db.Schema.IsClassExist<TestClass>())
                {
                    db.Create.Class<TestClass>().CreateProperties<TestClass>().Run();

                    var document = db.Query(_metadataQuery);

                    var SomeListMetadata = document.Find(d => d.GetField<string>("name") == "SomeList");
                    validateMetadata(SomeListMetadata, OType.EmbeddedList);

                    var DictionaryMetadata = document.Find(d => d.GetField<string>("name") == "Dictionary");
                    validateMetadata(DictionaryMetadata, OType.EmbeddedMap);
                }
            }
        }
        public void ShouldCreateNonPrimitiveProperties()
        {
            using (TestDatabaseContext testContext = new TestDatabaseContext())
                using (var db = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
                {
                    if (!db.Schema.IsClassExist <TestClass>())
                    {
                        db.Create.Class <TestClass>().CreateProperties <TestClass>().Run();

                        var document = db.Query(_metadataQuery);

                        var SomeListMetadata = document.Find(d => d.GetField <string>("name") == "SomeList");
                        validateMetadata(SomeListMetadata, OType.EmbeddedList);

                        var DictionaryMetadata = document.Find(d => d.GetField <string>("name") == "Dictionary");
                        validateMetadata(DictionaryMetadata, OType.EmbeddedMap);
                    }
                }
        }
        static void TestQuery()
        {
            ODatabase database = new ODatabase(_alias);

            //List<ORecord> records = database.Query("select from OGraphVertex where title = \"server 1\"", "*:2");
            //List<ORecord> records = database.Query("select in.in.@rid as inVs, in.out.@rid as outVs, title from OGraphVertex where @rid = #8:0");
            List<ORecord> records = database.Query(
                "select " +
                " out.in as neighborRIDs," +
                //" out.in.type as neighborTypes," +
                //" out.in.state as neighborStates," +
                " title," +
                " @rid" +
                " from #8:0"
            );

            foreach (ORecord record in records)
            {
                //Ve v = record.To<Ve>();
                List<ORID> orids = record.GetField<List<ORID>>("neighborRIDs");
                List<string> types = record.GetField<List<string>>("neighborTypes");
                List<int> states = record.GetField<List<int>>("neighborStates");

                System.Console.WriteLine("{0} - {1} {2} {3}", record.GetField<string>("title"), orids.Count, types.Count, states.Count);
                //System.Console.WriteLine(v.Title);
            }

            /*foreach (ORecord record in database.Query("select from OGraphEdge limit 20", "*:2"))
            {
                Ed e = record.To<Ed>();
                System.Console.WriteLine(e.Label);
            }*/

            //ORecord rec = database.Command("create vertex OGraphVertex set title = \"whoa\"").ToSingle();
            //object foo = database.Command("delete vertex " + rec.ORID.ToString());
        }
        public void GIVEN___EmployeeArrayType_class_with_common_data_type___WHEN___write_to_orientdb___THEN___should_be_able_to_read()
        {
            using (TestDatabaseContext testContext = new TestDatabaseContext())
            using (var db = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
            {
                var employeeClassName = "EmployeeArrayType";

                var clusterid = db.Create.Class(employeeClassName).Run();

                var employee = new EmployeeArrayType();
                employee.Id = Guid.NewGuid();
                employee.Name = new string[2];
                employee.Name[0] = "Andrew";
                employee.Name[1] = ("Jack");
                employee.Age = new int[2];
                employee.Age[0] = (1);
                employee.Age[1] = (2);
                employee.BirthDate = new DateTime[2];
                employee.BirthDate[0] = (DateTime.Now);
                employee.BirthDate[1] = (DateTime.Now.AddDays(-3));
                employee.Childs = new EmployeeCommonType[2];
                employee.Childs[0] = (new EmployeeCommonType() { Id = Guid.NewGuid() });
                employee.Childs[1] = (new EmployeeCommonType() { Id = Guid.NewGuid() });
                employee.FavoriteColor = new Color[2];
                employee.FavoriteColor[0] = (Color.Red);
                employee.FavoriteColor[1] = (Color.Blue);
                employee.Height = new short[2];
                employee.Height[0] = (323);
                employee.Height[1] = (333);
                employee.Ids = new Guid[2];
                employee.Ids[0] = (Guid.NewGuid());
                employee.Ids[1] = (Guid.NewGuid());
                employee.IsMarried = new bool[2];
                employee.IsMarried[0] = (true);
                employee.IsMarried[1] = (false);
                employee.Salary = new decimal[2];
                employee.Salary[0] = ((decimal)1234567890.123456789);
                employee.Salary[1] = ((decimal)1234567890.123456799);
                employee.Tall = new long[2];
                employee.Tall[0] = (3233);
                employee.Tall[1] = (3234);
                employee.YearlyIncome = new double[2];
                employee.YearlyIncome[0] = (3233);
                employee.YearlyIncome[1] = (1234);

                var document = db.Insert<EmployeeArrayType>(employee).Run();

                var result = db.Query<EmployeeArrayType>("SELECT * FROM " + employeeClassName + " WHERE Id = '" + employee.Id + "'").SingleOrDefault();

                Assert.AreEqual(employee.Id, result.Id);
                Assert.AreEqual(employee.Ids[0], result.Ids[0]);
                Assert.AreEqual(employee.Ids[1], result.Ids[1]);
                Assert.AreEqual(employee.Name[0], result.Name[0]);
                Assert.AreEqual(employee.Name[1], result.Name[1]);
                Assert.AreEqual(employee.Age[0], result.Age[0]);
                Assert.AreEqual(employee.Age[1], result.Age[1]);
                Assert.AreEqual(employee.Age[0], result.Age[0]);
                Assert.AreEqual(employee.Salary[0], result.Salary[0]);
                Assert.AreEqual(employee.Salary[1], result.Salary[1]);
                Assert.AreEqual(employee.IsMarried[0], result.IsMarried[0]);
                Assert.AreEqual(employee.IsMarried[1], result.IsMarried[1]);
                Assert.AreEqual(employee.Childs[0].Id, result.Childs[0].Id);
                Assert.AreEqual(employee.Childs[1].Id, result.Childs[1].Id);
                Assert.AreEqual(employee.BirthDate[0].ToLongDateString(), result.BirthDate[0].ToLongDateString());
                Assert.AreEqual(employee.BirthDate[1].ToLongDateString(), result.BirthDate[1].ToLongDateString());
                Assert.AreEqual(employee.YearlyIncome[0], result.YearlyIncome[0]);
                Assert.AreEqual(employee.YearlyIncome[1], result.YearlyIncome[1]);
                Assert.AreEqual(employee.FavoriteColor[0], result.FavoriteColor[0]);
                Assert.AreEqual(employee.FavoriteColor[1], result.FavoriteColor[1]);
                Assert.AreEqual(employee.Height[0], result.Height[0]);
                Assert.AreEqual(employee.Height[1], result.Height[1]);
                Assert.AreEqual(employee.Tall[0], result.Tall[0]);
                Assert.AreEqual(employee.Tall[1], result.Tall[1]);

            }
        }
        static void CreateDatabasePoolTest()
        {
            OClient.CreateDatabasePool(
                    "localhost",
                    2424,
                    "GratefulDeadConcerts",
                    ODatabaseType.Graph,
                    "root",
                    "root",
                    10,
                    "AppConnection"
                );

            using (var database = new ODatabase("AppConnection"))
            {
                var documents = database.Query("select from v");
                foreach (var item in documents)
                {
                    System.Console.WriteLine("Name: {0} Type: {1}",
                        item.GetField<string>("name"), item.GetField<string>("type"));
                }
            }

            OClient.DropDatabasePool("AppConnection");
        }
        public void GIVEN___EmployeeDictionaryType_class_with_common_data_type___WHEN___write_to_orientdb___THEN___should_be_able_to_read()
        {
            using (TestDatabaseContext testContext = new TestDatabaseContext())
            using (var db = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
            {
                var employeeClassName = "EmployeeDictionaryType";

                var clusterid = db.Create.Class(employeeClassName).Run();

                var employee = new EmployeeDictionaryType();
                employee.Id = Guid.NewGuid();
                employee.Name = new Dictionary<string, string>();
                employee.Name.Add("Andrew", "Andrew");
                employee.Name.Add("Jack", "Jack");
                employee.Ids = new Dictionary<Guid, Guid>();
                employee.Ids.Add(Guid.NewGuid(), Guid.NewGuid());
                employee.Ids.Add(Guid.NewGuid(), Guid.NewGuid());
                employee.Age = new Dictionary<int, int>();
                employee.Age.Add(1, 2);
                employee.Age.Add(2, 4);
                employee.Height = new Dictionary<short, short>();
                employee.Height.Add(1, 2);
                employee.Height.Add(2, 4);
                employee.Tall = new Dictionary<long, long>();
                employee.Tall.Add(1234567890123456789, 987654321098765432);
                employee.Tall.Add(987654321098765432, 1234567890123456789);
                employee.Childs = new Dictionary<int, EmployeeCommonType>();
                employee.Childs.Add(1, new EmployeeCommonType() { Id = Guid.NewGuid() });
                employee.Childs.Add(2, new EmployeeCommonType() { Id = Guid.NewGuid() });
                employee.FavoriteColor = new Dictionary<Color, Color>();
                employee.FavoriteColor.Add(Color.Red, Color.Red);
                employee.FavoriteColor.Add(Color.Blue, Color.Blue);


                var document = db.Insert(employee).Into(employeeClassName).Run();

                var result = db.Query<EmployeeDictionaryType>("SELECT * FROM " + employeeClassName + " WHERE Id = '" + employee.Id + "'").SingleOrDefault();

                Assert.Equal(employee.Id, result.Id);
                Assert.True(result.Name.ContainsKey("Jack"));
                Assert.True(result.Name.ContainsKey("Andrew"));
                Assert.Equal(employee.Name["Jack"], result.Name["Jack"]);
                Assert.Equal(employee.Name["Andrew"], result.Name["Andrew"]);

                Assert.True(result.Ids.ContainsKey(employee.Ids.Keys.ToArray()[0]));
                Assert.True(result.Ids.ContainsKey(employee.Ids.Keys.ToArray()[1]));
                Assert.Equal(employee.Ids[employee.Ids.Keys.ToArray()[0]], result.Ids[employee.Ids.Keys.ToArray()[0]]);
                Assert.Equal(employee.Ids[employee.Ids.Keys.ToArray()[1]], result.Ids[employee.Ids.Keys.ToArray()[1]]);

                Assert.True(result.Age.ContainsKey(1));
                Assert.True(result.Age.ContainsKey(2));
                Assert.Equal(employee.Age[1], result.Age[1]);
                Assert.Equal(employee.Age[2], result.Age[2]);

                Assert.True(result.Height.ContainsKey(employee.Height.Keys.ToArray()[0]));
                Assert.True(result.Height.ContainsKey(employee.Height.Keys.ToArray()[1]));
                Assert.Equal(employee.Height[employee.Height.Keys.ToArray()[0]], result.Height[employee.Height.Keys.ToArray()[0]]);
                Assert.Equal(employee.Height[employee.Height.Keys.ToArray()[1]], result.Height[employee.Height.Keys.ToArray()[1]]);

                Assert.True(result.Tall.ContainsKey(employee.Tall.Keys.ToArray()[0]));
                Assert.True(result.Tall.ContainsKey(employee.Tall.Keys.ToArray()[1]));
                Assert.Equal(employee.Tall[employee.Tall.Keys.ToArray()[0]], result.Tall[employee.Tall.Keys.ToArray()[0]]);
                Assert.Equal(employee.Tall[employee.Tall.Keys.ToArray()[1]], result.Tall[employee.Tall.Keys.ToArray()[1]]);

                Assert.Equal(employee.Childs[1].Id, result.Childs[1].Id);
                Assert.Equal(employee.Childs[2].Id, result.Childs[2].Id);

                Assert.True(result.FavoriteColor.ContainsKey(Color.Red));
                Assert.True(result.FavoriteColor.ContainsKey(Color.Blue));
                Assert.Equal(employee.FavoriteColor[Color.Red], result.FavoriteColor[Color.Red]);
                Assert.Equal(employee.FavoriteColor[Color.Blue], result.FavoriteColor[Color.Blue]);

            }
        }
        static long Do()
        {
            DateTime start = DateTime.Now;
            bool running = true;
            long tps = 0;

            do
            {
                ODatabase database = new ODatabase(_alias);

                //List<ORecord> result = database.Query("select name from OGraphVertex where in[0].label = 'followed_by' and in[0].out.name = 'JAM'");
                //List<ORecord> result = database.Query("select from OGraphVertex limit 20");
                List<ORecord> result = database.Query("select from OGraphEdge limit 20");

                database.Close();
                tps++;

                TimeSpan dif = DateTime.Now - start;

                if (dif.TotalMilliseconds > 1000)
                {
                    running = false;
                }
            }
            while (running);

            return tps;
        }
        public void ShouldInsertClassWithEmbededList()
        {
            using (TestDatabaseContext testContext = new TestDatabaseContext())
            using (var db = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
            {
                var employeeListTypeClassName = "EmployeeListType";

                var clusterid = db.Create.Class(employeeListTypeClassName).Run();

                var employee = new EmployeeListType();
                employee.Id = Guid.NewGuid();
                employee.Name = new List<string>();
                employee.Name.Add("Andrew");
                employee.Name.Add("Jack");
                employee.Age = new List<int>();
                employee.Age.Add(1);
                employee.Age.Add(2);
                employee.BirthDate = new List<DateTime>();
                employee.BirthDate.Add(DateTime.Now);
                employee.BirthDate.Add(DateTime.Now.AddDays(-3));
                employee.Childs = new List<EmployeeCommonType>();
                employee.Childs.Add(new EmployeeCommonType() { Id = Guid.NewGuid() });
                employee.Childs.Add(new EmployeeCommonType() { Id = Guid.NewGuid() });
                employee.FavoriteColor = new List<Color>();
                employee.FavoriteColor.Add(Color.Red);
                employee.FavoriteColor.Add(Color.Blue);
                employee.Height = new List<short>();
                employee.Height.Add(323);
                employee.Height.Add(333);
                employee.Ids = new List<Guid>();
                employee.Ids.Add(Guid.NewGuid());
                employee.Ids.Add(Guid.NewGuid());
                employee.IsMarried = new List<bool>();
                employee.IsMarried.Add(true);
                employee.IsMarried.Add(false);
                employee.Salary = new List<decimal>();
                employee.Salary.Add((decimal)1234567890.123456789);
                employee.Salary.Add((decimal)1234567890.123456799);
                employee.Tall = new List<long>();
                employee.Tall.Add(3233);
                employee.Tall.Add(3234);
                employee.YearlyIncome = new List<double>();
                employee.YearlyIncome.Add(3233);
                employee.YearlyIncome.Add(1234);

                var document = db.Insert<EmployeeListType>(employee).Run();

                var result = db.Query<EmployeeListType>("SELECT * FROM " + employeeListTypeClassName + " WHERE Id = '" + employee.Id + "'").SingleOrDefault();

                Assert.Equal(employee.Id, result.Id);
                Assert.Equal(employee.Ids[0], result.Ids[0]);
                Assert.Equal(employee.Ids[1], result.Ids[1]);
                Assert.Equal(employee.Name[0], result.Name[0]);
                Assert.Equal(employee.Name[1], result.Name[1]);
                Assert.Equal(employee.Age[0], result.Age[0]);
                Assert.Equal(employee.Age[1], result.Age[1]);
                Assert.Equal(employee.Age[0], result.Age[0]);
                Assert.Equal(employee.Salary[0], result.Salary[0]);
                Assert.Equal(employee.Salary[1], result.Salary[1]);
                Assert.Equal(employee.IsMarried[0], result.IsMarried[0]);
                Assert.Equal(employee.IsMarried[1], result.IsMarried[1]);

                // Error happen here.
                Assert.Equal(employee.Childs[0].Id, result.Childs[0].Id);
                Assert.Equal(employee.Childs[1].Id, result.Childs[1].Id);
                Assert.Equal(employee.BirthDate[0].ToLongDateString(), result.BirthDate[0].ToLongDateString());
                Assert.Equal(employee.BirthDate[1].ToLongDateString(), result.BirthDate[1].ToLongDateString());
                Assert.Equal(employee.YearlyIncome[0], result.YearlyIncome[0]);
                Assert.Equal(employee.YearlyIncome[1], result.YearlyIncome[1]);
                Assert.Equal(employee.FavoriteColor[0], result.FavoriteColor[0]);
                Assert.Equal(employee.FavoriteColor[1], result.FavoriteColor[1]);
                Assert.Equal(employee.Height[0], result.Height[0]);
                Assert.Equal(employee.Height[1], result.Height[1]);
                Assert.Equal(employee.Tall[0], result.Tall[0]);
                Assert.Equal(employee.Tall[1], result.Tall[1]);

            }
        }
        static void ConnectionPoolTest()
        {
            using (TestDatabaseContext testContext = new TestDatabaseContext())
            {
                using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
                {
                    database
                        .Create.Class("Person")
                        .Extends<OVertex>()
                        .Run();

                    database
                        .Create.Class("Spouse")
                        .Extends<OVertex>()
                        .Run();

                    ODocument person1 = database
                        .Create.Vertex("Person")
                        .Set("Name", "Johny")
                        .Run();

                    ODocument spouse1 = database
                        .Create.Vertex("Spouse")
                        .Set("Name", "Mary")
                        .Run();

                    ODocument spouse2 = database
                        .Create.Vertex("Spouse")
                        .Set("Name", "Julia")
                        .Run();

                    // TODO: check what happens in command execution
                    ODocument edge1 = database
                        .Create.Edge<OEdge>()
                        .From(person1)
                        .To(spouse1)
                        .Run();

                    ODocument edge2 = database
                        .Create.Edge<OEdge>()
                        .From(person1)
                        .To(spouse2)
                        .Run();

                    List<ODocument> docs = database.Query("select from Person");
                }

                bool exit = false;

                using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
                {
                    database
                        .Create.Class("TestClass")
                        .Extends<OVertex>()
                        .Run();

                    database
                        .Create.Vertex("TestClass")
                        .Set("foo", "foo string value 1")
                        .Set("bar", 123)
                        .Run();

                    database
                        .Create.Vertex("TestClass")
                        .Set("foo", "foo string value 2")
                        .Set("bar", 1233)
                        .Run();
                }

                while (!exit)
                {
                    System.Console.WriteLine(
                        "Current pool size: {0} @ {1} : {2}",
                        OClient.DatabasePoolCurrentSize(TestConnection.GlobalTestDatabaseAlias),
                        DateTime.Now.ToString(),
                        Query().Count
                    );

                    string line = System.Console.ReadLine();

                    if (line.Equals("exit"))
                    {
                        exit = true;
                    }
                }
            }
        }
Exemple #44
0
        static void TestQuery()
        {
            using (ODatabase database = new ODatabase(_hostname, _port, _databaseName, ODatabaseType.Document, _username, _password))
            {
                TestClass obj = database.LoadRecord<TestClass>(new ORID(6, 0));

                foreach (string s in database.Query("select from cluster:ouser"))
                {
                    Console.WriteLine(s);
                }
            }
        }
        public void ShouldFetchDocumentsConnectedByEdges()
        {
            using (TestDatabaseContext testContext = new TestDatabaseContext())
            {
                using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias))
                {
                    // Need to set this 
                    database.Command("alter database custom useLightweightEdges=true");

                    database.Create.Class("House").Extends("V").Run();

                    database.Create.Class("Person").Extends("V").Run();
                    database.Create.Class("Owns").Extends("E").Run();

                    var house = new ODocument { OClassName = "House" };
                    database.Create.Vertex(house).Run();

                    var person = new ODocument { OClassName = "Person" };
                    person.SetField("name", "Shawn");
                    database.Create.Vertex(person).Run();

                    var person1 = new ODocument { OClassName = "Person" };
                    person1.SetField("name", "Roman");
                    database.Create.Vertex(person1).Run();

                    database.Create.Edge("Owns").From(person).To(house).Run();
                    database.Create.Edge("Owns").From(person1).To(house).Run();

                    house = database.Query("select from House", "*:-1").FirstOrDefault();

                    Assert.That(house != null);

                    Assert.That(database.ClientCache.Count(), Is.EqualTo(2), "client cache should contain two records");
                }
            }
        }