Exemplo n.º 1
0
        public async Task <TResponse> EnqueueTask(string commandDescription, TClient graphClient, IExecutionPolicy policy, CypherQuery query)
        {
            var taskCompletion = new TaskCompletionSource <TResponse>();

            try
            {
                var localPreviousTask = Interlocked.Exchange(ref previousTask, taskCompletion.Task);
                if (localPreviousTask != null)
                {
                    await localPreviousTask.ConfigureAwait(false);
                }
                var resp = await RunQuery(graphClient, query, policy, commandDescription).ConfigureAwait(false);

                taskCompletion.SetResult(resp);
            }
            catch (OperationCanceledException)
            {
                taskCompletion.SetCanceled();
            }
            catch (Exception e)
            {
                taskCompletion.SetException(e);
            }

            return(await taskCompletion.Task.ConfigureAwait(false));
        }
Exemplo n.º 2
0
 public void Complete(CypherQuery query, Bookmark lastBookmark, Exception exception)
 {
     // only parse the events when there's an event handler
     Complete(owner.OperationCompleted != null ? query.DebugQueryText : string.Empty, lastBookmark, -1, exception, identifier: query.Identifier, bookmarks: query.Bookmarks);
 }
Exemplo n.º 3
0
 public static bool ContainsParameter(this CypherQuery query, string parameterKey, object parameterValue)
 {
     return(query.QueryParameters.ContainsKey(parameterKey) && query.QueryParameters[parameterKey].Equals(parameterValue));
 }
Exemplo n.º 4
0
        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);

            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);
            }
        }
Exemplo n.º 5
0
 public void Complete(CypherQuery query, Bookmark lastBookmark, QueryStats queryStats)
 {
     Complete(owner.OperationCompleted != null ? query.DebugQueryText : string.Empty, lastBookmark, 0, null, identifier: query.Identifier, bookmarks: query.Bookmarks, stats: queryStats);
 }
Exemplo n.º 6
0
        /// <inheritdoc />
        async Task <IEnumerable <TResult> > IRawGraphClient.ExecuteGetCypherResultsAsync <TResult>(CypherQuery query)
        {
            if (Driver == null)
            {
                throw new InvalidOperationException("Can't execute cypher unless you have connected to the server.");
            }

            var            context = ExecutionContext.Begin(this);
            List <TResult> results;

            try
            {
//                var inTransaction = ;
                if (InTransaction)
                {
                    var result = await transactionManager.EnqueueCypherRequest($"The query was: {query.QueryText}", this, query).ConfigureAwait(false);

                    results = ParseResults <TResult>(result.StatementResult, query);
                }
                else
                {
                    using (var session = Driver.Session(query.IsWrite ? AccessMode.Write : AccessMode.Read))
                    {
                        var result = session.Run(query, this);
                        results = ParseResults <TResult>(result, query);
                    }
                }
            }
            catch (AggregateException aggregateException)
            {
                Exception unwrappedException;
                context.Complete(query, aggregateException.TryUnwrap(out unwrappedException) ? unwrappedException : aggregateException);
                throw;
            }
            catch (Exception e)
            {
                context.Complete(query, e);
                throw;
            }

            context.Complete(query, results.Count); //Doesn't this parse all the entries?
            return(results);
        }
