Пример #1
0
        public async Task <IResultSummary> Update <T>(string matchQuery, IDictionary <string, object> parameters, string matchQueryResultVariable, T obj)
            where T : class, new()
        {
            IResultSummary resultSummary = await RunQuery(engine.CreateSetNodeQuery <T>(matchQuery, parameters, matchQueryResultVariable, obj));

            return(resultSummary);
        }
        public void ClearTokens()
        {
            try
            {
                _logger.LogTrace("Querying for tokens to clear");

                var found = Int32.MaxValue;

                using (var serviceScope = _serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    using (ISession session = serviceScope.ServiceProvider.GetService <IdentityServerDriverProvider>().GetDriver().Session())
                    {
                        while (found >= _options.TokenCleanupBatchSize)
                        {
                            Node n = new Node(type: typeof(PersistedGrant));

                            IResultSummary summary = session.Run(
                                $"MATCH (p{n.Labels}) " +
                                $"WHERE p.{nameof(PersistedGrant.Expiration)}<$date " +
                                $"WITH p ORDER BY p.{nameof(PersistedGrant.Key)} " +
                                $"LIMIT $count " +
                                $"DETACH DELETE p",
                                new { date = DateTime.UtcNow, count = _options.TokenCleanupBatchSize }).Summary;

                            found = summary.Counters.NodesDeleted;
                            _logger.LogInformation("Cleared {tokenCount} tokens", found);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Exception clearing tokens: {exception}", ex.Message);
            }
        }
Пример #3
0
        public ProcessingResult Process(Resource resource)
        {
            var eventRecorder = new EventRecorder();
            this.Target = new StubTarget();

            var concordionBuilder = new ConcordionBuilder()
                .WithEvaluatorFactory(this.EvaluatorFactory)
                .WithSource(this.Source)
                .WithTarget(this.Target)
                .WithAssertEqualsListener(eventRecorder)
                .WithExceptionListener(eventRecorder);

            if (this.Fixture != null)
            {
                new ExtensionLoader(this.Configuration).AddExtensions(this.Fixture, concordionBuilder);
            }
            
            if (this.Extension != null)
            {
                this.Extension.AddTo(concordionBuilder);
            }

            var concordion = concordionBuilder.Build();

            try
            {
                IResultSummary resultSummary = concordion.Process(resource, this.Fixture);
                string xml = this.Target.GetWrittenString(resource);
                return new ProcessingResult(resultSummary, eventRecorder, xml);
            }
            catch (Exception e)
            {
                throw new Exception("Test rig failed to process specification", e);
            }
        }
Пример #4
0
        public async void TestUpdateNode()
        {
            var personGuid = Guid.NewGuid();
            var person     = new Person()
            {
                Age         = 50,
                DateOfBirth = DateTime.Now.AddYears(-50),
                Id          = personGuid,
                Name        = "neo",
                Salary      = 5400.77,
            };
            IDictionary <string, object> parameters = new Dictionary <string, object>()
            {
                { "Id", personGuid }
            };
            var            context         = new NeoContext(Driver);
            IResultSummary resultExecuting = await context.InsertNode <Person>(person);

            person.Age = 55;
            await context.Update <Person>("MATCH (p:Person { Id : $Id} )", parameters, "p", person);

            var resultPerson = await context.QueryDefault <Person>("MATCH (p:Person { Id : $Id} ) return p", parameters);

            Assert.Equal <Person>(person, resultPerson);
            await context.ExecuteQuery("MATCH (p:Person) DETACH DELETE p");
        }
Пример #5
0
        public async Task <IResultSummary> Insert(string cypherQuery, IDictionary <string, object> parameters)
        {
            parameters = engine.ParameterConverter(parameters);
            IResultSummary resultSummary = await RunQuery(new Query(cypherQuery, parameters));

            return(resultSummary);
        }
Пример #6
0
        public async Task <int> DropIndexAsync(string label, string propertyname)
        {
            string query = $"DROP INDEX ON :{label}({propertyname})";
            int    count = 0;

            using (ISession session = this._driver.Session())
            {
                try
                {
                    await session.ReadTransactionAsync(async (tx) =>
                    {
                        IStatementResultCursor reader = await tx.RunAsync(query);
                        await reader.ConsumeAsync();
                        IResultSummary summary = await reader.SummaryAsync();
                        count = summary.Counters.IndexesRemoved;
                    });
                }
                catch (Exception e)
                {
                    this._logger.LogError(e, $"Error dropping index for label {label} on property {propertyname}");
                }
                finally
                {
                    await session.CloseAsync();
                }
            }
            return(count);
        }
Пример #7
0
        public async Task ExecuteNonQuery(string cypherQuery, object queryParams = null)
        {
            IAsyncSession session = _driver.AsyncSession(o => o.WithDatabase(this._database));

            if (queryParams == null)
            {
                queryParams = new {};
            }

            try
            {
                _logger.LogDebug($"Executing query: {cypherQuery}");

                IResultCursor cursor = await session.RunAsync(cypherQuery, queryParams);

                IResultSummary result = await cursor.ConsumeAsync();

                _logger.LogTrace($"Query executed successfully.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error executing query. {ex.Message}");
                throw;
            }
            finally
            {
                await session.CloseAsync();
            }
        }
        public ExecuteHttpTriggerTests()
        {
            _request = new DefaultHttpRequest(new DefaultHttpContext());
            _request.Headers.Add("X-Forwarded-Host", "test.com");

            _executionContext = new ExecutionContext();

            _config = A.Fake <IOptionsMonitor <ServiceTaxonomyApiSettings> >();
            A.CallTo(() => _config.CurrentValue).Returns(new ServiceTaxonomyApiSettings
            {
                Function        = DefaultFunctionName,
                Neo4jUrl        = "bolt://localhost:11002",
                Neo4jUser       = "******",
                Neo4jPassword   = "******",
                Scheme          = "https://",
                ApplicationName = "ServiceTaxonomy"
            });

            _log = A.Fake <ILogger>();
            _httpRequestHelper = A.Fake <IHttpRequestHelper>();

            _neo4JHelper   = A.Fake <INeo4JHelper>();
            _fileHelper    = A.Fake <IFileHelper>();
            _resultSummary = A.Fake <IResultSummary>();

            A.CallTo(() => _neo4JHelper.GetResultSummaryAsync()).Returns(_resultSummary);

            const string query = "{\"query\": \"QUERY HERE\"}";

            A.CallTo(() => _fileHelper.ReadAllTextFromFileAsync($"\\CypherQueries\\{DefaultApiVersion}\\{DefaultFunctionName}.json")).Returns(query);

            _executeFunction = new Execute(_config, _httpRequestHelper, _neo4JHelper, _fileHelper);
        }
Пример #9
0
        public async void TestQueryMultiple()
        {
            var persons = new List <Person>()
            {
                new Person()
                {
                    Age         = 50,
                    DateOfBirth = DateTime.Now.AddYears(-50),
                    Id          = Guid.NewGuid(),
                    Name        = "neo",
                    Salary      = 5400.77,
                },
                new Person()
                {
                    Age         = 50,
                    DateOfBirth = DateTime.Now.AddYears(-50),
                    Id          = Guid.NewGuid(),
                    Name        = "neo",
                    Salary      = 5400.77,
                }
            };
            var            context         = new NeoContext(Driver);
            IResultSummary resultExecuting = await context.InsertNodes <Person>(persons);

            IEnumerable <Person> personsResult = await context.QueryMultiple <Person>("MATCH (p:Person) return p");

            await context.ExecuteQuery("MATCH (p:Person) DETACH DELETE p");
        }
Пример #10
0
        public async Task <int> CreateIndexAsync(NewIndex newIndex)
        {
            string query = $"CREATE INDEX ON :{newIndex.Label}({newIndex.Property})";
            int    count = 0;

            using (ISession session = this._driver.Session())
            {
                try
                {
                    await session.ReadTransactionAsync(async (tx) =>
                    {
                        IStatementResultCursor reader = await tx.RunAsync(query);
                        await reader.ConsumeAsync();
                        IResultSummary summary = await reader.SummaryAsync();
                        count = summary.Counters.IndexesAdded;
                    });
                }
                catch (Exception e)
                {
                    this._logger.LogError(e, $"Error creating index for label {newIndex.Label} on property {newIndex.Property}");
                }
                finally
                {
                    await session.CloseAsync();
                }
            }
            return(count);
        }
        public void ValidateResults(List <IRecord> records, IResultSummary resultSummary)
        {
            if (resultSummary.Counters.NodesDeleted != 1)
            {
                throw new CommandValidationException($"Expecting 1 node to be deleted, but {resultSummary.Counters.NodesDeleted} were actually deleted.");
            }

            //todo: check number of relationships deleted?
        }
        private Task <IResultSummary> GetSummaryAsync()
        {
            if (_summary == null && _summaryFunc != null)
            {
                _summary = _summaryFunc();
            }

            return(Task.FromResult(_summary));
        }
Пример #13
0
        public void CRUD_Node()
        {
            DriverProvider provider = Fixture.GetService <TestDriverProvider>();

            using (ISession session = provider.GetDriver().Session())
            {
                Symbol   s     = new Symbol();
                TestNode tnode = new TestNode()
                {
                    Id = 1
                };
                PrepareEntity(tnode);

                TestNode val = session.ExecuteQuery <TestNode>($"MATCH {new Node(s, tnode.GetType(), new { Id = 1 }.ToPropDictionary())} RETURN {s}").FirstOrDefault();
                Assert.Null(val);

                val = session.ExecuteQuery <TestNode>($"CREATE " +
                                                      $"{new Node(s, tnode.GetType(), (IDictionary<string, object>)tnode.Scope(new N4pper.ObjectExtensionsConfiguration(), q=>q.ToPropDictionary()))}" +
                                                      $" SET {s} :testlabel RETURN {s}").FirstOrDefault();
                Assert.NotNull(val);

                Assert.Equal(tnode.Id, val.Id);
                CheckEntityEquals(tnode, val);
                Assert.Null(val.ValuesObject);

                val = session.ExecuteQuery <TestNode>($"MATCH {new Node(s, tnode.GetType(), new { Id = 1 }.ToPropDictionary())} SET {new Set(s, new { Double = 1.2 }.ToPropDictionary())} RETURN {s}")
                      .FirstOrDefault();
                Assert.NotNull(val);
                Assert.Equal(1.2, val.Double);

                val = session.ExecuteQuery <TestNode>($"MATCH {new Node(s, tnode.GetType(), new { Id = 1 }.ToPropDictionary())} SET {s}+=$val RETURN {s}", new { val = new { EnumValue = TestEnum.C, Values = new List <string>()
                                                                                                                                                                             {
                                                                                                                                                                                 "aaa", "bbb", "ccc"
                                                                                                                                                                             } } })
                      .FirstOrDefault();
                Assert.NotNull(val);
                Assert.Equal(TestEnum.C, val.EnumValue);

                val = session.ExecuteQuery <TestNode>($"MATCH {new Node(s, tnode.GetType(), new { Id = 1 }.ToPropDictionary())} SET {s}+=$val RETURN {s}", new { val = new { EnumValue = TestEnum.C, Values = new List <string>()
                                                                                                                                                                             {
                                                                                                                                                                                 "aaa", "ccc"
                                                                                                                                                                             } } })
                      .FirstOrDefault();
                Assert.NotNull(val);
                Assert.Equal(new List <string>()
                {
                    "aaa", "ccc"
                }, val.Values);

                IResultSummary result = session.Execute($"MATCH {new Node(s, tnode.GetType(), new { Id = 1 }.ToPropDictionary())} DELETE {s}");
                Assert.Equal(1, result.Counters.NodesDeleted);

                val = session.ExecuteQuery <TestNode>($"MATCH {new Node(s, tnode.GetType(), new { Id = 1 }.ToPropDictionary())} RETURN {s}").FirstOrDefault();
                Assert.Null(val);
            }
        }
            protected override void ProcessSummary(IResultSummary summary)
            {
                if (summary == null)
                {
                    return;
                }

                _readQueriesByServer.AddOrUpdate(summary.Server.Address, new AtomicLong(1),
                                                 (key, value) => value.Increment());
            }
Пример #15
0
            protected override void ProcessSummary(IResultSummary summary)
            {
                if (summary == null)
                {
                    return;
                }

                summary.Server.Address.Should().Be(_expectedAddress);
                Interlocked.Increment(ref _readQueries);
            }
Пример #16
0
        public async Task ProcurarFamilia(string filho, string aniFilho, bool comAnilha) //Testar essa função
        {
            session = _driver.AsyncSession(o => o.WithDatabase("neo4j"));                //Nome da database está nas propriedades como padrão
            try {
                string optMatch;
                string matchf;
                if (comAnilha)
                {
                    matchf = "MATCH (f:Passaro{nome:$filho, anilha:$aniFilho})" +
                             "OPTIONAL MATCH (f)<-[:PAI]-(p1:Passaro)" +
                             "OPTIONAL MATCH (m1:Passaro)-[:MAE]->(f)";
                }
                else
                {
                    matchf = "MATCH (f:Passaro{nome:$filho})" +
                             "WHERE ID(f) = toInteger($aniFilho)" +
                             "OPTIONAL MATCH (f)<-[:PAI]-(p1:Passaro)" +
                             "OPTIONAL MATCH (m1:Passaro)-[:MAE]->(f)";
                }
                optMatch =
                    "optional match(m2:Passaro)-[:MAE]->(p1) < -[:PAI] - (p2: Passaro)" +
                    "optional match(m3:Passaro)-[:MAE]->(m1) < -[:PAI] - (p3: Passaro)" +
                    "optional match(m4:Passaro)-[:MAE]->(p2) < -[:PAI] - (p4: Passaro)" +
                    "optional match(m5:Passaro)-[:MAE]->(m2) < -[:PAI] - (p5: Passaro)" +
                    "optional match(m6:Passaro)-[:MAE]->(p3) < -[:PAI] - (p6: Passaro)" +
                    "optional match(m7:Passaro)-[:MAE]->(m3) < -[:PAI] - (p7: Passaro)" +
                    "OPTIONAL MATCH(m8:Passaro)-[:MAE]->(p4) < -[:PAI] - (p8: Passaro)" +
                    "OPTIONAL MATCH(m9:Passaro)-[:MAE]->(m4) < -[:PAI] - (p9: Passaro)" +
                    "OPTIONAL MATCH(m10:Passaro)-[:MAE]->(p5) < -[:PAI] - (p10: Passaro)" +
                    "OPTIONAL MATCH(m11:Passaro)-[:MAE]->(m5) < -[:PAI] - (p11: Passaro)" +
                    "OPTIONAL MATCH(m12:Passaro)-[:MAE]->(p6) < -[:PAI] - (p12: Passaro)" +
                    "OPTIONAL MATCH(m13:Passaro)-[:MAE]->(m6) < -[:PAI] - (p13: Passaro)" +
                    "OPTIONAL MATCH(m14:Passaro)-[:MAE]->(p7) < -[:PAI] - (p14: Passaro)" +
                    "OPTIONAL MATCH(m15:Passaro)-[:MAE]->(m7) < -[:PAI] - (p15: Passaro)" +
                    "return [f.nome, p1.nome, m1.nome, p2.nome, m2.nome, p3.nome, m3.nome, " +
                    "p4.nome, m4.nome, p5.nome, m5.nome, p6.nome, m6.nome, p7.nome, m7.nome," +
                    "p8.nome, m8.nome, p9.nome, m9.nome, p10.nome, m10.nome, p11.nome, m11.nome," +
                    "p12.nome, m12.nome, p13.nome, m13.nome, p14.nome, m14.nome, p15.nome, m15.nome] AS familia";

                cursor = await session.RunAsync(matchf + optMatch, new { filho, aniFilho });

                records = await cursor.ToListAsync();

                familia = new List <string>();
                //familia.Add(aniFilho);
                //familia.Add(filho);
                familia   = Records();
                resultado = await cursor.ConsumeAsync();
            }
            finally {
                await session.CloseAsync();
            }
        }
Пример #17
0
        /// <summary>
        /// Removes all grants of a give type for a given subject id and client id combination.
        /// </summary>
        /// <param name="subjectId">The subject identifier.</param>
        /// <param name="clientId">The client identifier.</param>
        /// <param name="type">The type.</param>
        /// <returns></returns>
        public async Task RemoveAllAsync(string subjectId, string clientId, string type)
        {
            using (ISession session = _context.GetDriver().Session())
            {
                Node c   = new Node(type: typeof(Client));
                Node n   = new Node(type: typeof(PersistedGrant));
                Rel  rel = new Rel(type: typeof(Relationships.Has));

                IResultSummary summary = await(await session.RunAsync(
                                                   $"MATCH (c{c.Labels} {{{nameof(Client.ClientId)}:${nameof(clientId)}}})" +
                                                   $"-{rel}->" +
                                                   $"(n{n.Labels} {{{nameof(PersistedGrant.ClientId)}:${nameof(clientId)},{nameof(PersistedGrant.SubjectId)}:${nameof(subjectId)},{nameof(PersistedGrant.Type)}:${nameof(type)}}}) " +
                                                   $"DETACH DELETE n"
                                                   , new { clientId, subjectId, type })).SummaryAsync();
            }
        }
Пример #18
0
        public async void TestInsertNodesWithRelation()
        {
            var person = new Person()
            {
                Age         = 50,
                DateOfBirth = DateTime.Now.AddYears(-50),
                Id          = Guid.NewGuid(),
                Name        = "neo",
                Salary      = 5400.77,
                Owns        = new List <Owns>()
                {
                    new Owns()
                    {
                        OwnedFrom = DateTime.Now.AddYears(-2),
                        OwnedTill = DateTime.Now.AddYears(-1),
                        House     = new House()
                        {
                            Address = "test address",
                            Age     = 150
                        }
                    }
                }
            };
            INeoContext    context         = new NeoContext(Driver);
            IResultSummary resultExecuting = await context.InsertNodeWithRelation <Person, Owns, House>(person, person.Owns.First(), person.Owns.First().House);

            Dictionary <Guid, Person> personContainer = new Dictionary <Guid, Person>();
            var resultPerson = await context.QueryDefaultIncludeable <Person, Owns, House>("MATCH (p:Person { Name: 'neo' })-[o:Owns]->(h:House) return p,o,h",
                                                                                           (p, o, h) =>
            {
                if (!personContainer.ContainsKey(p.Id))
                {
                    personContainer.Add(p.Id, p);
                    p.Owns = new List <Owns>();
                }
                personContainer[p.Id].Owns.Add(o);
                o.House = h;
                return(personContainer[p.Id]);
            }
                                                                                           );

            await context.ExecuteQuery("MATCH (n:Person { Name: 'neo' }) DETACH DELETE n");

            await context.ExecuteQuery("MATCH (p:House {Address: 'test address'}) DETACH DELETE p");

            Assert.Equal <Person>(person, resultPerson);
        }
Пример #19
0
        /// <summary>
        /// Removes the grant by key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        public async Task RemoveAsync(string key)
        {
            using (ISession session = _context.GetDriver().Session())
            {
                Node n = new Node(type: typeof(PersistedGrant));

                IResultSummary summary = await(await session.RunAsync(
                                                   $"MATCH (n{n.Labels} {{{nameof(PersistedGrant.Key)}:${nameof(key)}}}) " +
                                                   $"DETACH DELETE n"
                                                   , new { key })).SummaryAsync();

                if (summary.Counters.NodesDeleted == 0)
                {
                    _logger.LogDebug("no {persistedGrantKey} persisted grant found in database", key);
                }
            }
        }
Пример #20
0
        private void AddToTestResults(IResultSummary singleResult, IResultRecorder resultSummary)
        {
            if (resultSummary == null) return;

            if (singleResult.HasExceptions)
            {
                resultSummary.Record(Result.Exception);
            }
            else if (singleResult.HasFailures)
            {
                resultSummary.Record(Result.Failure);
            }
            else
            {
                resultSummary.Record(Result.Success);
            }
        }
Пример #21
0
        /// <summary>
        /// 创建node
        /// </summary>
        /// <param name="nodeType">node类型</param>
        /// <param name="id">id</param>
        /// <param name="vip">vip等级</param>
        /// <param name="ids">身份证</param>
        /// <param name="caree">名片</param>
        /// /// <param name="careerType">名片</param>
        /// <returns>bool 是否创建成功</returns>
        public bool CreateSingleNode(string nodeType, string id, string nickName, int vip, int identityAuth, int careerAuth, int careerType, DateTime registerAt, int status)
        {
            string query = string.Format("CREATE (n:{0} ", nodeType) + @"{id:$id,nickName:$nickName,vip:$vip,identityAuth:$identityAuth,careerAuth:$careerAuth,careerType:$careerType,registerAt:$registerAt,status:$status})";

            using (var session = _graphDatabase.Session(AccessMode.Write))
            {
                try
                {
                    var            result = session.WriteTransaction(tx => tx.Run(query, new { id = id.ToLower(), nickName, vip, identityAuth, careerAuth, careerType, registerAt, status }));
                    IResultSummary rs     = result.Summary;
                    return(rs.Counters.NodesCreated == 1);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Пример #22
0
        public async Task DefinirPaisAsync(string filho, string aniFilho, string pai, string aniPai, string mae, string aniMae, bool[] comAnilha)
        {
            session = _driver.AsyncSession(o => o.WithDatabase("neo4j"));//Nome da database está nas propriedades como padrão

            try {
                if (!comAnilha.All(anilhas => anilhas == true))  //Expressão Lambda (entrada) => (corpo/condição)
                {
                    string matchf = " MATCH(f: Passaro { nome: $filho, anilha:$aniFilho})";
                    string matchp = " MATCH(p: Passaro { nome: $pai, anilha:$aniPai})";
                    string matchm = " MATCH(m:Passaro  { nome: $mae, anilha:$aniMae})";
                    string where = " WHERE NOT (:Passaro)-[:PAI]->(f)<-[:MAE]-(:Passaro)";
                    string merge = " MERGE (p)-[:PAI]->(f)<-[:MAE]-(m)";

                    if (!comAnilha[0])
                    {
                        matchf = "MATCH (f:Passaro {nome: $filho})";
                        where += " and ID(f) = toInteger($aniFilho)";
                    }
                    if (!comAnilha[1])
                    {
                        matchp = "MATCH (p:Passaro {nome: $pai})";
                        where += " and ID(p) = toInteger($aniPai)";
                    }
                    if (!comAnilha[2])
                    {
                        matchm = "MATCH (m:Passaro {nome: $mae})";
                        where += " and ID(m) = toInteger($aniMae)";
                    }
                    cursor = await session.RunAsync(matchf + matchp + matchm + where + merge, new { filho, aniFilho, pai, aniPai, mae, aniMae });
                }
                else
                {
                    cursor = await session.RunAsync("MATCH (f:Passaro {nome: $filho, anilha:$aniFilho})" +
                                                    "MATCH (p:Passaro {nome: $pai, anilha:$aniPai})" +
                                                    "MATCH (m:Passaro {nome: $mae, anilha:$aniMae})" +
                                                    "WHERE NOT (:Passaro)-[:PAI]->(f)<-[:MAE]-(:Passaro)" +
                                                    "MERGE (p)-[:PAI]->(f)<-[:MAE]-(m)", new { filho, aniFilho, pai, aniPai, mae, aniMae });
                }
                resultado = await cursor.ConsumeAsync();
            }
            finally {
                await session.CloseAsync();
            }
        }
Пример #23
0
        private TestResult NUnitTestResult(IResultSummary concordionResult)
        {
            var testResult = new TestResult(this);

            if (concordionResult.HasExceptions)
            {
                testResult.Error(new NUnitException("Exception in Concordion test: please see Concordion test reports"));
            }
            else if (concordionResult.HasFailures)
            {
                testResult.Failure("Concordion Test Failures: " + concordionResult.FailureCount,
                                   "for stack trace, please see Concordion test reports");
            } else
            {
                testResult.Success();
            }

            return testResult;
        }
Пример #24
0
        public void ResultSummaryQueryProfile()
        {
            var driver  = GraphDatabase.Driver(_serverEndPoint, _authToken);
            var session = driver.Session();

            //tag::result-summary-query-profile[]
            var result = session.Run("PROFILE MATCH (p:Person {name: {name}}) RETURN id(p)",
                                     new Dictionary <string, object> {
                { "name", "Arthur" }
            });

            IResultSummary summary = result.Consume();

            Output.WriteLine(summary.StatementType.ToString());
            Output.WriteLine(summary.Profile.ToString());
            //end::result-summary-query-profile[]

            driver.Dispose();
        }
Пример #25
0
        public bool CreateSingleNode(string nodeType, UserInfo userInfo)
        {
            string query = string.Format("CREATE (n:{0} ", nodeType) + @"{id: $userID,nickName:$NickName,vip:$Vip,identityAuth:$IdentityAuth,careerAuth:$CareerAuth,careerType:$CareerType,registerAt:$RegisterAt})";

            using (var session = _graphDatabase.Session(AccessMode.Write))
            {
                try
                {
                    var            userID = userInfo.UserId.ToString();
                    var            result = session.WriteTransaction(tx => tx.Run(query, new { userID, userInfo.NickName, userInfo.Vip, userInfo.IdentityAuth, userInfo.CareerAuth, userInfo.CareerType, userInfo.RegisterAt }));
                    IResultSummary rs     = result.Summary;
                    return(rs.Counters.NodesCreated == 1);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Пример #26
0
        public void ResultSummaryQueryProfile()
        {
            var driver  = GraphDatabase.Driver("bolt://localhost:7687");
            var session = driver.Session();

            //tag::result-summary-query-profile[]
            var result = session.Run("PROFILE MATCH (p:Person { name: {name} }) RETURN id(p)",
                                     new Dictionary <string, object> {
                { "name", "The One" }
            });

            IResultSummary summary = result.Summary;

            output.WriteLine(summary.StatementType.ToString());
            output.WriteLine(summary.Profile.ToString());
            //end::result-summary-query-profile[]

            driver.Dispose();
        }
Пример #27
0
        public async void TestInsertQuery()
        {
            var person = new Person()
            {
                Age         = 50,
                DateOfBirth = DateTime.Now.AddYears(-50),
                Id          = Guid.NewGuid(),
                Name        = "neo",
                Salary      = 5400.77,
            };
            var            context         = new NeoContext(Driver);
            IResultSummary resultExecuting = await context.InsertNode <Person>(person);

            var resultPerson = await context.QueryDefault <Person>("MATCH (p:Person) RETURN p");

            Assert.True(resultExecuting.QueryType == Neo4j.Driver.QueryType.WriteOnly);
            Assert.Equal <Person>(person, resultPerson);
            await context.ExecuteQuery("MATCH (p:Person { Name : 'neo' }) DETACH DELETE p");
        }
Пример #28
0
        private TestResult NUnitTestResult(IResultSummary concordionResult)
        {
            var testResult = new TestResult(this);

            testResult.AssertCount = (int)concordionResult.SuccessCount + (int)concordionResult.FailureCount;
            if (!(concordionResult.HasFailures || concordionResult.HasExceptions))
            {
                testResult.Success();
            }
            else if (concordionResult.HasFailures)
            {
                testResult.Failure("Concordion Test Failures: " + concordionResult.FailureCount,
                                   "for stack trace, please see Concordion test reports");
            }
            else if (concordionResult.HasExceptions)
            {
                testResult.Error(new NUnitException("Exception in Concordion test: please see Concordion test reports"));
            }
            return(testResult);
        }
Пример #29
0
        private void AddToTestResults(IResultSummary singleResult, IResultRecorder resultSummary)
        {
            if (resultSummary == null)
            {
                return;
            }

            if (singleResult.HasExceptions)
            {
                resultSummary.AddResultDetails(singleResult.ErrorDetails);
            }
            else if (singleResult.HasFailures)
            {
                resultSummary.AddResultDetails(singleResult.FailureDetails);
            }
            else
            {
                resultSummary.Success();
            }
        }
Пример #30
0
        /// <summary>
        /// Stores the asynchronous.
        /// </summary>
        /// <param name="token">The token.</param>
        /// <returns></returns>
        public async Task StoreAsync(PersistedGrant token)
        {
            using (ISession session = _context.GetDriver().Session())
            {
                Node cli = new Node(type: typeof(Client));
                Node n   = new Node(type: typeof(PersistedGrant));
                Rel  rel = new Rel(type: typeof(Relationships.Has));

                IResultSummary summary = await(await session.RunAsync(
                                                   $"MATCH (c{cli.Labels} {{{nameof(Client.ClientId)}:$value.{nameof(token.ClientId)}}}) " +
                                                   $"MERGE (c)-{rel}->(n{n.Labels} {{{nameof(PersistedGrant.Key)}:$value.{nameof(token.Key)}}}) " +
                                                   $"ON CREATE SET n+=$value, n.{nameof(IGraphEntity.EntityId)}=id(n), n :{typeof(Neo4jPersistedGrant).Name} " +
                                                   $"ON MATCH SET n+=$value, n.{nameof(IGraphEntity.EntityId)}=id(n) ", new { value = token })).SummaryAsync();

                if (!summary.Counters.ContainsUpdates && summary.Counters.NodesCreated == 0)
                {
                    _logger.LogWarning("No node have been created or updated.");
                }
            }
        }
Пример #31
0
        public async Task <List <IRecord> > ProcurarPais(string nome, string anilha, bool comAnilha)
        {
            session = _driver.AsyncSession(o => o.WithDatabase("neo4j"));//Nome da database está nas propriedades como padrão

            try {
                if (!comAnilha)
                {
                    if (anilha != String.Empty)
                    {
                        cursor = await session.RunAsync("MATCH (f:Passaro{nome:$nome})" +
                                                        "WHERE ID(f) = toInteger($anilha) " +
                                                        "OPTIONAL MATCH (m1:Passaro)-[:MAE]->(f)" +
                                                        "OPTIONAL MATCH (f)<-[:PAI]-(p1:Passaro)" +
                                                        "RETURN f,[f.nome] AS Nomes,[m1.nome] AS Maes,[p1.nome] AS Pais, [ID(f)] AS Ids", new { nome, anilha });
                    }
                    else
                    {
                        cursor = await session.RunAsync("MATCH (f:Passaro{nome:$nome})" +
                                                        "OPTIONAL MATCH (m1:Passaro)-[:MAE]->(f)" +
                                                        "OPTIONAL MATCH (f)<-[:PAI]-(p1:Passaro)" +
                                                        "RETURN f,[f.nome] AS Nomes,[m1.nome] AS Maes,[p1.nome] AS Pais, [ID(f)] AS Ids", new { nome });
                    }
                }
                else
                {
                    cursor = await session.RunAsync("MATCH (f:Passaro {nome: $nome, anilha:$anilha})" +
                                                    "OPTIONAL MATCH (m1:Passaro)-[:MAE]->(f)" +
                                                    "OPTIONAL MATCH (f)<-[:PAI]-(p1:Passaro)" +
                                                    "RETURN f,[f.nome] AS Nomes,[m1.nome] AS Maes,[p1.nome] AS Pais, [ID(f)] AS Ids", new { nome, anilha });
                }

                var lista = await cursor.ToListAsync();

                resultado = await cursor.ConsumeAsync();

                return(lista);
            }
            finally {
                await session.CloseAsync();
            }
        }
Пример #32
0
        //TODO: Mudar cor das labels na frente do cartão pelo usuário
        //TODO: Menu para atualizar campos de passarinho
        //TODO: Pontos que precisam estão marcados com indicadores de bandeira branca
        //TODO: Clicar em pesquisar sem sair nomeFilhoF faz com que listnomesF == null
        //TODO: Criar menu para cadastrar em árvore
        //TODO: Atualizar buttonPesquisa para buttonImpressão
        public async Task <List <IRecord> > ProcurarFilhos(string nome)
        {
            session = _driver.AsyncSession(o => o.WithDatabase("neo4j"));//Nome da database está nas propriedades como padrão

            try {
                cursor = await session.RunAsync("MATCH (p:Passaro {nome: $nome})" +
                                                "OPTIONAL MATCH (p)-[:PAI|MAE]->(f:Passaro)" +
                                                "RETURN [p.nome] AS Nomes, [ID(p)] AS Ids,[f.nome] AS Filhos, " +
                                                "[p.anilha] AS Anilhas, [p.Sexo] AS Sexos, [p.NomePopular] AS NomesPopulares, " +
                                                "[p.Nascimento] AS Nascimentos ", new { nome });

                var lista = await cursor.ToListAsync();

                resultado = await cursor.ConsumeAsync();

                return(lista);
            }
            finally {
                await session.CloseAsync();
            }
        }
Пример #33
0
        private TestResult NUnitTestResult(IResultSummary concordionResult, string resultPath)
        {
            var testResult = new TestResult(this);

            if (concordionResult.HasExceptions)
            {
                var errorDetails = concordionResult.ErrorDetails.First();
                testResult.Error(errorDetails.Exception);
                testResult.SetResult(testResult.ResultState,
                                     resultPath + Environment.NewLine + testResult.Message,
                                     testResult.StackTrace);
            }
            else if (concordionResult.HasFailures)
            {
                var failureDetails = concordionResult.FailureDetails.First();
                testResult.Failure(resultPath + Environment.NewLine + failureDetails.Message, failureDetails.StackTrace);
            } else
            {
                testResult.Success(resultPath);
            }

            return testResult;
        }
Пример #34
0
        private void AddToTestResults(IResultSummary singleResult, IResultRecorder resultSummary)
        {
            if (resultSummary == null) return;

            if (singleResult.HasExceptions)
            {
                resultSummary.AddResultDetails(singleResult.ErrorDetails);
            }
            else if (singleResult.HasFailures)
            {
                resultSummary.AddResultDetails(singleResult.FailureDetails);
            }
            else
            {
                resultSummary.Success();
            }
        }
 public ProcessingResult(IResultSummary resultSummary, EventRecorder eventRecorder, string documentXML) 
 {
     this.resultSummary = resultSummary;
     this.eventRecorder = eventRecorder;
     this.documentXML = documentXML;
 }