public void GraphClientFactoryUseCase() { const string queryText = @"MATCH (d) RETURN d"; var cypherQuery = new CypherQuery(queryText, null, CypherResultMode.Set, CypherResultFormat.Rest); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.Get("/"), MockResponse.NeoRoot() }, { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), new MockResponse { StatusCode = HttpStatusCode.OK } } }) { var httpClient = testHarness.GenerateHttpClient(testHarness.BaseUri); var executeConfiguration = new ExecutionConfiguration { HttpClient = httpClient, UserAgent = string.Format("Neo4jClient/{0}", typeof(NeoServerConfiguration).Assembly.GetName().Version), UseJsonStreaming = true, JsonConverters = GraphClient.DefaultJsonConverters }; var configuration = NeoServerConfiguration.GetConfiguration(new Uri(testHarness.BaseUri), null, null, executeConfiguration); var factory = new GraphClientFactory(configuration); using (var client = factory.Create(httpClient)) { client.Cypher.Match("(d)").Return<object>("d").ExecuteWithoutResults(); } } }
public void WhenAsyncCommandFails_ShouldNotRaiseCompleted() { // Arrange const string queryText = @"return 1"; var parameters = new Dictionary<string, object>(); var cypherQuery = new CypherQuery(queryText, parameters, CypherResultMode.Set); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Throws() } }) { var graphClient = testHarness.CreateAndConnectGraphClient(); bool raisedEvent = false; graphClient.OperationCompleted += (sender, e) => { raisedEvent = true; }; //Act var task = graphClient.ExecuteCypherAsync(cypherQuery) .ContinueWith(t => { Assert.IsTrue(t.IsFaulted); Assert.IsInstanceOf<MockResponseThrowsException>(t.Exception.Flatten().InnerException); }); task.Wait(); Assert.IsFalse(raisedEvent, "Raised OperationCompleted"); } }
public void DebugQueryShouldBeSuccessfulWithNullAsParameters() { var query = new CypherQuery("MATCH (n) RETURN (n)", null, CypherResultMode.Set); const string expected = "MATCH (n) RETURN (n)"; Assert.AreEqual(expected, query.DebugQueryText); }
public void ShouldSendCommandAndNotCareAboutResults() { // Arrange const string queryText = @"START d=node({p0}), e=node({p1}) CREATE UNIQUE d-[:foo]->e"; var parameters = new Dictionary<string, object> { {"p0", 215}, {"p1", 219} }; var cypherQuery = new CypherQuery(queryText, parameters, CypherResultMode.Set); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Http((int)HttpStatusCode.OK) } }) { var graphClient = testHarness.CreateAndConnectGraphClient(); //Act graphClient.ExecuteCypher(cypherQuery); } }
public void ShouldSendCommandAndNotCareAboutResultsAsync() { // Arrange const string queryText = @"return 1"; var parameters = new Dictionary<string, object>(); var cypherQuery = new CypherQuery(queryText, parameters, CypherResultMode.Set); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Http((int)HttpStatusCode.OK) } }) { var graphClient = testHarness.CreateAndConnectGraphClient(); bool raisedEvent = false; graphClient.OperationCompleted += (sender, e) => { raisedEvent = true; }; //Act var task = graphClient.ExecuteCypherAsync(cypherQuery); task.Wait(); Assert.IsTrue(raisedEvent, "Raised OperationCompleted"); } }
[Test] public void ShouldDeserializePathsResultAsSetBased() { // Arrange const string queryText = @"START d=node({p0}), e=node({p1}) MATCH p = allShortestPaths( d-[*..15]-e ) RETURN p"; var parameters = new Dictionary<string, object> { {"p0", 215}, {"p1", 219} }; var cypherQuery = new CypherQuery(queryText, parameters, CypherResultMode.Set, CypherResultFormat.Rest); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Json(HttpStatusCode.OK, @"{ 'data' : [ [ { 'start' : 'http://foo/db/data/node/215', 'nodes' : [ 'http://foo/db/data/node/215', 'http://foo/db/data/node/0', 'http://foo/db/data/node/219' ], 'length' : 2, 'relationships' : [ 'http://foo/db/data/relationship/247', 'http://foo/db/data/relationship/257' ], 'end' : 'http://foo/db/data/node/219' } ], [ { 'start' : 'http://foo/db/data/node/215', 'nodes' : [ 'http://foo/db/data/node/215', 'http://foo/db/data/node/1', 'http://foo/db/data/node/219' ], 'length' : 2, 'relationships' : [ 'http://foo/db/data/relationship/248', 'http://foo/db/data/relationship/258' ], 'end' : 'http://foo/db/data/node/219' } ] ], 'columns' : [ 'p' ] }") } }) { var graphClient = testHarness.CreateAndConnectGraphClient(); //Act var results = graphClient .ExecuteGetCypherResults<PathsResult>(cypherQuery) .ToArray(); //Assert Assert.IsInstanceOf<IEnumerable<PathsResult>>(results); Assert.AreEqual(results.First().Length, 2); Assert.AreEqual(results.First().Start, "http://foo/db/data/node/215"); Assert.AreEqual(results.First().End, "http://foo/db/data/node/219"); Assert.AreEqual(results.Skip(1).First().Length, 2); Assert.AreEqual(results.Skip(1).First().Start, "http://foo/db/data/node/215"); Assert.AreEqual(results.Skip(1).First().End, "http://foo/db/data/node/219"); } }
public List<SoldBook> FindBooksWhoPeopleAlsoBoughtWhenTheyBought(BookKey book) { var query = new CypherQuery(@"start n=node(*) where has(n.Id) and n.Id = {p0} return n", new Dictionary<string, object> {{"p0", book.Value}}, CypherResultMode.Set); var books = ((IRawGraphClient) _client).ExecuteGetCypherResults<Node<Book>>(query).ToList(); IEnumerable<Node<Book>> soldBooks = _client.Cypher.Start(new {n = books}).Match("(n)--(x)").Return<Node<Book>>("x").Results; return soldBooks.Select(bookReference => new SoldBook{ Id = new BookKey{ Value = bookReference.Data.Id }}).ToList(); }
public IList<DTO.Worker> GetAll() { Connect(); var query = new CypherQuery("start R=node({0}) match R-[:RELATED_TO]->N-[:HAS_ITEM]->W where N.Name=\"Workers\" return W;", new Dictionary<string, object>() { { "0", RootNode.Reference.Id } }, CypherResultMode.Set); var workers = Client.ExecuteGetCypherResults<Node<PO.Worker>>( query) .Select(n => DTO.Worker.Create(n.Data)); return workers.ToList(); }
protected static Node<PO.Workers> GetWorkersRootNode(GraphClient client, Node<PO.Root> rootNode) { //var rootNode = GetRootNode(client); //var query = new CypherQuery("start R=node({p0}) match R-[:RELATED_TO]->N where N.__Type=\"Workers\" return N;", new Dictionary<string, object>() { { "p0", rootNode.Reference.Id } }, CypherResultMode.Set); var query = new CypherQuery("start R=node({p0}) match R-[:RELATED_TO]->WR where WR.Name='Workers' return WR;", new Dictionary<string, object>() { { "p0", rootNode.Reference.Id } }, CypherResultMode.Set); var node = client.ExecuteGetCypherResults<Node<PO.Workers>>( query ); return node.SingleOrDefault(); }
// --- Funkcija koja se izvrsava kao novi thread --- private void proveriProjekte() { CypherQuery vratiAktivneProjekte = new CypherQuery("match (n:Projekat)-[r:STATUS]->(m:Status_projekta) where m.Ime='Aktivan' return n", new Dictionary<string, object>(), CypherResultMode.Set); var listaAktivnaProjekata = ((IRawGraphClient)client).ExecuteGetCypherResults<Projekat>(vratiAktivneProjekte).ToList(); foreach (Projekat p in listaAktivnaProjekata) { DateTime danasnjiDatum = DateTime.Now.Date; DateTime krajnjiRok = Convert.ToDateTime(p.Rok_zavrsetka); // --- Ako je istekao rok, stavi projekat u zavrsene --- if (danasnjiDatum > krajnjiRok) { string radniciNaProjektu = ""; // --- Vrati mi radnike na projektu --- CypherQuery vratiRadnikeNaProjektu = new CypherQuery("match (n:Radnik)-[r:ANGAZOVAN_NA]->(m:Projekat) where m.Ime='" + p.Ime + "' return n", new Dictionary<string, object>(), CypherResultMode.Set); var listaRadnika = ((IRawGraphClient)client).ExecuteGetCypherResults<Radnik>(vratiRadnikeNaProjektu).ToList(); // --- Uzimamo ID, IME i PREZIME --- foreach (Radnik r in listaRadnika) { radniciNaProjektu += r.id + " " + r.Ime + " " + r.Prezime + ", "; } radniciNaProjektu = radniciNaProjektu.TrimEnd(", ".ToCharArray()); // --- Updateovanje atributa na projektu, tj. dodavanje radnika koji su radili na projektu --- client.Cypher .Match("(projekat:Projekat)") .Where((Projekat projekat) => projekat.Ime == p.Ime) .Set("projekat.Radnici_angazovani_na_projektu = {ranp}") .WithParam("ranp", radniciNaProjektu) .ExecuteWithoutResults(); // --- Brisanje svih veza na projektu --- client.Cypher.Match("(projekat:Projekat)-[r]-() ") .Where((Projekat projekat) => projekat.Ime == p.Ime) .Delete("r") .ExecuteWithoutResults(); // --- Stavljanje projekta u zavrsene (pravi se veza Projekat-Zavrsen), tj. Updatovanje Statusa --- client.Cypher.Match("(projekat:Projekat)", "(zavrsen:Status_projekta)") .Where((Projekat projekat) => projekat.Ime == p.Ime) .AndWhere((Status_projekta zavrsen) => zavrsen.Ime == "Zavrsen") .CreateUnique("projekat-[:STATUS]->zavrsen") .ExecuteWithoutResults(); } } }
private void btnAdd_Click(object sender, EventArgs e) { if (lblAdd.Text == "REGION") { Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("infoType", txtType.Text); var query = new Neo4jClient.Cypher.CypherQuery("MERGE (n:" + lblAdd.Text + " {infoType:'" + txtType.Text + "'}) return n", queryDict, CypherResultMode.Set); ((IRawGraphClient)client).ExecuteCypher(query); Dictionary <string, object> queryDict3 = new Dictionary <string, object>(); var query2 = new Neo4jClient.Cypher.CypherQuery("MATCH(a: Family),(b: " + lblAdd.Text + ")" + "WHERE a.familyName = '" + globalFamily.familyName + "' AND a.usernameOfFamilly='" + globalFamily.usernameOfFamilly + "' AND b.infoType = '" + txtType.Text + "'" + "MERGE(a) -[r: " + txtName.Text + "] - > (b)" + "RETURN type(r)", queryDict3, CypherResultMode.Set); ((IRawGraphClient)client).ExecuteCypher(query2); MessageBox.Show("Dodat je " + lblAdd.Text + " po imenu " + txtType.Text + "."); } else { Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("infoType", txtType.Text); var query = new Neo4jClient.Cypher.CypherQuery("MERGE (n:" + lblAdd.Text + " {infoType:'" + txtType.Text + "'}) return n", queryDict, CypherResultMode.Set); ((IRawGraphClient)client).ExecuteCypher(query); Dictionary <string, object> queryDict3 = new Dictionary <string, object>(); var query2 = new Neo4jClient.Cypher.CypherQuery("MATCH(a: familyMember),(b: " + lblAdd.Text + ")" + "WHERE a.name = '" + globalMember.name + "' AND a.surname='" + globalMember.surname + "' AND b.infoType = '" + txtType.Text + "'" + "CREATE(a) -[r: " + txtName.Text + "] - > (b)" + "RETURN type(r)", queryDict3, CypherResultMode.Set); ((IRawGraphClient)client).ExecuteCypher(query2); MessageBox.Show("Dodat je " + lblAdd.Text + " po imenu " + txtType.Text + "."); /*Dictionary<string, object> queryDict1 = new Dictionary<string, object>(); * var query1 = new Neo4jClient.Cypher.CypherQuery("MATCH (ee:"+lblAdd.Text+") WHERE ee.infoType = '" + txtType.Text + "' RETURN ee;", * queryDict1, CypherResultMode.Set); * Information fName = ((IRawGraphClient)client).ExecuteGetCypherResults<Information>(query1).FirstOrDefault(); * MessageBox.Show("Dodat je " + fName.infoName);*///za izvlacenje iz baze } this.Close(); }
public string deleteActor(string name) { var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "edukacija"); client.Connect(); Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("actorName", name); var query = new Neo4jClient.Cypher.CypherQuery("start n=node(*) where (n:Person) and exists(n.name) and n.name =~ {actorName} delete n", queryDict, CypherResultMode.Projection); ((IRawGraphClient)client).ExecuteCypher(query); return("Actor deleted."); }
public async Task <IActionResult> OnPostKomentarisi(int id) { int idLog; bool log = int.TryParse(HttpContext.Session.GetString("idKorisnik"), out idLog); if (log) { client = DataLayer.Neo4jManager.GetClient(); var query = new Neo4jClient.Cypher.CypherQuery("MATCH(a: Korisnik), (b: Objava) WHERE a.ID = " + idLog + " AND b.ID = " + id + " CREATE(a) -[r:KOMENTAR{DatumPostavljanja:" + DateTime.Now.ToString("MM/dd/yyyy") + ", Tekst:'" + Komentarcic + "'}]->(b)", new Dictionary <string, object>(), CypherResultMode.Set); ((IRawGraphClient)client).ExecuteCypher(query); return(RedirectToPage()); } else { return(RedirectToPage("../Index")); } }
public void createActedIn(string actorName, string movieTitle, string role) { var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "edukacija"); client.Connect(); Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("actorName", actorName); queryDict.Add("movieTitle", movieTitle); queryDict.Add("role", role); var query = new Neo4jClient.Cypher.CypherQuery("match (m) where exists(m.title) and m.title='" + movieTitle + "' match (p:Person) where exists(p.name) and p.name='" + actorName + "' create (p)-[:ACTED_IN {roles:'" + role + "'}]->(m) return p", queryDict, CypherResultMode.Projection); ((IRawGraphClient)client).ExecuteCypher(query); }
/*public void update(string title, int rate) * { * var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "edukacija"); * client.Connect(); * * Dictionary<string, object> queryDict = new Dictionary<string, object>(); * //queryDict.Add("title", title); * queryDict.Add("rate", rate); * * var query = new Neo4jClient.Cypher.CypherQuery("MERGE (n:Movie {title:'" + title + "'}) ON MATCH SET n.rate={rate}", * queryDict, CypherResultMode.Set); * * ((IRawGraphClient)client).ExecuteCypher(query); * * }*/ public string deleteMovie(string title) { var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "edukacija"); client.Connect(); Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("movieTitle", title); var query = new Neo4jClient.Cypher.CypherQuery("start n=node(*) where (n:Movie) and exists(n.title) and n.title =~ {movieTitle} delete n", queryDict, CypherResultMode.Projection); ((IRawGraphClient)client).ExecuteCypher(query); return("Movie deleted."); }
public async Task <IActionResult> OnGet() { int idLog; bool log = int.TryParse(HttpContext.Session.GetString("idKorisnik"), out idLog); if (log) { idKorisnika = idLog; try { client = DataLayer.Neo4jManager.GetClient(); var query = new Neo4jClient.Cypher.CypherQuery("MATCH (n:Korisnik) WHERE n.ID = " + idLog + " return n", new Dictionary <string, object>(), CypherResultMode.Set); List <Korisnik> k = ((IRawGraphClient)client).ExecuteGetCypherResults <Korisnik>(query).ToList(); zaPrikaz = k[0]; var query2 = new Neo4jClient.Cypher.CypherQuery("MATCH (a:Korisnik)-[r:KORISNIKOBJAVA]->(b:Objava) WHERE a.ID = " + idLog + " and (r.MojaObjava = true or r.PodeljenaObjava = true) return b", new Dictionary <string, object>(), CypherResultMode.Set); objaveZaPrikaz = ((IRawGraphClient)client).ExecuteGetCypherResults <Objava>(query2).ToList(); KomentariZaObjave = new Dictionary <int, List <Komentar> >(); foreach (var item in objaveZaPrikaz) { var queryZaObjave = new Neo4jClient.Cypher.CypherQuery("match (n)-[r:KOMENTAR]->(m) where m.ID = " + item.ID + " return r{Korisnik:n,Objava:m,Tekst:r.Tekst,DatumPostavljanja:r.DatumPostavljanja}", new Dictionary <string, object>(), CypherResultMode.Set); List <Komentar> pomKom = ((IRawGraphClient)client).ExecuteGetCypherResults <Komentar>(queryZaObjave).ToList(); KomentariZaObjave.Add(item.ID, pomKom); } } catch (Exception exc) { Console.WriteLine("greska"); } return(Page()); } else { return(RedirectToPage("../Index")); } }
public Actor GetActor(String actorName) { var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "edukacija"); client.Connect(); Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("actorName", actorName); var query = new Neo4jClient.Cypher.CypherQuery("start n=node(*) where (n:Person) and exists(n.name) and n.name =~ {actorName} return n", queryDict, CypherResultMode.Set); List <Actor> actors = ((IRawGraphClient)client).ExecuteGetCypherResults <Actor>(query).ToList(); return(actors.ToList().First()); }
private void button1_Click(object sender, EventArgs e) { //string presidentName = 'Vucic'; // Dictionary<string, object> queryDict = new Dictionary<string, object>(); // queryDict.Add("presidentName", presidentName); var query = new Neo4jClient.Cypher.CypherQuery("start n=node(*) match (n)-[r:VOTE_FOR]->(a) where a.name =~ 'Vucic' return n", new Dictionary <string, object>(), CypherResultMode.Set); List <Voters> voters = ((IRawGraphClient)client).ExecuteGetCypherResults <Voters>(query).ToList(); foreach (Voters v in voters) { MessageBox.Show(v.name); } }
public Restaurant Get(string name, string city) { Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("Name", name); queryDict.Add("City", city); var query = new Neo4jClient.Cypher.CypherQuery("start n=node(*) where (n:Restaurant) and exists(n.Name) " + "and n.Name =~'" + name + "' and n.City =~'" + city + "' return n", queryDict, CypherResultMode.Set); List <Restaurant> Restaurants = ((IRawGraphClient)client).ExecuteGetCypherResults <Restaurant>(query).ToList(); Restaurant Restaurant = Restaurants.Find(x => x.Name == name); return(Restaurant); }
public List <Cast> GetActorsFromMovieOrSeries(string movieOrSeriesTitle) { var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "edukacija"); client.Connect(); Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("movieOrSeriesName", movieOrSeriesTitle); var query = new Neo4jClient.Cypher.CypherQuery("start n=node(*) match (n)<-[r:ACTED_IN]-(a) where exists(n.title) and n.title =~ {movieOrSeriesName} return {name: a.name, role: r.roles} as actorRole", queryDict, CypherResultMode.Set); List <Cast> cast = ((IRawGraphClient)client).ExecuteGetCypherResults <Cast>(query).ToList(); return(cast.ToList()); }
public void ucitajSobe() { var query = new Neo4jClient.Cypher.CypherQuery("match(n:Prostorija:Soba)return n", new Dictionary <string, object>(), CypherResultMode.Set); List <Soba> sobe = ((IRawGraphClient)client).ExecuteGetCypherResults <Soba>(query).ToList(); listView1.Items.Clear(); foreach (Soba s in sobe) { ListViewItem item = new ListViewItem(new string[] { s.brojProstorije, s.sprat, s.brojKreveta, s.cena.ToString(), s.klima, s.tv, s.terasa }); listView1.Items.Add(item); // MessageBox.Show(s.sprat); } listView1.Refresh(); }
public static void DodajPutnika(Putnik p) { Dictionary <string, object> dictP = new Dictionary <string, object>(); dictP.Add("ime", p.ime); dictP.Add("prezime", p.prezime); dictP.Add("pasos", p.pasos); var query = new Neo4jClient.Cypher.CypherQuery("CREATE (n:Putnik {id:'" + p.id + "', ime:'" + p.ime + "', prezime:'" + p.prezime + "', pasos:'" + p.pasos + "'}) return n", dictP, CypherResultMode.Set); Putnik tm = ((IRawGraphClient)client).ExecuteGetCypherResults <Putnik>(query).Single(); }
public void ucitajSale() { // listView1.AllowColumnReorder = true; var query = new Neo4jClient.Cypher.CypherQuery("match(n:Prostorija:Sala)return n", new Dictionary <string, object>(), CypherResultMode.Set); List <Sala> sale = ((IRawGraphClient)client).ExecuteGetCypherResults <Sala>(query).ToList(); listView1.Items.Clear(); foreach (Sala s in sale) { ListViewItem item = new ListViewItem(new string[] { s.brojProstorije, s.kapacitetSale.ToString(), s.cena.ToString() }); listView1.Items.Add(item); // MessageBox.Show(s.sprat); } listView1.Refresh(); }
public void ucitajBazene() { var query = new Neo4jClient.Cypher.CypherQuery("match(n:Prostorija:Bazen)return n", new Dictionary <string, object>(), CypherResultMode.Set); List <Bazen> bazeni = ((IRawGraphClient)client).ExecuteGetCypherResults <Bazen>(query).ToList(); listView1.Items.Clear(); foreach (Bazen s in bazeni) { ListViewItem item = new ListViewItem(new string[] { s.brojProstorije, s.tip, s.cena.ToString() }); listView1.Items.Add(item); // MessageBox.Show(s.sprat); } listView1.Refresh(); }
private void reportReview_Click(object sender, EventArgs e) { ComboboxValue tmpComboboxValue = (ComboboxValue)choseDoctor.SelectedItem; var queryDelete = new Neo4jClient.Cypher.CypherQuery("MATCH(n { id: '" + tmpComboboxValue.doc.id + "' })-[r:Ima]->(p {id: '" + this.patients.id + "' }) DELETE r return p", new Dictionary <string, object>(), CypherResultMode.Set); ((IRawGraphClient)client).ExecuteGetCypherResults <Patients>(queryDelete).ToList(); client.Cypher .Match("(d:Doctors)", "(p:Patients)") .Where((Doctors d) => d.id == tmpComboboxValue.doc.id) .AndWhere((Patients p) => p.id == this.patients.id) .Create("(d)-[r:Ima]->(p)") .ExecuteWithoutResults(); MessageBox.Show("Pregled Prijavljen"); }
private void btnRegister_Click(object sender, EventArgs e) { try { var query = new CypherQuery($"MATCH (w:Worker) WHERE w.UserName = '******'" + $" RETURN w", new Dictionary <string, object>(), CypherResultMode.Set); var user = ((IRawGraphClient)client).ExecuteGetCypherResults <Worker>(query).SingleOrDefault(); if (user == null && checkRequirements()) { Worker worker = new Worker { UserName = tbUserName.Text, FirstName = tbFirstName.Text, LastName = tbLastName.Text, Password = tbPassword.Text }; Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("UserName", worker.UserName); queryDict.Add("FirstName", worker.FirstName); queryDict.Add("LastName", worker.LastName); queryDict.Add("Password", worker.Password); query = new Neo4jClient.Cypher.CypherQuery("Create (n:Worker {UserName: '******', FirstName: '" + worker.FirstName + "', LastName: '" + worker.LastName + "', Password: '******'})", queryDict, CypherResultMode.Set); ((IRawGraphClient)client).ExecuteCypher(query); lbStatus.Text = "Registracija uspesna."; lbStatus.Visible = true; } else if (user != null) { lbStatus.Text = "Korisnicko ime je zauzeto."; lbStatus.Visible = true; } } catch (Exception ex) { lbStatus.Text = ex.Message; lbStatus.Visible = true; } }
public async Task <ActionResult> OnPostBlokirajAsync(int id) { int idLog; bool log = int.TryParse(HttpContext.Session.GetString("idKorisnik"), out idLog); if (log) { client = DataLayer.Neo4jManager.GetClient(); var query = new Neo4jClient.Cypher.CypherQuery("match (n)-[r:KORISNIKKORISNIK]->(m) where n.ID = " + idKorisnika + " and m.ID = " + id + " and r.Prijatelj=true set r.Blokiran=true return r", new Dictionary <string, object>(), CypherResultMode.Set); ((IRawGraphClient)client).ExecuteCypher(query); return(RedirectToPage()); } else { return(RedirectToPage("../Index")); } }
public Restaurant Create(Restaurant typeInstance) { Dictionary <string, object> queryDictionary = new Dictionary <string, object>(); queryDictionary.Add("Name", typeInstance.Name); queryDictionary.Add("City", typeInstance.City); var query = new Neo4jClient.Cypher.CypherQuery("CREATE (n:Restaurant {Name:'" + typeInstance.Name + "', " + "City:'" + typeInstance.City + "'}) return n", queryDictionary, CypherResultMode.Set); List <Restaurant> Restaurants = ((IRawGraphClient)client).ExecuteGetCypherResults <Restaurant>(query).ToList(); Restaurant Restaurant = Restaurants.Find(x => x.Name == typeInstance.Name); return(Restaurant); }
public async Task <IActionResult> OnPostPostaniAdmin(int?id) { int idLog; bool log = int.TryParse(HttpContext.Session.GetString("idKorisnik"), out idLog); if (log) { try { client = DataLayer.Neo4jManager.GetClient(); var q = new Neo4jClient.Cypher.CypherQuery("MATCH (a:Korisnik)-[r: KORISNIKSTRANICA]->(b:Stranica) WHERE a.ID = " + HttpContext.Session.GetString("idKorisnik") + " AND b.ID = " + id + " RETURN a", new Dictionary <string, object>(), CypherResultMode.Set); List <Korisnik> pom = ((IRawGraphClient)client).ExecuteGetCypherResults <Korisnik>(q).ToList(); if (pom != null && pom.Count == 0) { var query = new Neo4jClient.Cypher.CypherQuery("MATCH (a:Korisnik), (b:Stranica) WHERE a.ID = " + HttpContext.Session.GetString("idKorisnik") + " AND b.ID = " + id + " CREATE (a)-[r: KORISNIKSTRANICA {Admin:true,Lajkovao:true,Pratilac:true}]->(b) RETURN r", new Dictionary <string, object>(), CypherResultMode.Set); ((IRawGraphClient)client).ExecuteGetCypherResults <KorisnikStranica>(query); ErrorMessage = ""; } else { var query2 = new Neo4jClient.Cypher.CypherQuery("MATCH (a:Korisnik)-[r: KORISNIKSTRANICA]->(b:Stranica) WHERE a.ID = " + HttpContext.Session.GetString("idKorisnik") + " AND b.ID = " + id + " set r.Admin=true set r.Lajkovao=true set r.Pratilac=true RETURN a", new Dictionary <string, object>(), CypherResultMode.Set); ((IRawGraphClient)client).ExecuteGetCypherResults <Korisnik>(query2); ErrorMessage = ""; } } catch (Exception exc) { Console.WriteLine("greska"); } return(RedirectToPage()); } else { return(RedirectToPage("../Index")); } }
private Zadatak CreateZadatak() { Zadatak z = new Zadatak(); z.naziv = textBox3.Text; if (checkBox1.Checked) { z.hitno = "da"; } else { z.hitno = "ne"; } z.datum = dateTimePicker1.Value.Date; switch (comboBox1.Text) { case ("Bazen"): z.prostorija = this.VratiBazen(); break; case ("Sala"): z.prostorija = this.VratiSalu(); break; case ("Soba"): z.prostorija = this.VratiSobu(); break; } Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("brojRadnika", brojRadnika); var query = new Neo4jClient.Cypher.CypherQuery("start n=node(*) where (n:Radnik) and exists(n.brojRadnika) and n.brojRadnika =~ {brojRadnika} return n", queryDict, CypherResultMode.Set); List <Radnik> radnik = ((IRawGraphClient)client).ExecuteGetCypherResults <Radnik>(query).ToList(); z.radnik = radnik[0]; return(z); }
public async Task <IActionResult> OnGet() { int idLog; bool log = int.TryParse(HttpContext.Session.GetString("idKorisnik"), out idLog); if (log) { try { client = DataLayer.Neo4jManager.GetClient(); var query2 = new Neo4jClient.Cypher.CypherQuery("MATCH (a:Korisnik) WHERE a.ID = " + HttpContext.Session.GetString("idKorisnik") + " RETURN a", new Dictionary <string, object>(), CypherResultMode.Set); List <Korisnik> pom = ((IRawGraphClient)client).ExecuteGetCypherResults <Korisnik>(query2).ToList(); Korisnik = pom[0]; int idchat; int.TryParse(HttpContext.Session.GetString("Chatid"), out idchat); var query3 = new Neo4jClient.Cypher.CypherQuery("MATCH (a:Korisnik) WHERE a.ID = " + HttpContext.Session.GetString("Chatid") + " RETURN a", new Dictionary <string, object>(), CypherResultMode.Set); List <Korisnik> pom2 = ((IRawGraphClient)client).ExecuteGetCypherResults <Korisnik>(query3).ToList(); Prijatelj = pom2[0]; poruke = DataLayer.DataProvider.GetPoruka(idLog.ToString(), idchat.ToString()); var poruke2 = DataLayer.DataProvider.GetPoruka(idchat.ToString(), idLog.ToString()); poruke.AddRange(poruke2); poruke = poruke.OrderBy(o => o.senttime).ToList(); } catch (Exception exc) { Console.WriteLine("greska"); } return(Page()); } else { return(RedirectToPage("../Index")); } }
private void PopuniPodacima() { pregledGostijuListView.Items.Clear(); Dictionary <string, object> queryDict = new Dictionary <string, object>(); var query = new Neo4jClient.Cypher.CypherQuery("match(n:Gost)-[r:PRIJAVA{aktivna:'true'}]->(s:Prostorija) return n", queryDict, CypherResultMode.Set); List <Gost> gosti = ((IRawGraphClient)client).ExecuteGetCypherResults <Gost>(query).ToList(); var query1 = new Neo4jClient.Cypher.CypherQuery("match(n:Gost)-[r:PRIJAVA{aktivna:'true'}]->(s:Prostorija) return ID(n)", queryDict, CypherResultMode.Set); List <String> listaID = ((IRawGraphClient)client).ExecuteGetCypherResults <String>(query1).ToList(); var query2 = new Neo4jClient.Cypher.CypherQuery("match(n:Gost)-[r:PRIJAVA{aktivna:'true'}]->(s:Prostorija) return s", queryDict, CypherResultMode.Set); List <Prostorija> sobe = ((IRawGraphClient)client).ExecuteGetCypherResults <Prostorija>(query2).ToList(); var query3 = new Neo4jClient.Cypher.CypherQuery("match(n:Gost)-[r:PRIJAVA{aktivna:'true'}]->(s:Prostorija) return r", queryDict, CypherResultMode.Set); List <Prijava> prijave = ((IRawGraphClient)client).ExecuteGetCypherResults <Prijava>(query3).ToList(); for (int i = 0; i < prijave.Count; i++) { gosti[i].idGosta = listaID[i].ToString(); prijave[i].gost = gosti[i]; prijave[i].prostorija = sobe[i]; } //List<Soba> sobeZaBrisanje = new List<Soba>(); //listaGostijuPregledGostiju = gosti; listaPrijava = prijave; foreach (Prijava r in prijave) { ListViewItem item = new ListViewItem(new string[] { r.gost.idGosta, r.gost.ime, r.gost.prezime, r.prostorija.brojProstorije.ToString(), r.gost.brojTelefona, r.gost.email, r.gost.dokument }); pregledGostijuListView.Items.Add(item); } pregledGostijuListView.Refresh(); }
public Series GetSeries(string sTitle) { var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "edukacija"); client.Connect(); Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("seriesTitle", sTitle); var query = new Neo4jClient.Cypher.CypherQuery("start n=node(*) match (n:Series) where exists(n.title) and n.title =~ {seriesTitle} return n", queryDict, CypherResultMode.Set); List <Series> series = ((IRawGraphClient)client).ExecuteGetCypherResults <Series>(query).ToList(); return(series.ToList().First()); }
public static IList <Projekat> vratiSveProjekte() { var query = new Neo4jClient.Cypher .CypherQuery("MATCH (p:Projekat) return p;", new Dictionary <string, object>(), CypherResultMode.Set); IList <Projekat> sviProjekti = ((IRawGraphClient)Session.Client) .ExecuteGetCypherResults <Projekat>(query) .ToList(); foreach (var projekat in sviProjekti) { projekat.FirmeNaProjektu = DataProvider.VratiFirmeKojeRadeNaProjektu(projekat.id); projekat.ZaposleniNaProjektu = DataProvider.VratiSveZaposleneNaProjektu(projekat.id); } return(sviProjekti); }
public bool IzmeniKvar(Kvar k) { try {//create(k)<-[ur:U_RADIONICI]-(rad1) return k var query = new Neo4jClient.Cypher.CypherQuery("match(rad1:Radionica{naziv:'" + vratiRadionicuRadnik(PrijavljenKorisnik).naziv + "'})" + "match(k:Kvar{sifraKvara: '" + k.sifraKvara + "'}) set k.naziv = '" + k.naziv + "'" + ", k.vremePrijaveKvara = '" + k.vremePrijaveKvara + "', k.vremeIspravkeKvara = '" + k.vremeIspravkeKvara + "'" + "create(k)<-[ur:U_RADIONICI]-(rad1) return k", new Dictionary <string, object>(), CypherResultMode.Set); List <Kvar> kvarovi = ((IRawGraphClient)client).ExecuteGetCypherResults <Kvar>(query).ToList(); return(DodajKvarRadnikovojRadionici(kvarovi[0])); } catch (Exception e) { return(false); } }
public static void obrisiProjekat(int id) { Dictionary <string, object> queryDict = new Dictionary <string, object>(); //prvo obrisati sve veze sa projektom...trenutno ima samo PRIPADA... DataProvider.ObrisiPripadaZaDatiProjekat(id); DataProvider.ObrisiRadiNaZaDatiProjekat(id); //DODATI BRISANJE OSTALIH VEZA!!!! queryDict.Add("id", id); var query = new Neo4jClient.Cypher.CypherQuery("MATCH(p: Projekat) WHERE p.id= {id} DETACH DELETE p", queryDict, CypherResultMode.Set); ((IRawGraphClient)Session.Client).ExecuteCypher(query); }
public List <Food> SearchFood(string name, string description) { Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("Name", name); queryDict.Add("Description", description); //var query = new Neo4jClient.Cypher.CypherQuery("MATCH (food:Food) WHERE food.Name CONTAINS '" + name + // "' AND food.Description CONTAINS '" + description + "' return food", // queryDict, CypherResultMode.Set); var query = new Neo4jClient.Cypher.CypherQuery("MATCH (food:Food {Name:'" + name + "'" + ", Description:'" + description + "'}) return food", queryDict, CypherResultMode.Set); List <Food> food = ((IRawGraphClient)client).ExecuteGetCypherResults <Food>(query).ToList(); return(food); }
public IActionResult PromeniPles(string staroIme, string novoIme)//edit zemlju porekla plesa { Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("staroime", staroIme); queryDict.Add("novoime", novoIme); var query = new Neo4jClient.Cypher.CypherQuery("start n = node(*) where(n: ples) and exists(n.zemljaporekla) and n.zemljaporekla ='" + staroIme + "' set n.zemljaporekla ='" + novoIme + "' return n", queryDict, CypherResultMode.Set); // List <Ples> pl = ((IRawGraphClient)client).ExecuteGetCypherResults <Ples>(query).ToList(); return(RedirectToAction("idiNaobrisiPlesStranicu")); }
public List <Role> GetSeriesFromActor(string actorName) { var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "edukacija"); client.Connect(); Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("actorName", actorName); var query = new Neo4jClient.Cypher.CypherQuery("start n=node(*) match (n)-[r:ACTED_IN]->(m:Series) where exists(n.name) and n.name =~ {actorName} return {title: m.title, role: r.roles} as seriesRole", queryDict, CypherResultMode.Set); List <Role> roles = ((IRawGraphClient)client).ExecuteGetCypherResults <Role>(query).ToList(); return(roles.ToList()); }
public List <Series> GetSeriesFromWriter(string writerName) { var client = new GraphClient(new Uri("http://localhost:7474/db/data"), "neo4j", "edukacija"); client.Connect(); Dictionary <string, object> queryDict = new Dictionary <string, object>(); queryDict.Add("writerName", writerName); var query = new Neo4jClient.Cypher.CypherQuery("start n=node(*) match (n)-[r:WROTE]->(m:Series) where exists(n.name) and n.name =~ {writerName} return m", queryDict, CypherResultMode.Set); List <Series> series = ((IRawGraphClient)client).ExecuteGetCypherResults <Series>(query).ToList(); return(series.ToList()); }
public IHttpActionResult Index(int limit = 100) { if (WebApiConfig.GraphClient == null) { Trace.WriteLine("Neo4j database is not initialised."); return Ok(); } if (WebApiConfig.Cache.Count != 0) { string query = WebApiConfig.Cache.Remove(User.Identity.GetUserId()); CypherQuery cypherQquery = new CypherQuery(query, null, CypherResultMode.Set); ((IRawGraphClient)WebApiConfig.GraphClient).ExecuteCypher(cypherQquery); } Graph graph = GraphHelper.LoadGraph(); return Ok(new { nodes = graph.Nodes, links = graph.NodeLinks }); }
public RawCheckResponse Check(IRawCheckRequest request) { /* Do i know what I'm doing? lets find out! https://github.com/Readify/Neo4jClient/wiki/cypher#manual-queries-highly-discouraged */ var rawClient = (IRawGraphClient) GraphClient; var parameters = new Dictionary<string, object>(); var cypherQuery = new CypherQuery(request.Cypher, parameters, CypherResultMode.Set); var violationIds = rawClient .ExecuteGetCypherResults<long>(cypherQuery) .ToList(); var response = new RawCheckResponse(); response.Request = request; response.Violations.AddRange(violationIds.ConvertAll(l => new Violation(l))); return response; }
public ActionResult Users() { GraphClient client = new GraphClient(new Uri("http://localhost:7474/db/data")); client.Connect(); var query = new Neo4jClient.Cypher.CypherQuery( "start n=node(0) match n<-[r:HasCompleted]-e return e.UserName as Name;", new Dictionary<string, object>(),CypherResultMode.Projection); //var result = client.ExecuteGetCypherResults<User>(query); // get all movies with any name using index List<Node<User>> list = client.QueryIndex<User>("User", IndexFor.Node, "Name: *").ToList(); List<User> movies = new List<User>(); foreach (Node<User> movieNode in list) { movies.Add(movieNode.Data); } return View(movies);//movies); }
public void SendingNullParametersShouldNotRaiseExceptionWhenExecutingCypher() { const string queryText = @"MATCH (d) RETURN d"; var cypherQuery = new CypherQuery(queryText, null, CypherResultMode.Set, CypherResultFormat.Rest); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Http((int)HttpStatusCode.OK) } }) { var graphClient = testHarness.CreateAndConnectGraphClient(); // execute cypher with "null" parameters graphClient.ExecuteCypher(cypherQuery); } }
public Task<HttpResponseMessage> EnqueueTask(string commandDescription, IGraphClient client, IExecutionPolicy policy, CypherQuery query) { // grab the endpoint in the same thread var txBaseEndpoint = policy.BaseEndpoint; var serializedQuery = policy.SerializeRequest(query); var task = new Task<HttpResponseMessage>(() => Request.With(client.ExecutionConfiguration) .Post(Endpoint ?? txBaseEndpoint) .WithJsonContent(serializedQuery) // HttpStatusCode.Created may be returned when emitting the first query on a transaction .WithExpectedStatusCodes(HttpStatusCode.OK, HttpStatusCode.Created) .ExecuteAsync( commandDescription, responseTask => { // we need to check for errors returned by the transaction. The difference with a normal REST cypher // query is that the errors are embedded within the result object, instead of having a 400 bad request // status code. var response = responseTask.Result; policy.AfterExecution(TransactionHttpUtils.GetMetadataFromResponse(response), this); return response; }) .Result ); _taskQueue.Add(task, _cancellationTokenSource.Token); if (_consumer == null) { _consumer = () => { while (true) { try { Task queuedTask; if (!_taskQueue.TryTake(out queuedTask, 0, _cancellationTokenSource.Token)) { // no items to consume _consumer = null; break; } queuedTask.RunSynchronously(); } catch (InvalidOperationException) { // we are done, CompleteAdding has been called break; } catch (OperationCanceledException) { // we are done, we were canceled break; } } }; _consumer.BeginInvoke(null, null); } return task; }
public Task<HttpResponseMessage> EnqueueCypherRequest(string commandDescription, IGraphClient client, CypherQuery query) { var policy = new CypherTransactionExecutionPolicy(client); // we try to get the current dtc transaction. If we are in a System.Transactions transaction and it has // been "promoted" to be handled by DTC then transactionObject will be null, but it doesn't matter as // we don't care about updating the object. var txContext = GetContext(); // the main difference with a normal Request.With() call is that the request is associated with the // TX context. return txContext.EnqueueTask(commandDescription, client, policy, query); }
public CypherTransactionStatement(CypherQuery query, bool restFormat) { _queryText = query.QueryText; _queryParameters = query.QueryParameters ?? new Dictionary<string, object>(); _formatContents = restFormat ? new[] {"REST"} : new string[] {}; }
public void ShouldDeserializeTableStructureWithRelationships() { // Arrange const string queryText = @" START x = node({p0}) MATCH x-[r]->n RETURN x AS Fooness, type(r) AS RelationshipType, n.Name? AS Name, n.UniqueId? AS UniqueId LIMIT 3"; var cypherQuery = new CypherQuery( queryText, new Dictionary<string, object> { {"p0", 123} }, CypherResultMode.Projection, CypherResultFormat.Rest); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Json(HttpStatusCode.OK, @"{ 'data' : [ [ { 'start' : 'http://foo/db/data/node/0', 'data' : { 'Bar' : 'bar', 'Baz' : 'baz' }, 'property' : 'http://foo/db/data/relationship/0/properties/{key}', 'self' : 'http://foo/db/data/relationship/0', 'properties' : 'http://foo/db/data/relationship/0/properties', 'type' : 'HAS_REFERENCE_DATA', 'extensions' : { }, 'end' : 'http://foo/db/data/node/1' }, 'HOSTS', 'foo', 44321 ], [ { 'start' : 'http://foo/db/data/node/1', 'data' : { 'Bar' : 'bar', 'Baz' : 'baz' }, 'property' : 'http://foo/db/data/relationship/1/properties/{key}', 'self' : 'http://foo/db/data/relationship/1', 'properties' : 'http://foo/db/data/relationship/1/properties', 'type' : 'HAS_REFERENCE_DATA', 'extensions' : { }, 'end' : 'http://foo/db/data/node/1' }, 'LIKES', 'bar', 44311 ], [ { 'start' : 'http://foo/db/data/node/2', 'data' : { 'Bar' : 'bar', 'Baz' : 'baz' }, 'property' : 'http://foo/db/data/relationship/2/properties/{key}', 'self' : 'http://foo/db/data/relationship/2', 'properties' : 'http://foo/db/data/relationship/2/properties', 'type' : 'HAS_REFERENCE_DATA', 'extensions' : { }, 'end' : 'http://foo/db/data/node/1' }, 'HOSTS', 'baz', 42586 ] ], 'columns' : [ 'Fooness', 'RelationshipType', 'Name', 'UniqueId' ] }") } }) { var graphClient = testHarness.CreateAndConnectGraphClient(); //Act //Act var results = graphClient.ExecuteGetCypherResults<ResultWithRelationshipDto>(cypherQuery); //Assert Assert.IsInstanceOf<IEnumerable<ResultWithRelationshipDto>>(results); var resultsArray = results.ToArray(); Assert.AreEqual(3, resultsArray.Count()); var firstResult = resultsArray[0]; Assert.AreEqual(0, firstResult.Fooness.Reference.Id); Assert.AreEqual("bar", firstResult.Fooness.Data.Bar); Assert.AreEqual("baz", firstResult.Fooness.Data.Baz); Assert.AreEqual("HOSTS", firstResult.RelationshipType); Assert.AreEqual("foo", firstResult.Name); Assert.AreEqual(44321, firstResult.UniqueId); var secondResult = resultsArray[1]; Assert.AreEqual(1, secondResult.Fooness.Reference.Id); Assert.AreEqual("bar", secondResult.Fooness.Data.Bar); Assert.AreEqual("baz", secondResult.Fooness.Data.Baz); Assert.AreEqual("LIKES", secondResult.RelationshipType); Assert.AreEqual("bar", secondResult.Name); Assert.AreEqual(44311, secondResult.UniqueId); var thirdResult = resultsArray[2]; Assert.AreEqual(2, thirdResult.Fooness.Reference.Id); Assert.AreEqual("bar", thirdResult.Fooness.Data.Bar); Assert.AreEqual("baz", thirdResult.Fooness.Data.Baz); Assert.AreEqual("HOSTS", thirdResult.RelationshipType); Assert.AreEqual("baz", thirdResult.Name); Assert.AreEqual(42586, thirdResult.UniqueId); } }
public void TestTransactionScopeWithSimpleDeserialization() { const string queryText = @"MATCH (n) RETURN count(n)"; const string resultColumn = @"{'columns':['count(n)'], 'data':[{'row':[1]}]}"; var cypherQuery = new CypherQuery(queryText, new Dictionary<string, object>(), CypherResultMode.Projection); var cypherApiQuery = new CypherStatementList { new CypherTransactionStatement(cypherQuery, false) }; var commitRequest = MockRequest.PostJson("/transaction/1/commit", @"{'statements': []}"); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/transaction", cypherApiQuery), MockResponse.Json(201, GenerateInitTransactionResponse(1, resultColumn), "http://foo/db/data/transaction/1") }, { commitRequest, MockResponse.Json(200, @"{'results':[], 'errors':[] }") } }) { var client = testHarness.CreateAndConnectTransactionalGraphClient(); using (var msTransaction = new TransactionScope()) { Assert.IsTrue(client.InTransaction); long total = client.Cypher .Match("(n)") .Return(n => n.Count()) .Results .SingleOrDefault(); Assert.AreEqual(1, total); msTransaction.Complete(); } Assert.IsFalse(client.InTransaction); } }
public void NestedTransactionWithTransactionScopeQueryFirst() { const string queryTextMsTransaction = @"MATCH (n) RETURN count(n)"; const string queryTextTx = @"MATCH (t) RETURN count(t)"; const string resultColumn = @"{'columns':['count(n)'], 'data':[{'row':[1]}]}"; var cypherQueryMsTx = new CypherQuery(queryTextMsTransaction, new Dictionary<string, object>(), CypherResultMode.Projection); var cypherQueryMsTxStatement = new CypherStatementList { new CypherTransactionStatement(cypherQueryMsTx, false) }; var cypherQueryTx = new CypherQuery(queryTextTx, new Dictionary<string, object>(), CypherResultMode.Projection); var cypherQueryTxStatement = new CypherStatementList { new CypherTransactionStatement(cypherQueryTx, false) }; var deleteRequest = MockRequest.Delete("/transaction/1"); var commitRequest = MockRequest.PostJson("/transaction/1/commit", @"{'statements': []}"); var commitRequestTx = MockRequest.PostJson("/transaction/2/commit", @"{'statements': []}"); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/transaction", cypherQueryMsTxStatement), MockResponse.Json(201, GenerateInitTransactionResponse(1, resultColumn), "http://foo/db/data/transaction/1") }, { MockRequest.PostObjectAsJson("/transaction", cypherQueryTxStatement), MockResponse.Json(201, GenerateInitTransactionResponse(2, resultColumn), "http://foo/db/data/transaction/2") }, { commitRequest, MockResponse.Json(200, @"{'results':[], 'errors':[] }") }, { commitRequestTx, MockResponse.Json(200, @"{'results':[], 'errors':[] }") }, { deleteRequest, MockResponse.Json(200, @"{'results':[], 'errors':[] }") } }.ShouldNotBeCalled(commitRequest)) { var client = testHarness.CreateAndConnectTransactionalGraphClient(); using (var msTransaction = new TransactionScope()) { Assert.IsTrue(client.InTransaction); long totalMsTx = client.Cypher .Match("(n)") .Return(n => n.Count()) .Results .SingleOrDefault(); Assert.AreEqual(1, totalMsTx); using (var tx = client.BeginTransaction()) { long total = client.Cypher .Match("(t)") .Return(t => t.Count()) .Results .SingleOrDefault(); Assert.AreEqual(1, total); // should not be called tx.Commit(); } } } }
public void AsyncRequestsInTransactionShouldBeExecutedInOrder() { const string queryTextBase = @"MATCH (n) RETURN {0} as Total"; const string resultColumnBase = @"{{'columns':['Total'], 'data':[{{'row':[{0}]}}]}}"; const int asyncRequests = 15; var queries = new CypherQuery[asyncRequests]; var apiQueries = new CypherStatementList[asyncRequests]; var responses = new MockResponse[asyncRequests]; var testHarness = new RestHarnessWithCounter(); for (int i = 0; i < asyncRequests; i++) { queries[i] = new CypherQuery(string.Format(queryTextBase, i), new Dictionary<string, object>(), CypherResultMode.Projection); apiQueries[i] = new CypherStatementList {new CypherTransactionStatement(queries[i], false)}; responses[i] = MockResponse.Json(200, @"{'results':[" + string.Format(resultColumnBase, i) + @"], 'errors':[] }"); if (i > 0) { testHarness.Add(MockRequest.PostObjectAsJson("/transaction/1", apiQueries[i]), responses[i]); } } testHarness.Add( MockRequest.PostObjectAsJson("/transaction", apiQueries[0]), MockResponse.Json(201, GenerateInitTransactionResponse(1, string.Format(resultColumnBase, 0)), "http://foo/db/data/transaction/1") ); testHarness.Add( MockRequest.PostJson("/transaction/1/commit", @"{'statements': []}"), MockResponse.Json(200, @"{'results':[], 'errors':[] }") ); try { var client = testHarness.CreateAndConnectTransactionalGraphClient(); var rawClient = (IRawGraphClient)client; var tasks = new Task[asyncRequests]; using (var tran = client.BeginTransaction()) { for (int i = 0; i < asyncRequests; i++) { int tmpResult = i; tasks[i] = rawClient.ExecuteGetCypherResultsAsync<DummyTotal>(queries[i]).ContinueWith(task => { Assert.AreEqual(tmpResult, task.Result.Single().Total); }); } Task.WaitAll(tasks); tran.Commit(); } } finally { testHarness.Dispose(); } // check that we have a total order Assert.AreEqual(asyncRequests, testHarness.Queue.Count); int lastElement = -1; for (int i = 0; i < asyncRequests; i++) { int headItem; Assert.IsTrue(testHarness.Queue.TryDequeue(out headItem)); Assert.Greater(headItem, lastElement); lastElement = headItem; } }
public void ExecuteAsyncRequestInTransaction() { const string queryText = @"MATCH (n) RETURN count(n) as Total"; const string resultColumn = @"{'columns':['Total'], 'data':[{'row':[1]}]}"; var cypherQuery = new CypherQuery(queryText, new Dictionary<string, object>(), CypherResultMode.Projection); var cypherApiQuery = new CypherStatementList { new CypherTransactionStatement(cypherQuery, false) }; var commitRequest = MockRequest.PostJson("/transaction/1/commit", @"{'statements': []}"); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/transaction", cypherApiQuery), MockResponse.Json(201, GenerateInitTransactionResponse(1, resultColumn), "http://foo/db/data/transaction/1") }, { commitRequest, MockResponse.Json(200, @"{'results':[], 'errors':[] }") } }) { var client = testHarness.CreateAndConnectTransactionalGraphClient(); var rawClient = (IRawGraphClient) client; using (var tran = client.BeginTransaction()) { var totalObj = rawClient.ExecuteGetCypherResultsAsync<DummyTotal>(cypherQuery).Result.Single(); Assert.AreEqual(1, totalObj.Total); tran.Commit(); } } }
public void CommitFailsOnPendingAsyncRequests() { const string queryText = @"MATCH (n) RETURN count(n) as Total"; const string resultColumn = @"{'columns':['Total'], 'data':[{'row':[1]}]}"; var cypherQuery = new CypherQuery(queryText, new Dictionary<string, object>(), CypherResultMode.Projection); var cypherApiQuery = new CypherStatementList { new CypherTransactionStatement(cypherQuery, false) }; using (var testHarness = new RestTestHarness(false) { { MockRequest.PostObjectAsJson("/transaction", cypherApiQuery), MockResponse.Json(201, GenerateInitTransactionResponse(1, resultColumn), "http://foo/db/data/transaction/1") } }) { var client = testHarness.CreateAndConnectTransactionalGraphClient(); var rawClient = (IRawGraphClient) client; using (var tran = client.BeginTransaction()) { rawClient.ExecuteGetCypherResultsAsync<DummyTotal>(cypherQuery); tran.Commit(); } } }
public void TestTransactionScopeWithComplexDeserialization() { const string queryText = @"MATCH (dt:DummyTotal) RETURN dt"; const string resultColumn = @"{'columns':['dt'],'data':[{'row':[{'total':1234}]}]}"; var cypherQuery = new CypherQuery(queryText, new Dictionary<string, object>(), CypherResultMode.Projection); var cypherApiQuery = new CypherStatementList { new CypherTransactionStatement(cypherQuery, false) }; var commitRequest = MockRequest.PostJson("/transaction/1/commit", @"{'statements': []}"); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/transaction", cypherApiQuery), MockResponse.Json(201, TransactionRestResponseHelper.GenerateInitTransactionResponse(1, resultColumn), "http://foo/db/data/transaction/1") }, { commitRequest, MockResponse.Json(200, @"{'results':[], 'errors':[] }") } }) { var client = testHarness.CreateAndConnectTransactionalGraphClient(); client.JsonContractResolver = new CamelCasePropertyNamesContractResolver(); using (var msTransaction = new TransactionScope()) { Assert.IsTrue(client.InTransaction); var results = client.Cypher.Match("(dt:DummyTotal)") .Return(dt => dt.As<DummyTotal>()) .Results .ToList(); Assert.AreEqual(1, results.Count()); Assert.AreEqual(1234, results.First().Total); msTransaction.Complete(); } Assert.IsFalse(client.InTransaction); } }
public void ShouldSupportAnonymousReturnTypesEndToEnd() { const string queryText = "START root=node({p0})\r\nMATCH root-->other\r\nRETURN other AS Foo"; var parameters = new Dictionary<string, object> { {"p0", 123} }; var cypherQuery = new CypherQuery(queryText, parameters, CypherResultMode.Projection); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Json(HttpStatusCode.OK, @"{ 'columns' : [ 'Foo' ], 'data' : [ [ { 'outgoing_relationships' : 'http://localhost:8000/db/data/node/748/relationships/out', 'data' : { 'Name' : 'Antimony', 'UniqueId' : 38 }, 'all_typed_relationships' : 'http://localhost:8000/db/data/node/748/relationships/all/{-list|&|types}', 'traverse' : 'http://localhost:8000/db/data/node/748/traverse/{returnType}', 'self' : 'http://localhost:8000/db/data/node/748', 'property' : 'http://localhost:8000/db/data/node/748/properties/{key}', 'outgoing_typed_relationships' : 'http://localhost:8000/db/data/node/748/relationships/out/{-list|&|types}', 'properties' : 'http://localhost:8000/db/data/node/748/properties', 'incoming_relationships' : 'http://localhost:8000/db/data/node/748/relationships/in', 'extensions' : { }, 'create_relationship' : 'http://localhost:8000/db/data/node/748/relationships', 'paged_traverse' : 'http://localhost:8000/db/data/node/748/paged/traverse/{returnType}{?pageSize,leaseTime}', 'all_relationships' : 'http://localhost:8000/db/data/node/748/relationships/all', 'incoming_typed_relationships' : 'http://localhost:8000/db/data/node/748/relationships/in/{-list|&|types}' } ], [ { 'outgoing_relationships' : 'http://localhost:8000/db/data/node/610/relationships/out', 'data' : { 'Name' : 'Bauxite', 'UniqueId' : 24 }, 'all_typed_relationships' : 'http://localhost:8000/db/data/node/610/relationships/all/{-list|&|types}', 'traverse' : 'http://localhost:8000/db/data/node/610/traverse/{returnType}', 'self' : 'http://localhost:8000/db/data/node/610', 'property' : 'http://localhost:8000/db/data/node/610/properties/{key}', 'outgoing_typed_relationships' : 'http://localhost:8000/db/data/node/610/relationships/out/{-list|&|types}', 'properties' : 'http://localhost:8000/db/data/node/610/properties', 'incoming_relationships' : 'http://localhost:8000/db/data/node/610/relationships/in', 'extensions' : { }, 'create_relationship' : 'http://localhost:8000/db/data/node/610/relationships', 'paged_traverse' : 'http://localhost:8000/db/data/node/610/paged/traverse/{returnType}{?pageSize,leaseTime}', 'all_relationships' : 'http://localhost:8000/db/data/node/610/relationships/all', 'incoming_typed_relationships' : 'http://localhost:8000/db/data/node/610/relationships/in/{-list|&|types}' } ], [ { 'outgoing_relationships' : 'http://localhost:8000/db/data/node/749/relationships/out', 'data' : { 'Name' : 'Bismuth', 'UniqueId' : 37 }, 'all_typed_relationships' : 'http://localhost:8000/db/data/node/749/relationships/all/{-list|&|types}', 'traverse' : 'http://localhost:8000/db/data/node/749/traverse/{returnType}', 'self' : 'http://localhost:8000/db/data/node/749', 'property' : 'http://localhost:8000/db/data/node/749/properties/{key}', 'outgoing_typed_relationships' : 'http://localhost:8000/db/data/node/749/relationships/out/{-list|&|types}', 'properties' : 'http://localhost:8000/db/data/node/749/properties', 'incoming_relationships' : 'http://localhost:8000/db/data/node/749/relationships/in', 'extensions' : { }, 'create_relationship' : 'http://localhost:8000/db/data/node/749/relationships', 'paged_traverse' : 'http://localhost:8000/db/data/node/749/paged/traverse/{returnType}{?pageSize,leaseTime}', 'all_relationships' : 'http://localhost:8000/db/data/node/749/relationships/all', 'incoming_typed_relationships' : 'http://localhost:8000/db/data/node/749/relationships/in/{-list|&|types}' } ] ] }") } }) { var graphClient = testHarness.CreateAndConnectGraphClient(); var results = graphClient .Cypher .Start("root", graphClient.RootNode) .Match("root-->other") .Return(other => new { Foo = other.As<Commodity>() }) .Results .ToList(); Assert.AreEqual(3, results.Count()); var result = results[0]; Assert.AreEqual("Antimony", result.Foo.Name); Assert.AreEqual(38, result.Foo.UniqueId); result = results[1]; Assert.AreEqual("Bauxite", result.Foo.Name); Assert.AreEqual(24, result.Foo.UniqueId); result = results[2]; Assert.AreEqual("Bismuth", result.Foo.Name); Assert.AreEqual(37, result.Foo.UniqueId); } }
public void WhenExecuteCypherFails_ShouldRaiseCompletedWithException() { // Arrange const string queryText = @"bad cypher"; var parameters = new Dictionary<string, object>(); var cypherQuery = new CypherQuery(queryText, parameters, CypherResultMode.Set); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Throws() } }) { var graphClient = testHarness.CreateAndConnectGraphClient(); OperationCompletedEventArgs eventArgs = null; graphClient.OperationCompleted += (sender, e) => { eventArgs = e; }; //Act Assert.Throws<MockResponseThrowsException>(() => { graphClient.ExecuteCypher(cypherQuery); }, "We should expect an exception"); Assert.IsNotNull(eventArgs, "but we should also have received the completion event"); Assert.IsTrue(eventArgs.HasException); Assert.AreEqual(typeof(MockResponseThrowsException), eventArgs.Exception.GetType()); Assert.AreEqual(-1, eventArgs.ResourcesReturned); } }
public void CommitFailsOnPendingAsyncRequests() { const string queryText = @"MATCH (n) RETURN count(n) as Total"; const string resultColumn = @"{'columns':['Total'], 'data':[{'row':[1]}]}"; var cypherQuery = new CypherQuery(queryText, new Dictionary<string, object>(), CypherResultMode.Projection); var cypherApiQuery = new CypherStatementList { new CypherTransactionStatement(cypherQuery, false) }; using (var testHarness = new RestTestHarness(false) { { MockRequest.PostObjectAsJson("/transaction", cypherApiQuery), MockResponse.Json(201, TransactionRestResponseHelper.GenerateInitTransactionResponse(1, resultColumn), "http://foo/db/data/transaction/1") } }) { var client = testHarness.CreateAndConnectTransactionalGraphClient(); var rawClient = (IRawGraphClient) client; using (var tran = client.BeginTransaction()) { rawClient.ExecuteGetCypherResultsAsync<DummyTotal>(cypherQuery); var ex = Assert.Throws<InvalidOperationException>(() => tran.Commit()); Assert.AreEqual("Cannot commit unless all tasks have been completed", ex.Message); } } }
public void TestTransactionScopeWithComplexDeserialization_WithCulture() { Thread.CurrentThread.CurrentCulture = new CultureInfo("nb-NO"); const string queryText = @"MATCH (dt:DummyTotal) RETURN dt"; const string resultColumn = @"{'columns':['dt'],'data':[{'row':[{'date':'2015-07-27T22:30:35Z'}]}]}"; var cypherQuery = new CypherQuery(queryText, new Dictionary<string, object>(), CypherResultMode.Projection); var cypherApiQuery = new CypherStatementList { new CypherTransactionStatement(cypherQuery, false) }; var commitRequest = MockRequest.PostJson("/transaction/1/commit", @"{'statements': []}"); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/transaction", cypherApiQuery), MockResponse.Json(201, TransactionRestResponseHelper.GenerateInitTransactionResponse(1, resultColumn), "http://foo/db/data/transaction/1") }, { commitRequest, MockResponse.Json(200, @"{'results':[], 'errors':[] }") } }) { var client = testHarness.CreateAndConnectTransactionalGraphClient(); client.JsonContractResolver = new CamelCasePropertyNamesContractResolver(); using (var msTransaction = new TransactionScope()) { Assert.IsTrue(client.InTransaction); var query = client.Cypher.Match("(dt:DummyTotal)") .Return(dt => dt.As<DateHolder>()); var eResults = query.Results; var results = eResults.ToList(); Assert.AreEqual(1, results.Count); var date = results.First().Date; Assert.AreEqual(date.Kind, DateTimeKind.Utc); Assert.AreEqual(new DateTime(2015,7,27,22,30,35), results.First().Date); msTransaction.Complete(); } Assert.IsFalse(client.InTransaction); } }
public void ShouldPromoteBadQueryResponseToNiceException() { // Arrange const string queryText = @"broken query"; var cypherQuery = new CypherQuery(queryText, new Dictionary<string, object>(), CypherResultMode.Projection, CypherResultFormat.Rest); var cypherApiQuery = new CypherApiQuery(cypherQuery); using (var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Json(HttpStatusCode.BadRequest, @"{ 'message' : 'expected START or CREATE\n\'bad query\'\n ^', 'exception' : 'SyntaxException', 'fullname' : 'org.neo4j.cypher.SyntaxException', 'stacktrace' : [ 'org.neo4j.cypher.internal.parser.v1_9.CypherParserImpl.parse(CypherParserImpl.scala:45)', 'org.neo4j.cypher.CypherParser.parse(CypherParser.scala:44)', 'org.neo4j.cypher.ExecutionEngine$$anonfun$prepare$1.apply(ExecutionEngine.scala:80)', 'org.neo4j.cypher.ExecutionEngine$$anonfun$prepare$1.apply(ExecutionEngine.scala:80)', 'org.neo4j.cypher.internal.LRUCache.getOrElseUpdate(LRUCache.scala:37)', 'org.neo4j.cypher.ExecutionEngine.prepare(ExecutionEngine.scala:80)', 'org.neo4j.cypher.ExecutionEngine.execute(ExecutionEngine.scala:72)', 'org.neo4j.cypher.ExecutionEngine.execute(ExecutionEngine.scala:76)', 'org.neo4j.cypher.javacompat.ExecutionEngine.execute(ExecutionEngine.java:79)', 'org.neo4j.server.rest.web.CypherService.cypher(CypherService.java:94)', 'java.lang.reflect.Method.invoke(Unknown Source)', 'org.neo4j.server.rest.security.SecurityFilter.doFilter(SecurityFilter.java:112)' ] }") } }) { var graphClient = testHarness.CreateAndConnectGraphClient(); var ex = Assert.Throws<NeoException>(() => graphClient.ExecuteGetCypherResults<ResultWithRelationshipDto>(cypherQuery)); Assert.AreEqual("SyntaxException: expected START or CREATE\n'bad query'\n ^", ex.Message); Assert.AreEqual("expected START or CREATE\n'bad query'\n ^", ex.NeoMessage); Assert.AreEqual("SyntaxException", ex.NeoExceptionName); Assert.AreEqual("org.neo4j.cypher.SyntaxException", ex.NeoFullName); var expectedStack = new[] { "org.neo4j.cypher.internal.parser.v1_9.CypherParserImpl.parse(CypherParserImpl.scala:45)", "org.neo4j.cypher.CypherParser.parse(CypherParser.scala:44)", "org.neo4j.cypher.ExecutionEngine$$anonfun$prepare$1.apply(ExecutionEngine.scala:80)", "org.neo4j.cypher.ExecutionEngine$$anonfun$prepare$1.apply(ExecutionEngine.scala:80)", "org.neo4j.cypher.internal.LRUCache.getOrElseUpdate(LRUCache.scala:37)", "org.neo4j.cypher.ExecutionEngine.prepare(ExecutionEngine.scala:80)", "org.neo4j.cypher.ExecutionEngine.execute(ExecutionEngine.scala:72)", "org.neo4j.cypher.ExecutionEngine.execute(ExecutionEngine.scala:76)", "org.neo4j.cypher.javacompat.ExecutionEngine.execute(ExecutionEngine.java:79)", "org.neo4j.server.rest.web.CypherService.cypher(CypherService.java:94)", "java.lang.reflect.Method.invoke(Unknown Source)", "org.neo4j.server.rest.security.SecurityFilter.doFilter(SecurityFilter.java:112)" }; CollectionAssert.AreEqual(expectedStack, ex.NeoStackTrace); } }
public void ShouldDeserializeSimpleTableStructure() { // Arrange const string queryText = @" START x = node({p0}) MATCH x-[r]->n RETURN type(r) AS RelationshipType, n.Name? AS Name, n.UniqueId? AS UniqueId LIMIT 3"; var cypherQuery = new CypherQuery( queryText, new Dictionary<string, object> { {"p0", 123} }, CypherResultMode.Projection, CypherResultFormat.Rest); var cypherApiQuery = new CypherApiQuery(cypherQuery); using(var testHarness = new RestTestHarness { { MockRequest.PostObjectAsJson("/cypher", cypherApiQuery), MockResponse.Json(HttpStatusCode.OK, @"{ 'data' : [ [ 'HOSTS', 'foo', 44321 ], [ 'LIKES', 'bar', 44311 ], [ 'HOSTS', 'baz', 42586 ] ], 'columns' : [ 'RelationshipType', 'Name', 'UniqueId' ] }") } }) { var graphClient = testHarness.CreateAndConnectGraphClient(); //Act var results = graphClient.ExecuteGetCypherResults<SimpleResultDto>(cypherQuery); //Assert Assert.IsInstanceOf<IEnumerable<SimpleResultDto>>(results); var resultsArray = results.ToArray(); Assert.AreEqual(3, resultsArray.Count()); var firstResult = resultsArray[0]; Assert.AreEqual("HOSTS", firstResult.RelationshipType); Assert.AreEqual("foo", firstResult.Name); Assert.AreEqual(44321, firstResult.UniqueId); var secondResult = resultsArray[1]; Assert.AreEqual("LIKES", secondResult.RelationshipType); Assert.AreEqual("bar", secondResult.Name); Assert.AreEqual(44311, secondResult.UniqueId); var thirdResult = resultsArray[2]; Assert.AreEqual("HOSTS", thirdResult.RelationshipType); Assert.AreEqual("baz", thirdResult.Name); Assert.AreEqual(42586, thirdResult.UniqueId); } }