Exemplo n.º 7
0
        public void ShouldDeserializeArrayOfNodesInPropertyAsResultOfCollectFunctionInCypherQuery()
        {
            // Arrange
            var cypherQuery = new CypherQuery(
                @"START root=node(0) MATCH root-[:HAS_COMPANIES]->()-[:HAS_COMPANY]->company, company--foo RETURN company, collect(foo) as Bar",
                new Dictionary <string, object>(),
                CypherResultMode.Projection);

            var cypherApiQuery = new CypherApiQuery(cypherQuery);

            using (var testHarness = new RestTestHarness
            {
                {
                    MockRequest.PostObjectAsJson("/cypher", cypherApiQuery),
                    MockResponse.Json(HttpStatusCode.OK, @"{
  'columns' : [ 'ColumnA', 'ColumnBFromCollect' ],
  'data' : [ [ {
    'paged_traverse' : 'http://localhost:8000/db/data/node/358/paged/traverse/{returnType}{?pageSize,leaseTime}',
    'outgoing_relationships' : 'http://localhost:8000/db/data/node/358/relationships/out',
    'data' : {
      'Bar' : 'BHP',
      'Baz' : '1'
    },
    'all_typed_relationships' : 'http://localhost:8000/db/data/node/358/relationships/all/{-list|&|types}',
    'traverse' : 'http://localhost:8000/db/data/node/358/traverse/{returnType}',
    'self' : 'http://localhost:8000/db/data/node/358',
    'property' : 'http://localhost:8000/db/data/node/358/properties/{key}',
    'all_relationships' : 'http://localhost:8000/db/data/node/358/relationships/all',
    'outgoing_typed_relationships' : 'http://localhost:8000/db/data/node/358/relationships/out/{-list|&|types}',
    'properties' : 'http://localhost:8000/db/data/node/358/properties',
    'incoming_relationships' : 'http://localhost:8000/db/data/node/358/relationships/in',
    'incoming_typed_relationships' : 'http://localhost:8000/db/data/node/358/relationships/in/{-list|&|types}',
    'extensions' : {
    },
    'create_relationship' : 'http://localhost:8000/db/data/node/358/relationships'
  }, [ {
    'paged_traverse' : 'http://localhost:8000/db/data/node/362/paged/traverse/{returnType}{?pageSize,leaseTime}',
    'outgoing_relationships' : 'http://localhost:8000/db/data/node/362/relationships/out',
    'data' : {
      'OpportunityType' : 'Board',
      'Description' : 'Foo'
    },
    'all_typed_relationships' : 'http://localhost:8000/db/data/node/362/relationships/all/{-list|&|types}',
    'traverse' : 'http://localhost:8000/db/data/node/362/traverse/{returnType}',
    'self' : 'http://localhost:8000/db/data/node/362',
    'property' : 'http://localhost:8000/db/data/node/362/properties/{key}',
    'all_relationships' : 'http://localhost:8000/db/data/node/362/relationships/all',
    'outgoing_typed_relationships' : 'http://localhost:8000/db/data/node/362/relationships/out/{-list|&|types}',
    'properties' : 'http://localhost:8000/db/data/node/362/properties',
    'incoming_relationships' : 'http://localhost:8000/db/data/node/362/relationships/in',
    'incoming_typed_relationships' : 'http://localhost:8000/db/data/node/362/relationships/in/{-list|&|types}',
    'extensions' : {
    },
    'create_relationship' : 'http://localhost:8000/db/data/node/362/relationships'
  }, {
    'paged_traverse' : 'http://localhost:8000/db/data/node/359/paged/traverse/{returnType}{?pageSize,leaseTime}',
    'outgoing_relationships' : 'http://localhost:8000/db/data/node/359/relationships/out',
    'data' : {
      'OpportunityType' : 'Executive',
      'Description' : 'Bar'
    },
    'all_typed_relationships' : 'http://localhost:8000/db/data/node/359/relationships/all/{-list|&|types}',
    'traverse' : 'http://localhost:8000/db/data/node/359/traverse/{returnType}',
    'self' : 'http://localhost:8000/db/data/node/359',
    'property' : 'http://localhost:8000/db/data/node/359/properties/{key}',
    'all_relationships' : 'http://localhost:8000/db/data/node/359/relationships/all',
    'outgoing_typed_relationships' : 'http://localhost:8000/db/data/node/359/relationships/out/{-list|&|types}',
    'properties' : 'http://localhost:8000/db/data/node/359/properties',
    'incoming_relationships' : 'http://localhost:8000/db/data/node/359/relationships/in',
    'incoming_typed_relationships' : 'http://localhost:8000/db/data/node/359/relationships/in/{-list|&|types}',
    'extensions' : {
    },
    'create_relationship' : 'http://localhost:8000/db/data/node/359/relationships'
  } ] ] ]
}")
                }
            })
            {
                var graphClient = testHarness.CreateAndConnectGraphClient();

                //Act
                var results = graphClient.ExecuteGetCypherResults <CollectResult>(cypherQuery);

                //Assert
                Assert.IsInstanceOf <IEnumerable <CollectResult> >(results);

                var resultsArray = results.ToArray();
                Assert.AreEqual(1, resultsArray.Count());

                var firstResult = resultsArray[0];
                Assert.AreEqual(358, firstResult.ColumnA.Reference.Id);
                Assert.AreEqual("BHP", firstResult.ColumnA.Data.Bar);
                Assert.AreEqual("1", firstResult.ColumnA.Data.Baz);

                var collectedResults = firstResult.ColumnBFromCollect.ToArray();
                Assert.AreEqual(2, collectedResults.Count());

                var firstCollectedResult = collectedResults[0];
                Assert.AreEqual(362, firstCollectedResult.Reference.Id);
                Assert.AreEqual("Board", firstCollectedResult.Data.OpportunityType);
                Assert.AreEqual("Foo", firstCollectedResult.Data.Description);

                var secondCollectedResult = collectedResults[1];
                Assert.AreEqual(359, secondCollectedResult.Reference.Id);
                Assert.AreEqual("Executive", secondCollectedResult.Data.OpportunityType);
                Assert.AreEqual("Bar", secondCollectedResult.Data.Description);
            }
        }
