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 void truncateDatabase() { using (ODatabase database = new ODatabase(opts)) { string queryTruncateUser = string.Format("truncate class User unsafe"); string queryTruncateFriend = string.Format("truncate class Friend unsafe"); OCommandResult commandResult = database.Command(queryTruncateUser); commandResult = database.Command(queryTruncateFriend); } }
public void ProblemDeseralizingObjectWithDateTimeFields_31() { using (TestDatabaseContext testContext = new TestDatabaseContext()) using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { var startRecords = database.CountRecords; // explicitly setting the timezone to UTC instead of the JVM default timezone // FIXME: this is a work around for now database.Command("ALTER DATABASE TIMEZONE UTC"); database.Create.Class<File>().Extends<OVertex>().CreateProperties().Run(); var dateTime = DateTime.UtcNow; // OrientDB truncates milliseconds, so do so here for a proper comparison dateTime = dateTime.AddTicks( - (dateTime.Ticks % TimeSpan.TicksPerSecond)); database.Insert(new File { Filename = "myfile", Created = dateTime }).Run(); var doc = database.Select().From<File>().ToList().First(); var file = doc.To<File>(); // FIXME: the time zone is off Assert.That(file.Created, Is.EqualTo(dateTime)); var endRecords = database.CountRecords; Assert.AreEqual(startRecords + 1, endRecords); } }
public void ProblemDeseralizingObjectWithDateTimeFields_31() { using (TestDatabaseContext testContext = new TestDatabaseContext()) using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { var startRecords = database.CountRecords; // explicitly setting the timezone to UTC instead of the JVM default timezone // FIXME: this is a work around for now database.Command("ALTER DATABASE TIMEZONE UTC"); database.Create.Class <File>().Extends <OVertex>().CreateProperties().Run(); var dateTime = DateTime.UtcNow; // OrientDB truncates milliseconds, so do so here for a proper comparison dateTime = dateTime.AddTicks(-(dateTime.Ticks % TimeSpan.TicksPerSecond)); database.Insert(new File { Filename = "myfile", Created = dateTime }).Run(); var doc = database.Select().From <File>().ToList().First(); var file = doc.To <File>(); // FIXME: the time zone is off Assert.That(file.Created, Is.EqualTo(dateTime)); var endRecords = database.CountRecords; Assert.AreEqual(startRecords + 1, endRecords); } }
public void ShouldInsertDocumentIntoCluster() { using (TestDatabaseContext testContext = new TestDatabaseContext()) { using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { // prerequisites database .Create.Class("TestClass") .Run(); database .Create.Cluster("TestCluster", OClusterType.Physical) .Run(); database.Command("alter class TestClass addcluster TestCluster"); ODocument document = new ODocument() .SetField("foo", "foo string value") .SetField("bar", 12345); ODocument insertedDocument = database .Insert(document) .Into("TestClass") .Cluster("TestCluster") .Run(); Assert.IsTrue(insertedDocument.ORID != null); Assert.AreEqual(insertedDocument.OClassName, "TestClass"); Assert.AreEqual(insertedDocument.GetField <string>("foo"), document.GetField <string>("foo")); Assert.AreEqual(insertedDocument.GetField <int>("bar"), document.GetField <int>("bar")); } } }
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)); } } } }
/// <summary> /// Thêm đối tượng /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnThem_Click(object sender, EventArgs e) { ODatabase database = opentDatabase(); NhanVien nv = new NhanVien(txtHoTen.Text, dtpNgaySinh.Value, txtDiaChi.Text, cbbGioiTinh.Text, int.Parse(txtID.Text)); database.Command("INSERT INTO NhanVien(HoTenNV,DiaChi,NgaySinh,GioiTinh,ID) VALUES ('" + nv.hoTen + "','" + nv.diaChi + "','" + nv.ngaySinh + "','" + nv.gioiTinh + "','" + txtID.Text + "')"); LoadData(); }
//Egyszerű sql utasításokkal tölt fel, a for ciklusban beállított dokumentumokra. //Aminerekhez, public static void AThreadProc1() { OServer server = Server.Connect(); ODatabase database = new ODatabase("localhost", 2424, "TreeOfScience", ODatabaseType.Graph, "admin", "admin"); string url, json; Vertex v; AminerVertex a = new AminerVertex { }; url = @"F:\graph\aminer_papers_"; for (int i = 0; i < 1 /*55*/; i++) { using (StreamReader sr = File.OpenText(url + i + ".txt")) { while ((json = sr.ReadLine()) != null) { v = JsonConvert.DeserializeObject <Vertex>(json); if (v.authors != null) { for (int currentAuthor = 0; currentAuthor < v.authors.Length; currentAuthor++) { v.authors[currentAuthor].@class = "Author"; v.authors[currentAuthor].@type = "d"; } } a.aminer_id = v.id; a.title = v.title; a.authors = v.authors; a.year = v.year; a.venue = v.venue; a.keywords = v.keywords; a.fos = v.fos; a.n_citation = v.n_citation; a.references = v.references; a.page_stat = v.page_stat; a.page_end = v.page_end; a.doc_type = v.doc_type; a.lang = v.lang; a.publisher = v.publisher; a.volume = v.volume; a.issue = v.issue; a.issn = v.issn; a.isbn = v.isbn; a.doi = v.doi; a.pdf = v.pdf; a.url = v.url; a.Abstract = v.Abstract; json = JsonConvert.SerializeObject(a).Replace("Abstract", "abstract").Replace("type", "@type").Replace("class", "@class").Replace("doc_@type", "doc_type"); database.Command("INSERT INTO Document CONTENT " + json); } } Console.WriteLine("a" + i); } }
/// <summary> /// upload cell /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSua_Click(object sender, EventArgs e) { dataGridView1.Rows.Clear(); ODatabase database = opentDatabase(); NhanVien nv = new NhanVien(txtHoTen.Text, dtpNgaySinh.Value, txtDiaChi.Text, cbbGioiTinh.Text, int.Parse(txtID.Text)); database.Command("UPDATE NhanVien SET HoTenNV='" + nv.hoTen + "', DiaChi='" + nv.diaChi + "', NgaySinh='" + nv.ngaySinh + "', GioiTinh='" + nv.gioiTinh + "' WHERE ID=" + int.Parse(txtID.Text)); LoadData(); }
/// <summary> /// Xóa đối tượng /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnXoa_Click(object sender, EventArgs e) { dataGridView1.Rows.Clear(); ODatabase database = opentDatabase(); //NhanVien nv = new NhanVien(txtHoTen.Text, dtpNgaySinh.Value, txtDiaChi.Text, cbbGioiTinh.Text, int.Parse(txtID.Text)); database.Command("DELETE VERTEX NhanVien WHERE ID=" + int.Parse(txtID.Text)); LoadData(); }
public void ShouldExecuteQueryAfterClassIsChanged() { _database.Create.Vertex("TestClass") .Set("Name", "First Vertex") .Run(); // Get clusters for class TestClass before changes var clustersBefore = _database.Schema.GetClustersForClass("TestClass"); Assert.Equal(1, clustersBefore.Count()); var result = _database.Command("ALTER CLASS TestClass Name Test"); var cluster2id = _database.Create .Cluster("TestClassCluster2", OClusterType.Physical) .Run(); _database.Command("alter class Test addcluster TestClassCluster2"); var clustersAfter = _database.Schema.GetClustersForClass("Test"); Assert.Equal(2, clustersAfter.Count()); var doc = _database .Create .Vertex("Test") .Set("Name", "Second Vertex") .Run(); var doc1 = _database .Create .Vertex("Test") .Cluster("TestClassCluster2") .Set("Name", "Third Vertex in same class but another cluster") .Run(); Assert.Equal(_clusterId, doc.ORID.ClusterId); Assert.Equal(cluster2id, doc1.ORID.ClusterId); }
static void Main(string[] args) { //var db = new Orient.Client.ODatabase("10.10.116.6", 2480, "test", ODatabaseType.Document, "root", "Administrator"); //var b = db.DatabaseProperties.OClassName.Length; //db.Create.Document(RedditModel.GetDemo()); //var _server = new OServer("10.10.116.6", 2424, "root", "Administrator"); //if(!_server.DatabaseExist("test", OStorageType.Memory)); var connectionOptyion = new ConnectionOptions() { DatabaseType = ODatabaseType.Document, Port = 2424, Password = "******", HostName = "10.10.116.6", DatabaseName = "test", UserName = "******" }; using (ODatabase database = new ODatabase(connectionOptyion)) { database.Command("TRUNCATE CLASS RedditModel"); // prerequisites if (!database.Schema.IsClassExist("TweeterModel")) { database .Create.Class("TweeterModel") .Run(); } var mf = new ModelFactory(); ModelFactory.Populate(ModelDataType.Reddit, 10); var model = mf.GetDemoModel(ModelDataType.Reddit); var doc = model.ToDocument(); var data = database.Select("*").From("RedditModel").Where("Id=" + 7).ToList <RedditModel>(); database.Create.Document(typeof(RedditModel).Name).Set(doc).Run(); } var a = new RavenDbBenchmark(); ModelFactory.Populate(ModelDataType.Reddit, 1000); a.Test <RedditModel>(new EqualReadWriteStrategy() { CountOfOperations = 1000 }); }
public void TestOrderedEdges() { using (TestDatabaseContext testContext = new TestDatabaseContext()) { using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { database.Create.Class<Widget>().Extends("V").CreateProperties().Run(); database.Create.Class<WidgetVersion>().Extends("V").CreateProperties().Run(); database.Create.Class("VersionOf").Extends("E").Run(); database.Command(string.Format("create property {0}.out link {1}", "VersionOf", typeof(WidgetVersion).Name)); database.Command(string.Format("create property {0}.in link {1}", "VersionOf", typeof(Widget).Name)); database.Command(string.Format("create property {1}.in_{0} ANY", "VersionOf", typeof(Widget).Name)); database.Command(string.Format("alter property {1}.in_{0} custom ordered=true", "VersionOf", typeof(Widget).Name)); var w1 = new Widget() {Value = 12}; var wv1 = new WidgetVersion() {Value = 23}; var wv2 = new WidgetVersion() { Value = 34 }; var v1 = database.Create.Vertex(w1).Run(); var v2 = database.Create.Vertex(wv1).Run(); var v3 = database.Create.Vertex(wv2).Run(); database.Create.Edge("VersionOf").From(v1).To(v2).Run(); database.Create.Edge("VersionOf").From(v1).To(v3).Run(); var loaded1 = database.Load.ORID(v1.ORID).Run(); var typed1 = loaded1.To<Widget>(); Assert.AreEqual(2, typed1.out_VersionOf.Count); Assert.AreEqual(12, typed1.Value); var loaded2 = database.Load.ORID(v2.ORID).Run(); var typed2 = loaded2.To<WidgetVersion>(); Assert.AreNotEqual(null, typed2.in_VersionOf); } } }
/// <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(databaseAlias)) { foreach (VK.VKMan User in Users) { Console.WriteLine("User has been added"); OCommandResult commandResult = database.Command(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, "1900-10-10 00:00:00", User.country, User.city, User.interests, User.music, User.movies, User.games, User.about) ); var test = commandResult.ToDocument()["ORID"]; User.ORID = commandResult.ToDocument().ORID.ToString(); database.Command(string.Format("CREATE EDGE FROM {0} TO {1} SET weight={2}", rootUser.ORID, User.ORID, calculateWeigth())); var i = 0; } return(true); } }
public void ShouldCreateDocumentsWithPreparedCommandByName() { var createQuery = new PreparedCommand("insert into Profile set name = :name , surname = :surname"); var values = new[] { new { Name = "Pura", Surname = "Shields" }, new { Name = "Deedra", Surname = "Bonura" }, new { Name = "Foster", Surname = "Coppin" }, new { Name = "Bradly", Surname = "Sanzone" } }; foreach (var item in values) { var createdDoc = _database.Command(createQuery) .Set("name", item.Name) .Set("surname", item.Surname) .Run().ToSingle(); Assert.That(createdDoc.ORID, Is.Not.Null); Assert.That(createdDoc.GetField <string>("name"), Is.EqualTo(item.Name)); Assert.That(createdDoc.GetField <string>("surname"), Is.EqualTo(item.Surname)); } }
public void TestOrderedEdges() { using (TestDatabaseContext testContext = new TestDatabaseContext()) using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { database.Command("alter database custom useLightweightEdges=false"); database.Create.Class <Widget>().Extends("V").CreateProperties().Run(); database.Create.Class <WidgetVersion>().Extends("V").CreateProperties().Run(); database.Create.Class("VersionOf").Extends("E").Run(); var w1 = new Widget() { Value = 12 }; var wv1 = new WidgetVersion() { Value = 23 }; var wv2 = new WidgetVersion() { Value = 34 }; var v1 = database.Create.Vertex(w1).Run(); var v2 = database.Create.Vertex(wv1).Run(); var v3 = database.Create.Vertex(wv2).Run(); var e1 = database.Create.Edge("VersionOf").From(v1).To(v2).Run(); var e2 = database.Create.Edge("VersionOf").From(v1).To(v3).Run(); var loaded1 = database.Load.ORID(v1.ORID).Run <Widget>(); Assert.Equal(2, loaded1.out_VersionOf.Count); Assert.True(loaded1.out_VersionOf.Contains(e1.ORID)); Assert.True(loaded1.out_VersionOf.Contains(e2.ORID)); Assert.Equal(12, loaded1.Value); var loaded2 = database.Load.ORID(v2.ORID).Run <WidgetVersion>(); Assert.NotNull(loaded2.in_VersionOf); Assert.Equal(1, loaded2.in_VersionOf.Count); Assert.Equal(23, loaded2.Value); Assert.True(loaded2.in_VersionOf.Contains(e1.ORID)); var loaded3 = database.Load.ORID(v3.ORID).Run <WidgetVersion>(); Assert.NotNull(loaded3.in_VersionOf); Assert.Equal(1, loaded3.in_VersionOf.Count); Assert.Equal(34, loaded3.Value); Assert.True(loaded3.in_VersionOf.Contains(e2.ORID)); } }
//Éleket tölt fel, jelenleg nem működik megfelelően. public static void Edge1() { try { OServer server = Server.Connect(); ODatabase database = new ODatabase("localhost", 2424, "TreeOfScience", ODatabaseType.Graph, "admin", "admin"); string url, json; Vertex v; AminerVertex a = new AminerVertex { }; url = @"F:\graph\aminer_papers_"; for (int i = 0; i < 1; i++) { using (StreamReader sr = File.OpenText(url + i + ".txt")) { while ((json = sr.ReadLine()) != null) { v = JsonConvert.DeserializeObject <Vertex>(json); a.aminer_id = v.id; a.references = v.references; if (a.references != null) { if (a.references.Length != 0) { foreach (string refr in a.references) { //if (a.references.Length != 0) foreach (string refr in a.references) //{ // database.Command("create edge from (select from document where aminer_id = '" + a.aminer_id + "') to (select from document where aminer_id = '" + refr + "')"); //} for (int refn = 0; refn < a.references.Length; refn++) { database.Command("create edge from (select from document where aminer_id = '" + a.aminer_id + "') to (select from document where aminer_id = '" + a.references[refn] + "')"); } } } } } } Console.WriteLine("a" + i); } } catch (OException e) { Console.WriteLine(e.Message); } }
/// <summary> /// Записать в базу список пользователей (без связей) /// </summary> /// <param name="Users"></param> /// <returns></returns> public bool WriteVKUsers(List <VK.VKMan> Users) { using (ODatabase database = new ODatabase(databaseAlias)) { foreach (VK.VKMan User in Users) { Console.WriteLine("User has been added"); OCommandResult commandResult = database.Command(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, User.about) ); User.ORID = commandResult.ToDocument().ORID.ToString(); } return(true); } }
public void TestOrderedEdges() { using (TestDatabaseContext testContext = new TestDatabaseContext()) using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { database.Command("alter database custom useLightweightEdges=false"); database.Create.Class<Widget>().Extends("V").CreateProperties().Run(); database.Create.Class<WidgetVersion>().Extends("V").CreateProperties().Run(); database.Create.Class("VersionOf").Extends("E").Run(); var w1 = new Widget() { Value = 12 }; var wv1 = new WidgetVersion() { Value = 23 }; var wv2 = new WidgetVersion() { Value = 34 }; var v1 = database.Create.Vertex(w1).Run(); var v2 = database.Create.Vertex(wv1).Run(); var v3 = database.Create.Vertex(wv2).Run(); var e1 = database.Create.Edge("VersionOf").From(v1).To(v2).Run(); var e2 = database.Create.Edge("VersionOf").From(v1).To(v3).Run(); var loaded1 = database.Load.ORID(v1.ORID).Run<Widget>(); Assert.Equal(2, loaded1.out_VersionOf.Count); Assert.True(loaded1.out_VersionOf.Contains(e1.ORID)); Assert.True(loaded1.out_VersionOf.Contains(e2.ORID)); Assert.Equal(12, loaded1.Value); var loaded2 = database.Load.ORID(v2.ORID).Run<WidgetVersion>(); Assert.NotNull(loaded2.in_VersionOf); Assert.Equal(1, loaded2.in_VersionOf.Count); Assert.Equal(23, loaded2.Value); Assert.True(loaded2.in_VersionOf.Contains(e1.ORID)); var loaded3 = database.Load.ORID(v3.ORID).Run<WidgetVersion>(); Assert.NotNull(loaded3.in_VersionOf); Assert.Equal(1, loaded3.in_VersionOf.Count); Assert.Equal(34, loaded3.Value); Assert.True(loaded3.in_VersionOf.Contains(e2.ORID)); } }
/// <summary> /// Записать в базу список пользователей (без связей) /// </summary> /// <param name="Users"></param> /// <returns></returns> public bool WriteVKUsers(List <VK.VKMan> Users) { using (ODatabase database = new ODatabase(opts)) { foreach (VK.VKMan User in Users) { //TODO Т.к. мы вставляем через UPSERT, то не получаем ORID. Поэтому надо наверно через select по уникальному vkid его получать. Console.WriteLine("User has been added"); var strUpsert = 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 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); /* * OCommandResult commandResult = database.Command(String.Format("INSERT INTO user (first_name,last_name,sex,bday,country," + * "city,interests,music,movies,games,about, vkid)" + * "values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}', '{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) * ); */ OCommandResult commandResult = database.Command(queryString); //OCommandResult commandSelectORIDResult = database.Command(queryStringSelectORID); //Переделывал работу с ORIENT CLIENT //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(); } } return(true); } }
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.True(house != null); Assert.Equal(database.ClientCache.Count(), 2); // client cache should contain two records; } } }
public void ShouldCreateRecordContainingSingleQuote() { using (TestDatabaseContext testContext = new TestDatabaseContext()) using (var db = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { if (!db.Schema.IsClassExist<TestClass>()) { db.Create.Class<TestClass>().CreateProperties<TestClass>().Run(); } db.Command("delete from TestClass"); var text = @"Jim'n"; var test = new TestClass() { SomeString = text }; db.Insert(test).Run(); var result = db.Select().From<TestClass>().ToList<TestClass>(); Assert.Equal(text, result.Single().SomeString); } }
public void ShouldCreateEdgeClusterFromTo() { using (TestDatabaseContext testContext = new TestDatabaseContext()) { using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { // prerequisites database .Create.Class("TestEdgeClass") .Extends <OEdge>() .Run(); database .Create.Cluster("TestCluster", OClusterType.Physical) .Run(); var res = database.Command("alter class TestEdgeClass addcluster testcluster"); OVertex vertex1 = database .Create.Vertex <OVertex>() .Run(); OVertex vertex2 = database .Create.Vertex <OVertex>() .Run(); OEdge createdEdge = database .Create.Edge("TestEdgeClass") .Cluster("TestCluster") .From(vertex1.ORID) .To(vertex2.ORID) .Run(); Assert.NotNull(createdEdge.ORID); Assert.Equal("TestEdgeClass", createdEdge.Label); Assert.Equal("TestEdgeClass", createdEdge.OClassName); Assert.Equal(vertex2.ORID, createdEdge.InV); Assert.Equal(vertex1.ORID, createdEdge.OutV); } } }
public void ShouldCreateEdgeClusterFromTo() { using (TestDatabaseContext testContext = new TestDatabaseContext()) { using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { // prerequisites database .Create.Class("TestEdgeClass") .Extends<OEdge>() .Run(); database .Create.Cluster("TestCluster", OClusterType.Physical) .Run(); var res = database.Command("alter class TestEdgeClass addcluster testcluster"); OVertex vertex1 = database .Create.Vertex<OVertex>() .Run(); OVertex vertex2 = database .Create.Vertex<OVertex>() .Run(); OEdge createdEdge = database .Create.Edge("TestEdgeClass") .Cluster("TestCluster") .From(vertex1.ORID) .To(vertex2.ORID) .Run(); Assert.NotNull(createdEdge.ORID); Assert.Equal("TestEdgeClass", createdEdge.Label); Assert.Equal("TestEdgeClass", createdEdge.OClassName); Assert.Equal(vertex2.ORID, createdEdge.InV); Assert.Equal(vertex1.ORID, createdEdge.OutV); } } }
public void ShouldExecuteSimpleFunction() { using (TestDatabaseContext testContext = new TestDatabaseContext()) using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { database .Command("create function sum 'return parseInt(a)+parseInt(b);' parameters [a , b] language javascript"); var result = database .JavaScript("sum(a,b);") .Set("a",3) .Set("b",5) .Run() .ToSingle(); Assert.IsNotNull(result); Assert.AreEqual(1, result.Count); var actual = result.GetField<string>("value"); if (actual != "8") // 8 seems to come back from this call - maybe depends on exact version of OrientDB server?... Anyway, it's a good enough result { Assert.AreEqual("8.0d", actual); } } }
public void ShouldCreateRecordContainingSingleQuote() { using (TestDatabaseContext testContext = new TestDatabaseContext()) using (var db = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { if (!db.Schema.IsClassExist <TestClass>()) { db.Create.Class <TestClass>().CreateProperties <TestClass>().Run(); } db.Command("delete from TestClass"); var text = @"Jim'n"; var test = new TestClass() { SomeString = text }; db.Insert(test).Run(); var result = db.Select().From <TestClass>().ToList <TestClass>(); Assert.AreEqual(text, result.Single().SomeString); } }
public void ShouldExecuteSimpleFunction() { using (TestDatabaseContext testContext = new TestDatabaseContext()) using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { database .Command("create function sum 'return parseInt(a)+parseInt(b);' parameters [a , b] language javascript"); var result = database .JavaScript("sum(a,b);") .Set("a", 3) .Set("b", 5) .Run() .ToSingle(); Assert.IsNotNull(result); Assert.AreEqual(1, result.Count); var actual = result.GetField <string>("value"); if (actual != "8") // 8 seems to come back from this call - maybe depends on exact version of OrientDB server?... Anyway, it's a good enough result { Assert.AreEqual("8.0d", actual); } } }
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"); } } }
private bool CreateDatabaseIfNotExists(string hostname, int port, string user, string password, string database) { using (var server = new OServer(hostname, port, user, password)) { if (!server.DatabaseExist(database, OStorageType.PLocal)) { var created = server.CreateDatabase(database, ODatabaseType.Graph, OStorageType.PLocal); using (var db = new ODatabase("localhost", 2424, "txgraph", ODatabaseType.Graph, "admin", "admin")) { db.Command("CREATE CLASS Transaction EXTENDS V"); db.Command("CREATE PROPERTY Transaction.Hash STRING"); db.Command("CREATE INDEX IndexForHash ON Transaction (Hash) UNIQUE_HASH_INDEX"); db.Command("CREATE PROPERTY Transaction.BlockTime DATETIME"); db.Command("CREATE PROPERTY Transaction.Coinbase BOOLEAN"); db.Command("ALTER PROPERTY Transaction.Coinbase DEFAULT False"); db.Command("CREATE PROPERTY Transaction.Unlinked BOOLEAN"); db.Command("ALTER PROPERTY Transaction.Unlinked DEFAULT True"); db.Command("CREATE CLASS Link EXTENDS E"); db.Command("CREATE PROPERTY Link.sTx STRING"); db.Command("CREATE PROPERTY Link.sN LONG"); db.Command("CREATE PROPERTY Link.tTx STRING"); db.Command("CREATE PROPERTY Link.tAddr STRING"); db.Command("CREATE PROPERTY Link.amount LONG"); } return(created); } else { return(true); } } }
public void ShouldInsertIntoClusterSet() { using (TestDatabaseContext testContext = new TestDatabaseContext()) { using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { // prerequisites database .Create.Class("TestClass") .Run(); database .Create.Cluster("TestCluster", OClusterType.Physical) .Run(); database.Command("alter class TestClass addcluster TestCluster"); ODocument insertedDocument = database .Insert() .Into("TestClass") .Cluster("TestCluster") .Set("foo", "foo string value") .Set("bar", 12345) .Run(); Assert.IsTrue(insertedDocument.ORID != null); Assert.AreEqual(insertedDocument.OClassName, "TestClass"); Assert.AreEqual(insertedDocument.GetField<string>("foo"), "foo string value"); Assert.AreEqual(insertedDocument.GetField<int>("bar"), 12345); } } }
public void Example_For_Question57() { // create three classes extending V var personClusterId = _database.Create.Class("Persons").Extends("V").Run(); var cityClusterId = _database.Create.Class("Cities").Extends("V").Run(); var carsClusterId = _database.Create.Class("Cars").Extends("V").Run(); // create two edges extendin E var livesClusterId = _database.Create.Class("Lives").Extends("E").Run(); var ownsClusterId = _database.Create.Class("Owns").Extends("E").Run(); //inser sample data var persons = new[] { "Michael", "Roman", "Luca", "Nick", "Fredi" }; foreach (var p in persons) { _database.Insert().Into("Persons") .Set("Name", p) .Run(); } var cars = new[] { "Audi", "Subaru", "BMW", "Mazda" }; foreach (var c in cars) { _database.Insert().Into("Cars") .Set("Name", c) .Run(); } var cities = new[] { "London", "New York", "Shanghai", "Delhi", "Kabul" }; foreach (var c in cities) { _database.Insert().Into("Cities") .Set("Name", c) .Run(); } _database.Command("create edge Lives from (select from Persons where Name = 'Michael') to (select from Cities where Name = 'Kabul')"); _database.Command("create edge Lives from (select from Persons where Name = 'Roman') to (select from Cities where Name = 'London')"); _database.Command("create edge Lives from (select from Persons where Name = 'Luca') to (select from Cities where Name = 'New York')"); _database.Command("create edge Lives from (select from Persons where Name = 'Nick') to (select from Cities where Name = 'Kabul')"); _database.Command("create edge Lives from (select from Persons where Name = 'Fredi') to (select from Cities where Name = 'Delphi')"); _database.Command("create edge Owns from (select from Persons where Name = 'Fredi') to (select from Cars where Name in ['BMW','Subaru'])"); _database.Command("create edge Owns from (select from Persons where Name = 'Luca') to (select from Cars where Name in ['BMW','Subaru','Audi'])"); _database.Command("create edge Owns from (select from Persons where Name = 'Nick') to (select from Cars where Name in ['Mazda'])"); _database.Command("create edge Owns from (select from Persons where Name = 'Roman') to (select from Cars where Name in ['Subaru'])"); // Query vertex var vertexes = _database.Query("select from Persons"); foreach (var v in vertexes) { foreach (var kv in v) { Debug.WriteLine(String.Format("{0}: {1} ({2})", kv.Key, kv.Value, kv.Value.GetType())); } } // This is output of a program, all properties have strong type and outgoin and incoming edges // have format [out | in]_EDGECLASS and type is List<ORID> /* * * @ORID: #13:0 (Orient.Client.ORID) * @OVersion: 2 (System.Int32) * @OType: Document (Orient.Client.ORecordType) * @OClassId: 0 (System.Int16) * @OClassName: Persons (System.String) * Name: Michael (System.String) * out_Lives: System.Collections.Generic.List`1[Orient.Client.ORID] (System.Collections.Generic.List`1[Orient.Client.ORID]) * * @ORID: #13:1 (Orient.Client.ORID) * @OVersion: 3 (System.Int32) * @OType: Document (Orient.Client.ORecordType) * @OClassId: 0 (System.Int16) * @OClassName: Persons (System.String) * Name: Roman (System.String) * out_Lives: System.Collections.Generic.List`1[Orient.Client.ORID] (System.Collections.Generic.List`1[Orient.Client.ORID]) * out_Owns: System.Collections.Generic.List`1[Orient.Client.ORID] (System.Collections.Generic.List`1[Orient.Client.ORID]) * * @ORID: #13:2 (Orient.Client.ORID) * @OVersion: 5 (System.Int32) * @OType: Document (Orient.Client.ORecordType) * @OClassId: 0 (System.Int16) * @OClassName: Persons (System.String) * Name: Luca (System.String) * out_Lives: System.Collections.Generic.List`1[Orient.Client.ORID] (System.Collections.Generic.List`1[Orient.Client.ORID]) * out_Owns: System.Collections.Generic.List`1[Orient.Client.ORID] (System.Collections.Generic.List`1[Orient.Client.ORID]) * * @ORID: #13:3 (Orient.Client.ORID) * @OVersion: 3 (System.Int32) * @OType: Document (Orient.Client.ORecordType) * @OClassId: 0 (System.Int16) * @OClassName: Persons (System.String) * Name: Nick (System.String) * out_Lives: System.Collections.Generic.List`1[Orient.Client.ORID] (System.Collections.Generic.List`1[Orient.Client.ORID]) * out_Owns: System.Collections.Generic.List`1[Orient.Client.ORID] (System.Collections.Generic.List`1[Orient.Client.ORID]) * * @ORID: #13:4 (Orient.Client.ORID) * @OVersion: 3 (System.Int32) * @OType: Document (Orient.Client.ORecordType) * @OClassId: 0 (System.Int16) * @OClassName: Persons (System.String) * Name: Fredi (System.String) * out_Owns: System.Collections.Generic.List`1[Orient.Client.ORID] (System.Collections.Generic.List`1[Orient.Client.ORID]) * */ }
static void Main(string[] args) { List <Occupations> _lisOccupations = LoadOccupations(); #region try { OrientDBDriver.CreateDatabase(); OrientDBDriver.CreatePool(); ODatabase oDB = new ODatabase(OrientDBDriver.DatabaseAlias); // we are setting Database to useLightweightEdges set to True because currently // we don't need any properties in edges for User hasOccupationa and Movies_genres oDB.Command("ALTER DATABASE custom useLightweightEdges=true"); #region Load Occupation // First of all create Class of Occupation which extends from vertex class V Console.WriteLine("Creating VERTEX Occupation ...."); oDB.Create.Class <Occupations>().Extends <OVertex>().CreateProperties <Occupations>().Run(); foreach (Occupations occ in _lisOccupations) { oDB.Create.Vertex <Occupations>(occ).Run(); } Console.WriteLine("Successfully created Vertex Occupation"); #endregion #region Load Users List <Users> _listUsers = LoadUsers(); Console.WriteLine("Creating VERTEX Users with relation 'hasOccupation' using EDGE ...."); oDB.Create.Class <Users>().Extends <OVertex>().CreateProperties().Run(); oDB.Create.Class("hasOccupation").Extends <OEdge>().Run(); foreach (Users user in _listUsers) { ODocument odoc = oDB.Create.Vertex("Users") .Set("userID", user.userID) .Set("Gender", user.gender) // .Set("OccupationID",user.OccupationID) .Set("Age", user.age) .Set("ZipCode", user.ZipCode) .Run(); string generateSQL = new OSqlSelect().Select().From("Occupations").Where("OccupationID").Equals(user.OccupationID).Limit(1).ToString(); List <ODocument> result = oDB.Query(generateSQL); if (result.Count > 0) { OEdge edge = oDB.Create.Edge("hasOccupation").From(odoc.ORID).To(result[0].ORID).Run(); } } Console.WriteLine("Successfully created Vertex Users"); #endregion #region Load Genres List <Genres> _listGenres = LoadGenres(); Console.WriteLine("Creating VERTEX Genres ...."); oDB.Create.Class <Genres>().Extends <OVertex>().CreateProperties <Genres>().Run(); foreach (Genres g in _listGenres) { oDB.Create.Vertex <Genres>(g).Run(); } Console.WriteLine("Successfully created Vertex Occupation"); Console.WriteLine("Successfully created Vertex Genres"); #endregion #region Load Movies // ------------- Load Movies with Relation Genres----------------- List <Movies> _listMovies = LoadMovies(); Console.WriteLine("Creating VERTEX Movies ...."); oDB.Create.Class <Movies>().Extends <OVertex>().CreateProperties().Run(); oDB.Create.Class("hasGenera").Extends <OEdge>().Run(); foreach (Movies g in _listMovies) { ODocument odoc = oDB.Create.Vertex("Movies") .Set("MovieID", g.MovieID) .Set("Title", g.Title) .Run(); foreach (string genres in g.Genres) { string generateSQL = new OSqlSelect().Select().From("Genres").Where("description").Equals(genres).Limit(1).ToString(); List <ODocument> result = oDB.Query(generateSQL); if (result.Count > 0) { OEdge edge = oDB.Create.Edge("hasGenera").From(odoc.ORID).To(result[0].ORID).Run(); } } } Console.WriteLine("Successfully created Vertex Movies with relation has genres"); #endregion //---------- Load One Million I takes almost ~20mins in Core i7 6th Gen, 2.5 GHz processor with 8GB RAM // --- Waiting for response from OrientDB for Bulkinsert (massiveinsert) operaion support in .Net API #region Load Ratings oDB.Command("ALTER DATABASE custom useLightweightEdges=false"); oDB.Create.Class <Rated>().Extends <OEdge>().CreateProperties().Run(); oDB.Command("CREATE INDEX users.userID UNIQUE"); oDB.Command("CREATE INDEX Movies.movieID UNIQUE"); Console.WriteLine("Creating Ratings one Million...."); int i = 0; System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch(); st.Start(); List <Rating> _listRating = LoadRatings(_PathRatings); oDB.Transaction.Reset(); object locker = new object(); Parallel.ForEach(_listRating, r => { lock (locker) { i++; // we can also use OrientDB command to create Edges between two vertices oDB.Command(" create edge rated from (select from Users where userID = " + r.userID + ") to (select from Movies where MovieID = " + r.movieID + " ) set rating =" + r.Ratings + " "); Console.WriteLine("Creating Ratings...." + i.ToString()); } }); st.Stop(); Console.WriteLine("Successfully Created Ratings Transaction committed...." + st.Elapsed.TotalMinutes + "mins"); #endregion } catch (Exception ex) { Console.WriteLine(ex.Message); } #endregion Console.ReadLine(); }
public static void CreateEdgeCable(ORID o1, ORID o2, String firstNodeType, String secondNodeType, String connectionTypeValue, String CableTypeValue, LanCable lanCable, OpticCable opticCable) { ODatabase database = InitDB(); if ((firstNodeType == "Desktop" || firstNodeType == "Laptop" || firstNodeType == "Server") && (secondNodeType == "Router" || secondNodeType == "Switch")) { String query = "SELECT * FROM Computer WHERE @rid=" + o1.RID.ToString(); List <ODocument> resultset = database.Query(query).ToList(); JavaScriptSerializer converter = new JavaScriptSerializer(); List <Computer> AllComputers = new List <Computer>(); String macAddress1 = null; foreach (ODocument doc in resultset) { var json = converter.Serialize(doc); String a = json.ToString(); Computer d = converter.Deserialize <Computer>(a); AllComputers.Add(d); } Computer computer = null; if (AllComputers != null) { computer = AllComputers[0]; } macAddress1 = computer.LanMacAddress; String query1 = "SELECT * FROM Node WHERE @rid=" + o2.RID.ToString(); List <ODocument> resultset1 = database.Query(query1).ToList(); List <Node> AllNodes = new List <Node>(); foreach (ODocument doc in resultset1) { var json = converter.Serialize(doc); String a = json.ToString(); Node d = converter.Deserialize <Node>(a); AllNodes.Add(d); } Node node = null; if (AllNodes != null) { node = AllNodes[0]; } String macAddress2 = null; if (node != null) { if (node.NumberOfPorts != node.NumberOfTakenPorts) { node.NumberOfTakenPorts++; macAddress2 = node.MacAddressList.ElementAt(node.NumberOfTakenPorts - 1); } } if (connectionTypeValue == "Cable") { if (CableTypeValue == "Lan") { lanCable.End1 = macAddress1; lanCable.End2 = macAddress2; lanCable.Type = "Lan"; String addCableQuerry = "CREATE EDGE LanCable FROM " + o1.RID.ToString() + " TO " + o2.RID.ToString() + " SET End1 = \"" + lanCable.End1 + "\", End2 = \"" + lanCable.End2 + "\", Type=\"" + lanCable.Type + "\", Manufacturer=\"" + lanCable.Manufacturer + "\", Category=\"" + lanCable.Category + "\""; database.Command(addCableQuerry); if (node != null) { database.Update(o2) .Set("NumberOfPorts", node.NumberOfPorts) .Set("NumberOfTakenPorts", node.NumberOfTakenPorts) .Set("MacAddressList", node.MacAddressList).Run(); } return; } } else if (connectionTypeValue == "WiFi") { if (firstNodeType == "Laptop") { String queryL = "SELECT * FROM Laptop WHERE @rid=" + o1.RID.ToString(); List <ODocument> resultsetL = database.Query(queryL).ToList(); 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]; } macAddress1 = laptop.WifiMacAddress; } String query2 = "SELECT * FROM Router WHERE @rid=" + o2.RID.ToString(); List <ODocument> resultset2 = database.Query(query1).ToList(); List <Router> AllRouters = new List <Router>(); foreach (ODocument doc in resultset2) { 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]; } if (router != null) { macAddress2 = router.WiFiMacAddress; } WiFiConnection wificonnection = new WiFiConnection(); wificonnection.ClientMacAddress = macAddress1; wificonnection.HostMacAddress = macAddress2; wificonnection.WiFiNetworkName = router.WiFiNetworkName; String addWifiQuerry = "CREATE EDGE WiFiConnection FROM " + o1.RID.ToString() + " TO " + o2.RID.ToString() + " SET WiFiNetworkName = \"" + wificonnection.WiFiNetworkName + "\", HostMacAddress = \"" + wificonnection.HostMacAddress + "\", ClientMacAddress=\"" + wificonnection.ClientMacAddress + "\""; database.Command(addWifiQuerry); } } else if ((secondNodeType == "Desktop" || secondNodeType == "Laptop" || secondNodeType == "Server") && (firstNodeType == "Router" || firstNodeType == "Switch")) { String query = "SELECT * FROM Computer WHERE @rid=" + o2.RID.ToString(); List <ODocument> resultset = database.Query(query).ToList(); JavaScriptSerializer converter = new JavaScriptSerializer(); List <Computer> AllComputers = new List <Computer>(); String macAddress1 = null; foreach (ODocument doc in resultset) { var json = converter.Serialize(doc); String a = json.ToString(); Computer d = converter.Deserialize <Computer>(a); AllComputers.Add(d); } Computer computer = null; if (AllComputers != null) { computer = AllComputers[0]; } macAddress1 = computer.LanMacAddress; String query1 = "SELECT * FROM Node WHERE @rid=" + o1.RID.ToString(); List <ODocument> resultset1 = database.Query(query1).ToList(); List <Node> AllNodes = new List <Node>(); foreach (ODocument doc in resultset1) { var json = converter.Serialize(doc); String a = json.ToString(); Node d = converter.Deserialize <Node>(a); AllNodes.Add(d); } Node node = null; if (AllNodes != null) { node = AllNodes[0]; } String macAddress2 = null; if (node != null) { if (node.NumberOfPorts != node.NumberOfTakenPorts) { node.NumberOfTakenPorts++; macAddress2 = node.MacAddressList.ElementAt(node.NumberOfTakenPorts - 1); } } if (connectionTypeValue == "Cable") { if (CableTypeValue == "Lan") { lanCable.End1 = macAddress1; lanCable.End2 = macAddress2; lanCable.Type = "Lan"; String addCableQuerry = "CREATE EDGE LanCable FROM " + o2.RID.ToString() + " TO " + o1.RID.ToString() + " SET End1 = \"" + lanCable.End1 + "\", End2 = \"" + lanCable.End2 + "\", Type=\"" + lanCable.Type + "\", Manufacturer=\"" + lanCable.Manufacturer + "\", Category=\"" + lanCable.Category + "\""; database.Command(addCableQuerry); if (node != null) { database.Update(o1) .Set("NumberOfPorts", node.NumberOfPorts) .Set("NumberOfTakenPorts", node.NumberOfTakenPorts) .Set("MacAddressList", node.MacAddressList).Run(); } return; } } if (connectionTypeValue == "WiFi") { if (secondNodeType == "Laptop") { String queryL = "SELECT * FROM Laptop WHERE @rid=" + o2.RID.ToString(); List <ODocument> resultsetL = database.Query(queryL).ToList(); 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]; } macAddress1 = laptop.WifiMacAddress; } String query2 = "SELECT * FROM Router WHERE @rid=" + o1.RID.ToString(); List <ODocument> resultset2 = database.Query(query1).ToList(); List <Router> AllRouters = new List <Router>(); foreach (ODocument doc in resultset2) { 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]; } if (router != null) { macAddress2 = router.WiFiMacAddress; } WiFiConnection wificonnection = new WiFiConnection(); wificonnection.ClientMacAddress = macAddress1; wificonnection.HostMacAddress = macAddress2; wificonnection.WiFiNetworkName = router.WiFiNetworkName; String addWifiQuerry = "CREATE EDGE WiFiConnection FROM " + o2.RID.ToString() + " TO " + o1.RID.ToString() + " SET WiFiNetworkName = \"" + wificonnection.WiFiNetworkName + "\", HostMacAddress = \"" + wificonnection.HostMacAddress + "\", ClientMacAddress=\"" + wificonnection.ClientMacAddress + "\""; database.Command(addWifiQuerry); } } else if ((firstNodeType == "Desktop" || firstNodeType == "Laptop" || firstNodeType == "Server") && (secondNodeType == "Desktop" || secondNodeType == "Laptop" || secondNodeType == "Server")) { String query = "SELECT * FROM Computer WHERE @rid=" + o1.RID.ToString(); List <ODocument> resultset = database.Query(query).ToList(); JavaScriptSerializer converter = new JavaScriptSerializer(); List <Computer> AllComputers = new List <Computer>(); String macAddress1 = null; foreach (ODocument doc in resultset) { var json = converter.Serialize(doc); String a = json.ToString(); Computer d = converter.Deserialize <Computer>(a); AllComputers.Add(d); } Computer computer = null; if (AllComputers != null) { computer = AllComputers[0]; } macAddress1 = computer.LanMacAddress; String query1 = "SELECT * FROM Computer WHERE @rid=" + o2.RID.ToString(); List <ODocument> resultset1 = database.Query(query1).ToList(); List <Computer> AllComputers1 = new List <Computer>(); String macAddress2 = null; foreach (ODocument doc in resultset1) { var json = converter.Serialize(doc); String a = json.ToString(); Computer d = converter.Deserialize <Computer>(a); AllComputers1.Add(d); } Computer computer1 = null; if (AllComputers1 != null) { computer1 = AllComputers1[0]; } macAddress2 = computer1.LanMacAddress; if (connectionTypeValue == "Cable") { if (CableTypeValue == "Lan") { lanCable.End1 = macAddress1; lanCable.End2 = macAddress2; lanCable.Type = "Lan"; String addCableQuerry = "CREATE EDGE LanCable FROM " + o1.RID.ToString() + " TO " + o2.RID.ToString() + " SET End1 = \"" + lanCable.End1 + "\", End2 = \"" + lanCable.End2 + "\", Type=\"" + lanCable.Type + "\", Manufacturer=\"" + lanCable.Manufacturer + "\", Category=\"" + lanCable.Category + "\""; database.Command(addCableQuerry); return; } } } else if ((firstNodeType == "Router" || firstNodeType == "Switch") && (secondNodeType == "Router" || secondNodeType == "Switch")) { String query = "SELECT * FROM Node WHERE @rid=" + o1.RID.ToString(); JavaScriptSerializer converter = new JavaScriptSerializer(); List <ODocument> resultset = database.Query(query).ToList(); List <Node> AllNodes = new List <Node>(); foreach (ODocument doc in resultset) { var json = converter.Serialize(doc); String a = json.ToString(); Node d = converter.Deserialize <Node>(a); AllNodes.Add(d); } Node node = null; if (AllNodes != null) { node = AllNodes[0]; } String macAddress1 = null; if (node != null) { if (node.NumberOfPorts != node.NumberOfTakenPorts) { node.NumberOfTakenPorts++; macAddress1 = node.MacAddressList.ElementAt(node.NumberOfTakenPorts - 1); } } String query1 = "SELECT * FROM Node WHERE @rid=" + o2.RID.ToString(); List <ODocument> resultset1 = database.Query(query1).ToList(); List <Node> AllNodes1 = new List <Node>(); foreach (ODocument doc in resultset1) { var json = converter.Serialize(doc); String a = json.ToString(); Node d = converter.Deserialize <Node>(a); AllNodes1.Add(d); } Node node1 = null; if (AllNodes1 != null) { node1 = AllNodes1[0]; } String macAddress2 = null; if (node1 != null) { if (node1.NumberOfPorts != node1.NumberOfTakenPorts) { node1.NumberOfTakenPorts++; macAddress2 = node1.MacAddressList.ElementAt(node1.NumberOfTakenPorts - 1); } } if (connectionTypeValue == "Cable") { if (CableTypeValue == "Lan") { lanCable.End1 = macAddress1; lanCable.End2 = macAddress2; lanCable.Type = "Lan"; String addCableQuerry = "CREATE EDGE LanCable FROM " + o1.RID.ToString() + " TO " + o2.RID.ToString() + " SET End1 = \"" + lanCable.End1 + "\", End2 = \"" + lanCable.End2 + "\", Type=\"" + lanCable.Type + "\", Manufacturer=\"" + lanCable.Manufacturer + "\", Category=\"" + lanCable.Category + "\""; database.Command(addCableQuerry); if (node != null) { database.Update(o1) .Set("NumberOfPorts", node.NumberOfPorts) .Set("NumberOfTakenPorts", node.NumberOfTakenPorts) .Set("MacAddressList", node.MacAddressList).Run(); } if (node1 != null) { database.Update(o2) .Set("NumberOfPorts", node1.NumberOfPorts) .Set("NumberOfTakenPorts", node1.NumberOfTakenPorts) .Set("MacAddressList", node1.MacAddressList).Run(); } return; } } } }
public void FlushDb() { _db.Command("TRUNCATE CLASS " + typeof(TweeterModel).Name); _db.Command("TRUNCATE CLASS " + typeof(YoutubeModel).Name); _db.Command("TRUNCATE CLASS " + typeof(RedditModel).Name); }
public void ShouldUpdateCluster() { using (TestDatabaseContext testContext = new TestDatabaseContext()) { using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { // prerequisites database .Create.Class("TestClass") .Run(); database .Create.Cluster("TestCluster", OClusterType.Physical) .Run(); database.Command("alter class TestClass addcluster TestCluster"); ODocument document = new ODocument(); document.OClassName = "TestClass"; document .SetField("foo", "foo string value") .SetField("bar", 12345); database .Insert(document) .Cluster("TestCluster") .Run(); database .Insert(document) .Cluster("TestCluster") .Run(); document .SetField("bar", 54321) .SetField("baz", "new baz value"); int documentsUpdated = database .Update(document) .Cluster("TestCluster") .Run(); Assert.AreEqual(documentsUpdated, 2); List<ODocument> documents = database .Select() .From("cluster:TestCluster") .ToList(); Assert.AreEqual(documents.Count, 2); for (int i = 0; i < documents.Count; i++) { Assert.IsTrue(documents[i].ORID != null); Assert.AreEqual(documents[i].OClassName, document.OClassName); Assert.AreEqual(documents[i].GetField<string>("foo"), document.GetField<string>("foo")); Assert.AreEqual(documents[i].GetField<int>("bar"), document.GetField<int>("bar")); Assert.AreEqual(documents[i].GetField<string>("baz"), document.GetField<string>("baz")); } } } }
public void ShouldUpdateCluster() { using (TestDatabaseContext testContext = new TestDatabaseContext()) { using (ODatabase database = new ODatabase(TestConnection.GlobalTestDatabaseAlias)) { // prerequisites database .Create.Class("TestClass") .Run(); database .Create.Cluster("TestCluster", OClusterType.Physical) .Run(); database.Command("alter class TestClass addcluster TestCluster"); ODocument document = new ODocument(); document.OClassName = "TestClass"; document .SetField("foo", "foo string value") .SetField("bar", 12345); database .Insert(document) .Cluster("TestCluster") .Run(); database .Insert(document) .Cluster("TestCluster") .Run(); document .SetField("bar", 54321) .SetField("baz", "new baz value"); int documentsUpdated = database .Update(document) .Cluster("TestCluster") .Run(); Assert.AreEqual(documentsUpdated, 2); List <ODocument> documents = database .Select() .From("cluster:TestCluster") .ToList(); Assert.AreEqual(documents.Count, 2); for (int i = 0; i < documents.Count; i++) { Assert.IsTrue(documents[i].ORID != null); Assert.AreEqual(documents[i].OClassName, document.OClassName); Assert.AreEqual(documents[i].GetField <string>("foo"), document.GetField <string>("foo")); Assert.AreEqual(documents[i].GetField <int>("bar"), document.GetField <int>("bar")); Assert.AreEqual(documents[i].GetField <string>("baz"), document.GetField <string>("baz")); } } } }