Exemplo n.º 8
0
        public async Task ShouldDeserializeMapWithAnonymousReturn()
        {
            // simulates the following query
            const string queryText = "MATCH (start:Node) WITH {Node: start, Count: 1} AS Node, start RETURN Node, start";

            var cypherQuery = new CypherQuery(queryText, new Dictionary <string, object>(), CypherResultMode.Projection,
                                              CypherResultFormat.Transactional, "neo4j");

            using (var testHarness = new BoltTestHarness())
            {
                INode start = new TestNode
                {
                    Id         = 1337,
                    Properties = new Dictionary <string, object>()
                    {
                        { "Ids", new List <int>()
                          {
                              1, 2, 3
                          } }
                    }
                };
                IDictionary <string, object> resultMap = new Dictionary <string, object>()
                {
                    { "Node", start },
                    { "Count", 1 }
                };

                var recordMock = new Mock <IRecord>();
                recordMock
                .Setup(r => r["Node"])
                .Returns(resultMap);
                recordMock
                .Setup(r => r["Start"])
                .Returns(start);
                recordMock
                .Setup(r => r.Keys)
                .Returns(new[] { "Node", "Start" });

                var testStatementResult = new TestStatementResult(new[] { "Node", "Start" }, recordMock.Object);
                testHarness.SetupCypherRequestResponse(cypherQuery.QueryText, cypherQuery.QueryParameters, testStatementResult);

                // the anon type
                var dummy = new
                {
                    Node  = new ObjectWithNodeWithIds(),
                    Start = new ObjectWithIds()
                };
                var anonType    = dummy.GetType();
                var graphClient = await testHarness.CreateAndConnectBoltGraphClient();

                var genericGetCypherResults   = typeof(IRawGraphClient).GetMethod(nameof(graphClient.ExecuteGetCypherResultsAsync));
                var anonymousGetCypherResults = genericGetCypherResults.MakeGenericMethod(anonType);
                var genericResultsTask        = anonymousGetCypherResults.Invoke(graphClient, new object[] { cypherQuery });
                await(Task) genericResultsTask;
                var genericResults = (IEnumerable)((dynamic)genericResultsTask).Result;

                var results = genericResults.Cast <object>().ToArray();

                //Assert
                Assert.Equal(1, results.Length);

                var startNode = (ObjectWithIds)anonType.GetProperty(nameof(dummy.Start)).GetValue(results.First(), null);
                startNode.Ids.Count.Should().Be(3);
                startNode.Ids[0].Should().Be(1);
                startNode.Ids[1].Should().Be(2);
                startNode.Ids[2].Should().Be(3);

                var nodeWrapper = (ObjectWithNodeWithIds)anonType.GetProperty(nameof(dummy.Node)).GetValue(results.First(), null);
                nodeWrapper.Count.Should().Be(1);
                startNode = nodeWrapper.Node;

                startNode.Ids.Count.Should().Be(3);
                startNode.Ids[0].Should().Be(1);
                startNode.Ids[1].Should().Be(2);
                startNode.Ids[2].Should().Be(3);
            }
        }
Exemplo n.º 9
0
        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, TransactionRestResponseHelper.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;
            }
        }
Exemplo n.º 10
0
        public async Task RelationshipShouldDeserializeInAnonymousType()
        {
            // Arrange
            const string queryText = @"MATCH (n:Test)-[r]->(t:Test) RETURN r AS Rel";

            var cypherQuery = new CypherQuery(queryText, new Dictionary <string, object>(), CypherResultMode.Projection, CypherResultFormat.Transactional, "neo4j");

            using (var testHarness = new BoltTestHarness())
            {
                var relationshipMock = new Mock <IRelationship>();
                relationshipMock
                .Setup(r => r.StartNodeId)
                .Returns(1);
                relationshipMock
                .Setup(r => r.EndNodeId)
                .Returns(2);
                relationshipMock
                .Setup(r => r.Type)
                .Returns("Xx");
                relationshipMock
                .Setup(r => r.Id)
                .Returns(3);
                relationshipMock
                .Setup(r => r.Properties)
                .Returns(new Dictionary <string, object>()
                {
                    { "Id", 42 }
                });

                var recordMock = new Mock <IRecord>();
                recordMock
                .Setup(r => r["Rel"])
                .Returns(relationshipMock.Object);
                recordMock
                .Setup(r => r.Keys)
                .Returns(new[] { "Rel" });

                var testStatementResult = new TestStatementResult(new[] { "Rel" }, recordMock.Object);
                testHarness.SetupCypherRequestResponse(cypherQuery.QueryText, cypherQuery.QueryParameters, testStatementResult);

                //Session mock???
                var dummy = new
                {
                    Rel = new RelationType()
                };
                var anonType    = dummy.GetType();
                var graphClient = await testHarness.CreateAndConnectBoltGraphClient();

                var genericGetCypherResults   = typeof(IRawGraphClient).GetMethod(nameof(graphClient.ExecuteGetCypherResultsAsync));
                var anonymousGetCypherResults = genericGetCypherResults.MakeGenericMethod(anonType);
                var genericResultsTask        = anonymousGetCypherResults.Invoke(graphClient, new object[] { cypherQuery });
                await(Task) genericResultsTask;
                var genericResults = (IEnumerable)((dynamic)genericResultsTask).Result;

                var results = genericResults.Cast <object>().ToArray();

                //Assert
                Assert.Equal(1, results.Length);
                var relation = (RelationType)anonType.GetProperty(nameof(dummy.Rel)).GetValue(results.First(), null);
                relation.Id.Should().Be(42);
            }
        }
Exemplo n.º 11
0
        public async Task CollectionOfComplexTypesShouldDeserializeCorrectlyWhenInConjunctionWithAnotherComplexTypeInAContainer()
        {
            const string queryText = "MATCH (start:Node)-->(next:Node) RETURN start AS Start, collect(next) AS Next";

            var queryParams = new Dictionary <string, object>();

            var cypherQuery = new CypherQuery(queryText, queryParams, CypherResultMode.Projection, CypherResultFormat.Transactional, "neo4j");

            using (var testHarness = new BoltTestHarness())
            {
                var startNodeMock = new Mock <INode>();
                startNodeMock
                .Setup(n => n.Id)
                .Returns(1);
                startNodeMock
                .Setup(n => n.Properties)
                .Returns(new Dictionary <string, object> {
                    { "Id", 1 }
                });

                var nextNodeMock = new Mock <INode>();
                nextNodeMock
                .Setup(n => n.Id)
                .Returns(2);
                nextNodeMock
                .Setup(n => n.Properties)
                .Returns(new Dictionary <string, object> {
                    { "Id", 2 }
                });

                var recordMock = new Mock <IRecord>();
                recordMock
                .Setup(r => r["Next"])
                .Returns(new List <INode> {
                    nextNodeMock.Object
                });

                recordMock
                .Setup(r => r["Start"])
                .Returns(startNodeMock.Object);

                recordMock
                .Setup(r => r.Keys)
                .Returns(new[] { "Start", "Next" });

                var testStatementResult = new TestStatementResult(new[] { "Start", "Next" }, recordMock.Object);
                testHarness.SetupCypherRequestResponse(cypherQuery.QueryText, cypherQuery.QueryParameters, testStatementResult);

                var graphClient = await testHarness.CreateAndConnectBoltGraphClient();

                var results = (await graphClient.ExecuteGetCypherResultsAsync <Container>(cypherQuery)).ToArray();

                //Assert
                var deserializedObject = results.First();
                deserializedObject.Start.Should().NotBeNull();
                deserializedObject.Start.Id.Should().Be(1);

                var deserializedNext = deserializedObject.Next.ToList();
                deserializedNext.Should().HaveCount(1);
                deserializedNext.First().Id.Should().Be(2);
            }
        }
        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);
            }
        }
Exemplo n.º 13
0
        private void btnInsure_Click(object sender, EventArgs e)
        {
            try
            {
                var pusac = rbYes.Checked ? "Da" : "Ne";
                if (cbInsuranceKind.Text == "Individualno")
                {
                    tbSecondIdentifier.Enabled = false;
                    tbThirdIdentifier.Enabled  = false;
                    tbFourthIdentifier.Enabled = false;

                    var query = new CypherQuery("Match (i:Insured), (p:Policy) where i.Identifier = '" + identifier + "' and p.Tip = 'Zivotno Osiguranje' and p.Vrsta = '" + cbInsuranceKind.Text + "'" +
                                                " create (i)-[r:HAS_POLICY{Razlog:'" + cbReason.Text + "', Pusac: '" +
                                                pusac + "', Uplata: '"
                                                + tbInsuranceStake.Text + "', OsiguravajucaSuma: '" + tbInsurancePayout.Text + "'}]->(p)", new Dictionary <string, object>(), CypherResultMode.Set);
                    ((IRawGraphClient)client).ExecuteCypher(query);

                    lbStatus.Text    = "Uspesno kreirana polisa. Korisnik osiguran.";
                    lbStatus.Visible = true;
                }
                else if (cbInsuranceKind.Text == "Porodicno")
                {
                    string first  = "";
                    string second = "";
                    string third  = "";

                    if (tbSecondIdentifier.Text != string.Empty)
                    {
                        var query = new CypherQuery("MATCH (i:Insured) where i.Identifier = '" + long.Parse(tbSecondIdentifier.Text) + "' return i"
                                                    , new Dictionary <string, object>(), CypherResultMode.Set);
                        var user = ((IRawGraphClient)client).ExecuteGetCypherResults <Insured>(query).SingleOrDefault();
                        if (user == null)
                        {
                            throw new Exception("Ne postoji 2. clan porodice sa prosledjenim jmbg-om");
                        }
                        first = tbSecondIdentifier.Text;
                    }
                    else
                    {
                        throw new Exception("Za porodicno osiguranje je neophodan jmbg 2. clana porodice.");
                    }
                    if (tbThirdIdentifier.Text != string.Empty)
                    {
                        var query = new CypherQuery("MATCH (i:Insured) where i.Identifier = '" + long.Parse(tbThirdIdentifier.Text) + "' return i"
                                                    , new Dictionary <string, object>(), CypherResultMode.Set);
                        var user = ((IRawGraphClient)client).ExecuteGetCypherResults <Insured>(query).SingleOrDefault();
                        if (user == null)
                        {
                            throw new Exception("Ne postoji 3. clan porodice sa prosledjenim jmbg-om");
                        }
                        second = tbThirdIdentifier.Text;
                    }
                    if (tbFourthIdentifier.Text != string.Empty)
                    {
                        var query = new CypherQuery("MATCH (i:Insured) where i.Identifier = '" + long.Parse(tbFourthIdentifier.Text) + "' return i"
                                                    , new Dictionary <string, object>(), CypherResultMode.Set);
                        var user = ((IRawGraphClient)client).ExecuteGetCypherResults <Insured>(query).SingleOrDefault();
                        if (user == null)
                        {
                            throw new Exception("Ne postoji 4. clan porodice sa prosledjenim jmbg-om");
                        }
                        third = tbFourthIdentifier.Text;
                    }

                    var queryString = new CypherQuery("Match (i:Insured), (p:Policy) where i.Identifier = '"
                                                      + identifier + "' and p.Tip = 'Zivotno Osiguranje' and p.Vrsta = '" + cbInsuranceKind.Text + "'" +
                                                      " create (i)-[r:HAS_GROUP_POLICY{Razlog:'" + cbReason.Text + "', Pusac: '" +
                                                      pusac + "', Uplata: '"
                                                      + tbInsuranceStake.Text + "', OsiguravajucaSuma: '" + tbInsurancePayout.Text +
                                                      "', DrugiClan: '" + first + "', TreciClan: '" + second + "', CetvrtiClan: '" + third + "'}]->(p)",
                                                      new Dictionary <string, object>(), CypherResultMode.Set);
                    ((IRawGraphClient)client).ExecuteCypher(queryString);
                    lbStatus.Text    = "Uspesno kreirana polisa. Korisnik osiguran.";
                    lbStatus.Visible = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 14
0
 public static async Task <IResultCursor> RunAsync(this IAsyncTransaction transaction, CypherQuery query, IGraphClient gc)
 {
     return(await transaction.RunAsync(query.QueryText, query.ToNeo4jDriverParameters(gc)));
 }
Exemplo n.º 15
0
 public void Complete(CypherQuery query, int resultsCount)
 {
     // only parse the events when there's an event handler
     Complete(owner.OperationCompleted != null ? query.DebugQueryText : string.Empty, resultsCount, null, query.CustomHeaders);
 }
Exemplo n.º 16
0
        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, TransactionRestResponseHelper.GenerateInitTransactionResponse(1, resultColumn), "http://foo/db/data/transaction/1")
                },
                {
                    MockRequest.PostObjectAsJson("/transaction", cypherQueryTxStatement),
                    MockResponse.Json(201, TransactionRestResponseHelper.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();
                    }
                }
            }
        }
Exemplo n.º 17
0
 public void Complete(CypherQuery query, Exception exception)
 {
     // only parse the events when there's an event handler
     Complete(owner.OperationCompleted != null ? query.DebugQueryText : string.Empty, -1, exception);
 }
Exemplo n.º 18
0
        public static List <Radnik> tryTest(Projekat novi, GraphClient client)
        {
            string[] razvojIbrojLjudi = novi.Potrebni_ljudi_iz_razvoja.Split(',');
            int      ukupanBroj       = 0;

            for (int i = 0; i < razvojIbrojLjudi.Length; i++)
            {
                string[] split        = razvojIbrojLjudi[i].Split(' ');
                int      parsovanBroj = 0;
                bool     done         = Int32.TryParse(split[1], out parsovanBroj);
                if (done)
                {
                    ukupanBroj += parsovanBroj;
                }
            }
            if (ukupanBroj == 0)
            {
                return(null);
            }

            string[] jezikIznanje = novi.Potrebno_iskustvo.Split(',');
            // ide r.Iskustvo =~ "splited[0] [splited[1]...10]" + or
            string query = "match (r:Radnik) where ";

            foreach (string jezik in jezikIznanje)
            {
                //nulta lokacija jezik a na prvoj ocena 1-10
                int outInt = 0;

                string[] splited = jezik.Split(' ');
                bool     done    = Int32.TryParse(splited[1], out outInt);
                if (!done)
                {
                    return(null);
                }
                string result = "";
                if (outInt == 10)
                {
                    result = "10";
                }
                else
                {
                    var range = Enumerable.Range(outInt, 10 - outInt).ToArray();
                    result = string.Join(" ", range);
                }

                //.*[PHP C] [1 2 3 4 5 6].*
                query += "r.Iskustvo =~ \".*" + splited[0] + "." + "[" + result + "].*\"" + " or ";
            }
            query  = query.TrimEnd("or ".ToCharArray());
            query += " return r";

            CypherQuery query1 = new CypherQuery(query, new Dictionary <string, object>(), CypherResultMode.Set);
            CypherQuery query2 = new CypherQuery(query + ".id", new Dictionary <string, object>(), CypherResultMode.Set);

            List <Radnik> listaRadnika  = ((IRawGraphClient)client).ExecuteGetCypherResults <Radnik>(query1).ToList();
            int           ukupnoRadnika = listaRadnika.Count;
            int           trecina       = ukupnoRadnika / 3;
            var           IDs           = ((IRawGraphClient)client).ExecuteGetCypherResults <string>(query2).ToList();
            string        idPattern     = "[" + string.Join(" ", IDs) + "]";

            List <Radnik> izabrani = new List <Radnik>();

            //napokon imamo listu radnika sa znanjima
            for (int i = listaRadnika.Count - 1; i >= 0; i--)
            {
                string id = listaRadnika[i].id;

                query = "match (n:Radnik)-[r:NE_SLAZE_SE]->(m:Radnik) where n.id=~\"" + idPattern + "\"" + "and m.id=\"" + id + "\" return count(n)";
                CypherQuery query3 = new CypherQuery(query, new Dictionary <string, object>(), CypherResultMode.Set);
                int         broj   = ((IRawGraphClient)client).ExecuteGetCypherResults <int>(query3).Single();
                if (broj > trecina)
                {
                    listaRadnika.RemoveAt(i);
                }
                if (broj == 0)
                {
                    query = "match (n:Radnik)-[r:SLAZE_SE]->(m:Radnik) where n.id=~\"" + id + "\" return m";
                    CypherQuery   query4  = new CypherQuery(query, new Dictionary <string, object>(), CypherResultMode.Set);
                    List <Radnik> friends = ((IRawGraphClient)client).ExecuteGetCypherResults <Radnik>(query4).ToList();
                    if (izabrani.Count + friends.Count < ukupanBroj)
                    {
                        izabrani.Add(listaRadnika[i]);
                        izabrani = izabrani.Concat <Radnik>(friends).ToList();
                    }
                    else
                    {
                        int koliko = ukupanBroj - izabrani.Count;
                        for (int j = 0; j < koliko - 1; j++)
                        {
                            izabrani.Add(friends[j]);
                        }
                    }
                }
                //client.Cypher.Match("(projekat:Projekat)", "(radnik:Radnik)")
                //       .Where((Projekat projekat) => projekat.Ime == novi.Ime)
                //       .AndWhere((Radnik radnik) => radnik.id == )
                //       .CreateUnique("projekat<-[:ANGAZOVAN_NA]-radnik")
                //       .ExecuteWithoutResults();
            }
            //
            //query = "match (n:Radnik)-[r:SLAZE_SE]->(m:Radnik) where n.id=~\"" + id + "\" return m";
            //CypherQuery query5 = new CypherQuery(query, new Dictionary<string, object>(), CypherResultMode.Set);

            return(izabrani);
        }
Exemplo n.º 19
0
        /// <inheritdoc />
        void IRawGraphClient.ExecuteCypher(CypherQuery query)
        {
            var task = ((IRawGraphClient)this).ExecuteCypherAsync(query);

            task.Wait();
        }
 public CypherTransactionStatement(CypherQuery query, bool restFormat)
 {
     _queryText       = query.QueryText;
     _queryParameters = query.QueryParameters ?? new Dictionary <string, object>();
     _formatContents  = restFormat ? new[] { "REST" } : new string[] {};
 }
Exemplo n.º 21
0
        public void ShouldDeserializeTableStructureWithNodeDataObjects()
        {
            // 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);

            var cypherApiQuery = new CypherApiQuery(cypherQuery);

            using (var testHarness = new RestTestHarness
            {
                {
                    MockRequest.PostObjectAsJson("/cypher", cypherApiQuery),
                    MockResponse.Json(HttpStatusCode.OK, @"{
                                'data' : [ [ {
                                'outgoing_relationships' : 'http://foo/db/data/node/0/relationships/out',
                                'data' : {
                                    'Bar' : 'bar',
                                    'Baz' : 'baz'
                                },
                                'traverse' : 'http://foo/db/data/node/0/traverse/{returnType}',
                                'all_typed_relationships' : 'http://foo/db/data/node/0/relationships/all/{-list|&|types}',
                                'property' : 'http://foo/db/data/node/0/properties/{key}',
                                'self' : 'http://foo/db/data/node/0',
                                'properties' : 'http://foo/db/data/node/0/properties',
                                'outgoing_typed_relationships' : 'http://foo/db/data/node/0/relationships/out/{-list|&|types}',
                                'incoming_relationships' : 'http://foo/db/data/node/0/relationships/in',
                                'extensions' : {
                                },
                                'create_relationship' : 'http://foo/db/data/node/0/relationships',
                                'paged_traverse' : 'http://foo/db/data/node/0/paged/traverse/{returnType}{?pageSize,leaseTime}',
                                'all_relationships' : 'http://foo/db/data/node/0/relationships/all',
                                'incoming_typed_relationships' : 'http://foo/db/data/node/0/relationships/in/{-list|&|types}'
                                }, 'HOSTS', 'foo', 44321 ], [ {
                                'outgoing_relationships' : 'http://foo/db/data/node/0/relationships/out',
                                'data' : {
                                    'Bar' : 'bar',
                                    'Baz' : 'baz'
                                },
                                'traverse' : 'http://foo/db/data/node/0/traverse/{returnType}',
                                'all_typed_relationships' : 'http://foo/db/data/node/0/relationships/all/{-list|&|types}',
                                'property' : 'http://foo/db/data/node/0/properties/{key}',
                                'self' : 'http://foo/db/data/node/2',
                                'properties' : 'http://foo/db/data/node/0/properties',
                                'outgoing_typed_relationships' : 'http://foo/db/data/node/0/relationships/out/{-list|&|types}',
                                'incoming_relationships' : 'http://foo/db/data/node/0/relationships/in',
                                'extensions' : {
                                },
                                'create_relationship' : 'http://foo/db/data/node/0/relationships',
                                'paged_traverse' : 'http://foo/db/data/node/0/paged/traverse/{returnType}{?pageSize,leaseTime}',
                                'all_relationships' : 'http://foo/db/data/node/0/relationships/all',
                                'incoming_typed_relationships' : 'http://foo/db/data/node/0/relationships/in/{-list|&|types}'
                                }, 'LIKES', 'bar', 44311 ], [ {
                                'outgoing_relationships' : 'http://foo/db/data/node/0/relationships/out',
                                'data' : {
                                    'Bar' : 'bar',
                                    'Baz' : 'baz'
                                },
                                'traverse' : 'http://foo/db/data/node/0/traverse/{returnType}',
                                'all_typed_relationships' : 'http://foo/db/data/node/0/relationships/all/{-list|&|types}',
                                'property' : 'http://foo/db/data/node/0/properties/{key}',
                                'self' : 'http://foo/db/data/node/12',
                                'properties' : 'http://foo/db/data/node/0/properties',
                                'outgoing_typed_relationships' : 'http://foo/db/data/node/0/relationships/out/{-list|&|types}',
                                'incoming_relationships' : 'http://foo/db/data/node/0/relationships/in',
                                'extensions' : {
                                },
                                'create_relationship' : 'http://foo/db/data/node/0/relationships',
                                'paged_traverse' : 'http://foo/db/data/node/0/paged/traverse/{returnType}{?pageSize,leaseTime}',
                                'all_relationships' : 'http://foo/db/data/node/0/relationships/all',
                                'incoming_typed_relationships' : 'http://foo/db/data/node/0/relationships/in/{-list|&|types}'
                                }, 'HOSTS', 'baz', 42586 ] ],
                                'columns' : [ 'Fooness', 'RelationshipType', 'Name', 'UniqueId' ]
                            }")
                }
            })
            {
                var graphClient = testHarness.CreateAndConnectGraphClient();

                //Act
                var results = graphClient.ExecuteGetCypherResults <ResultWithNodeDataObjectsDto>(cypherQuery);

                //Assert
                Assert.IsInstanceOf <IEnumerable <ResultWithNodeDataObjectsDto> >(results);

                var resultsArray = results.ToArray();
                Assert.AreEqual(3, resultsArray.Count());

                var firstResult = resultsArray[0];
                Assert.AreEqual("bar", firstResult.Fooness.Bar);
                Assert.AreEqual("baz", firstResult.Fooness.Baz);
                Assert.AreEqual("HOSTS", firstResult.RelationshipType);
                Assert.AreEqual("foo", firstResult.Name);
                Assert.AreEqual(44321, firstResult.UniqueId);

                var secondResult = resultsArray[1];
                Assert.AreEqual("bar", secondResult.Fooness.Bar);
                Assert.AreEqual("baz", secondResult.Fooness.Baz);
                Assert.AreEqual("LIKES", secondResult.RelationshipType);
                Assert.AreEqual("bar", secondResult.Name);
                Assert.AreEqual(44311, secondResult.UniqueId);

                var thirdResult = resultsArray[2];
                Assert.AreEqual("bar", thirdResult.Fooness.Bar);
                Assert.AreEqual("baz", thirdResult.Fooness.Baz);
                Assert.AreEqual("HOSTS", thirdResult.RelationshipType);
                Assert.AreEqual("baz", thirdResult.Name);
                Assert.AreEqual(42586, thirdResult.UniqueId);
            }
        }
Exemplo n.º 22
0
        // public static IStatementResult Run(this ITransaction transaction, CypherQuery query, IGraphClient gc)
        // {
        //     return transaction.Run(query.QueryText, query.ToNeo4jDriverParameters(gc));
        // }
        //
        // public static async Task<IResultCursor> RunAsync(this IAsyncSession session, CypherQuery query, IGraphClient gc)
        // {
        //     return await session.RunAsync(query.QueryText, query.ToNeo4jDriverParameters(gc)).ConfigureAwait(false);
        // }
        //
        // public static async Task<IResultCursor> RunAsync(this ITransaction session, CypherQuery query, IGraphClient gc)
        // {
        //     return await session.RunAsync(query.QueryText, query.ToNeo4jDriverParameters(gc)).ConfigureAwait(false);
        // }

        // ReSharper disable once InconsistentNaming
        public static Dictionary <string, object> ToNeo4jDriverParameters(this CypherQuery query, IGraphClient gc)
        {
            return(query.QueryParameters.ToDictionary(item => item.Key, item => Serialize(item.Value, gc.JsonConverters, gc)));
        }
Exemplo n.º 23
0
        public Task <BoltResponse> EnqueueTask(string commandDescription, BoltGraphClient graphClient, IExecutionPolicy policy, CypherQuery query)
        {
            var task = new Task <BoltResponse>(() =>
            {
                var result = BoltTransaction.DriverTransaction.Run(query, graphClient);

                var resp = new BoltResponse {
                    StatementResult = result
                };
                return(resp);
            }
                                               );

            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);
        }
Exemplo n.º 24
0
        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);

            CustomHeaders = query.CustomHeaders;
            var task = new Task <HttpResponseMessage>(() =>
                                                      Request.With(client.ExecutionConfiguration, query.CustomHeaders, query.MaxExecutionTime)
                                                      .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);
        }
Exemplo n.º 25
0
 public void Complete(CypherQuery query, Bookmark lastBookmark, int resultsCount, QueryStats stats)
 {
     // only parse the events when there's an event handler
     Complete(owner.OperationCompleted != null ? query.DebugQueryText : string.Empty, lastBookmark, resultsCount, null, query.CustomHeaders, identifier: query.Identifier, bookmarks: query.Bookmarks, stats: stats);
 }
 public static IStatementResult Run(this ITransaction session, CypherQuery query, IGraphClient gc)
 {
     return(session.Run(query.QueryText, query.ToNeo4jDriverParameters(gc)));
 }
Exemplo n.º 27
0
        /// <inheritdoc />
        async Task <IEnumerable <TResult> > IRawGraphClient.ExecuteGetCypherResultsAsync <TResult>(CypherQuery query)
        {
            if (Driver == null)
            {
                throw new InvalidOperationException("Can't execute cypher unless you have connected to the server.");
            }

            var            context = ExecutionContext.Begin(this);
            List <TResult> results;
            Bookmark       lastBookmark = null;
            QueryStats     stats        = null;

            async Task <QueryStats> GetQueryStats(IResultCursor resultCursor)
            {
                if (!query.IncludeQueryStats)
                {
                    return(null);
                }
                var summary = await resultCursor.ConsumeAsync().ConfigureAwait(false);

                stats = new QueryStats(summary.Counters);

                return(stats);
            }

            try
            {
                if (InTransaction)
                {
                    context.Database = Transaction.Database;
                    var result = await transactionManager.EnqueueCypherRequest($"The query was: {query.QueryText}", this, query).ConfigureAwait(false);

                    results = ParseResults <TResult>(await result.StatementResult.ToListAsync().ConfigureAwait(false), query);
                    if (query.IncludeQueryStats)
                    {
                        var summary = await result.StatementResult.ConsumeAsync().ConfigureAwait(false);

                        stats = new QueryStats(summary.Counters);
                    }
                }
                else
                {
                    var session = Driver.AsyncSession(ServerVersion, query.Database, query.IsWrite, query.Bookmarks);

                    async Task <List <IRecord> > Records(IAsyncTransaction asyncTransaction)
                    {
                        var cursor = await asyncTransaction.RunAsync(query, this).ConfigureAwait(false);

                        var output = await cursor.ToListAsync().ConfigureAwait(false);

                        stats = await GetQueryStats(cursor).ConfigureAwait(false);

                        return(output);
                    }

                    var result = query.IsWrite
                        ? await session.WriteTransactionAsync(Records).ConfigureAwait(false)
                        : await session.ReadTransactionAsync(Records).ConfigureAwait(false);

                    results = ParseResults <TResult>(result, query);



                    lastBookmark = session.LastBookmark;
                    await session.CloseAsync().ConfigureAwait(false);
                }
            }
            catch (AggregateException aggregateException)
            {
                context.Complete(query, lastBookmark, aggregateException.TryUnwrap(out var unwrappedException) ? unwrappedException : aggregateException);
                throw;
            }
            catch (Exception e)
            {
                context.Complete(query, lastBookmark, e);
                throw;
            }

            context.Complete(query, lastBookmark, results.Count, stats);
            return(results);
        }
        // ReSharper disable once InconsistentNaming
        public static Dictionary <string, object> ToNeo4jDriverParameters(this CypherQuery query, IGraphClient gc)
        {
            var output = new Dictionary <string, object>();

            foreach (var item in query.QueryParameters)
            {
                var type     = item.Value.GetType();
                var typeInfo = type.GetTypeInfo();

                if (typeInfo.IsClass && type != typeof(string))
                {
                    object itemToAdd;
                    if (typeInfo.ImplementedInterfaces.Contains(typeof(IEnumerable)))
                    {
                        if (typeInfo.IsArray)
                        {
                            itemToAdd = item.Value;
                        }
                        else if (typeInfo.IsGenericType && type.GenericTypeArguments.Length == 1)
                        {
                            var genericType     = type.GenericTypeArguments[0];
                            var genericTypeInfo = genericType.GetTypeInfo();
                            if (genericTypeInfo.IsValueType || genericType == typeof(string))
                            {
                                itemToAdd = item.Value;
                            }
                            else
                            {
                                itemToAdd = ConvertListToListOfDictionaries((IEnumerable)item.Value, gc);
                            }
                        }

                        else
                        {
                            itemToAdd = ConvertListToListOfDictionaries((IEnumerable)item.Value, gc);
                        }
                    }
                    else
                    {
                        var serialized = JsonConvert.SerializeObject(item.Value, Formatting.None, gc.JsonConverters.ToArray());
                        itemToAdd = JsonConvert.DeserializeObject <Dictionary <string, object> >(serialized, new JsonSerializerSettings {
                            DateParseHandling = DateParseHandling.None
                        });
                    }

                    output.Add(item.Key, itemToAdd);
                }
                else if (type == typeof(string) || typeInfo.IsPrimitive)
                {
                    output.Add(item.Key, item.Value);
                }
                else if (type == typeof(Guid))
                {
                    output.Add(item.Key, $"{item.Value}");
                }
                else
                {
                    output.Add(item.Key, JsonConvert.SerializeObject(item.Value));
                }
            }

            return(output);
        }
Exemplo n.º 29
0
 public static Task<IResultCursor> Run(this IAsyncSession session, CypherQuery query, IGraphClient gc)
 {
     return session.RunAsync(query.QueryText, query.ToNeo4jDriverParameters(gc));
 }
Exemplo n.º 30
0
 protected abstract Task <TResponse> RunQuery(TClient client, CypherQuery query, IExecutionPolicy policy, string commandDescription);