예제 #1
0
        public async Task InserirNoAsync(string nome, string anilha, string sexo, string nomePopular, string nascimento)
        {
            session = _driver.AsyncSession(o => o.WithDatabase("neo4j"));//Nome da database está nas propriedades como padrão

            string query = String.Empty;

            if (sexo != string.Empty)
            {
                query += ",Sexo:" + "$sexo";
            }
            if (nomePopular != string.Empty)
            {
                query += ",NomePopular:" + "$nomePopular";
            }
            if (nascimento != string.Empty)
            {
                query += ",Nascimento:" + "$nascimento";
            }

            try {
                if (anilha == string.Empty)
                {
                    cursor = await session.RunAsync("CREATE (p:Passaro{nome:$nome" + query + "})", new { nome, sexo, nomePopular, nascimento });//MERGE Impede cadastro de mesmo nome
                }
                else
                {
                    cursor = await session.RunAsync("CREATE (p:Passaro{nome:$nome, anilha:$anilha" + query + "})", new { nome, anilha, sexo, nomePopular, nascimento });
                }

                await cursor.ConsumeAsync();
            }
            finally {
                await session.CloseAsync();
            }
        }
예제 #2
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();
            }
        }
예제 #3
0
        public async void CreateActor()
        {
            // arrange
            IAsyncSession session = _neo4JResource.GetAsyncSession();

            try
            {
                // act
                var actor = new Actor("Keanu Reaves", 56);

                IDictionary <string, object> parameters =
                    new Neo4jParameters().WithEntity("newActor", actor);

                IResultCursor cursor = await session.RunAsync(
                    @"CREATE (actor:Actor $newActor) RETURN actor",
                    parameters);

                Actor createdActor = await cursor.MapSingleAsync <Actor>();

                await cursor.ConsumeAsync();

                // assert
                createdActor.MatchSnapshot();
            }
            finally
            {
                await session.CloseAsync();
            }
        }
    // ############
    // RETURN TWO LIST<STRING>
    // ############

    async void MultipleReturnsTest()
    {
        // Each IDriver instance maintains a pool of connections inside, as a result, it is recommended to only use one driver per application.
        // The driver is thread-safe, while the session or the transaction is not thread-safe.
        IDriver       driver  = GraphDatabase.Driver("neo4j://localhost:7687", AuthTokens.Basic("neo4j", "123456"));
        IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

        try
        {
            IResultCursor cursor = await session.RunAsync("MATCH (a:Person) RETURN a.name, a.born");

            // A record is accessible once it is received by the client. It is not needed for the whole result set to be received before it can be visited.
            // Each record can only be visited (a.k.a.consumed) once!
            // The recommended way to access these result records is to make use of methods provided by ResultCursorExtensions such as SingleAsync,
            // ToListAsync, and ForEachAsync.
            List <DataHolder> people = await cursor.ToListAsync(record => new DataHolder(record["a.name"].As <string>(), record["a.born"].As <string>()));

            await cursor.ConsumeAsync();

            foreach (var item in people)
            {
                Debug.Log(item.ToString());
            }
        }
        finally
        {
            await session.CloseAsync();
        }
        await driver.CloseAsync();
    }
    // ############
    // RETURN SINGLE NODE
    // ############

    async void SingleNodeLabelsTest()
    {
        // Each IDriver instance maintains a pool of connections inside, as a result, it is recommended to only use one driver per application.
        // The driver is thread-safe, while the session or the transaction is not thread-safe.
        IDriver       driver  = GraphDatabase.Driver("neo4j://localhost:7687", AuthTokens.Basic("neo4j", "123456"));
        IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

        try
        {
            IResultCursor cursor = await session.RunAsync("MATCH (a {name: 'Joel Silver'}) RETURN a");

            // The recommended way to access these result records is to make use of methods provided by ResultCursorExtensions such as SingleAsync,
            // ToListAsync, and ForEachAsync.
            INode person = await cursor.SingleAsync(record => record["a"].As <INode>());

            await cursor.ConsumeAsync();

            foreach (var item in person.Labels)
            {
                Debug.Log(item);
            }
        }
        finally
        {
            await session.CloseAsync();
        }
        await driver.CloseAsync();
    }
    // ############
    // RETURN SINGLE LIST<STRING>
    // ############

    async void SingleReturnTest()
    {
        // Each IDriver instance maintains a pool of connections inside, as a result, it is recommended to only use one driver per application.
        // The driver is thread-safe, while the session or the transaction is not thread-safe.
        IDriver       driver  = GraphDatabase.Driver("neo4j://localhost:7687", AuthTokens.Basic("neo4j", "123456"));
        IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

        try
        {
            IResultCursor cursor = await session.RunAsync("MATCH (a:Person) RETURN a.name as name");

            // The recommended way to access these result records is to make use of methods provided by ResultCursorExtensions such as SingleAsync,
            // ToListAsync, and ForEachAsync.
            List <string> people = await cursor.ToListAsync(record => record["name"].As <string>());

            await cursor.ConsumeAsync();

            Debug.Log(people.Count + " single returns");
        }
        finally
        {
            await session.CloseAsync();
        }
        await driver.CloseAsync();
    }
예제 #7
0
        private async Task mnu_ClickAsync(object sender, RoutedEventArgs e)
        {
            IDriver       driver  = GraphDatabase.Driver("neo4j://localhost:7687", AuthTokens.Basic("neo4j", "neo4j"));
            IAsyncSession session = driver.AsyncSession(o => o.WithDatabase("neo4j"));

            try
            {
                IResultCursor cursor = await session.RunAsync("CREATE (n) RETURN n");

                await cursor.ConsumeAsync();
            }
            finally
            {
                await session.CloseAsync();
            }

            await driver.CloseAsync();

            ///https://stackoverflow.com/questions/59581789/why-does-idriver-not-contain-a-definition-for-session-when-using-neo4j-in-c
            ///test

            /*[TestClass]
             * {
             *  [TestMethod]
             *  {
             *      System.Console.WriteLine();
             *  }
             * }*/
        }
예제 #8
0
        private static async Task CanAccessSummary(IResultCursor cursor)
        {
            // Summary is still saved
            var summary = await cursor.ConsumeAsync();

            summary.Query.Text.ToLower().Should().NotBeNullOrEmpty();
            summary.QueryType.Should().Be(QueryType.ReadOnly);
        }
예제 #9
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();
            }
        }
        /// <summary>
        /// Read each record in the result stream and apply the operation on each record.
        /// </summary>
        /// <param name="result">The result stream.</param>
        /// <param name="operation">The operation is carried out on each record.</param>
        /// <returns>The result summary after all records have been processed.</returns>
        public static async Task <IResultSummary> ForEachAsync(this IResultCursor result,
                                                               Action <IRecord> operation)
        {
            Throw.ArgumentNullException.IfNull(result, nameof(result));
            while (await result.FetchAsync().ConfigureAwait(false))
            {
                var record = result.Current;
                operation(record);
            }

            return(await result.ConsumeAsync().ConfigureAwait(false));
        }
예제 #11
0
        public async Task CriarUniqueAsync()
        {
            session = _driver.AsyncSession(o => o.WithDatabase("neo4j"));//Nome da database está nas propriedades como padrão

            try {
                cursor = await session.RunAsync("CREATE CONSTRAINT anilhaC ON (p:Passaro) ASSERT p.anilha IS UNIQUE");

                await cursor.ConsumeAsync();
            }
            finally {
                await session.CloseAsync();
            }
        }
예제 #12
0
        public async Task <IRequestExecutor> CreateSchema()
        {
            IAsyncSession session = GetAsyncSession();
            IResultCursor cursor  = await session.RunAsync(seedCypher);

            await cursor.ConsumeAsync();

            return(await new ServiceCollection()
                   .AddSingleton(Driver)
                   .AddGraphQL()
                   .AddQueryType()
                   .AddMovieTypes()
                   .Services
                   .BuildServiceProvider()
                   .GetRequiredService <IRequestExecutorResolver>()
                   .GetRequestExecutorAsync());
        }
예제 #13
0
        private async Task ExecuteCypher(string cypherQuery)
        {
            ExecuteQueryArgs e;
            var session = _driver.AsyncSession();

            try
            {
                if (_connected == false)
                {
                    var control = _customTaskPane.Control as ExecuteQuery;
                    ConnectDatabase(this, new ConnectDatabaseArgs {
                        ConnectionString = control.ConnectionString()
                    });
                }

                var worksheet = ((Worksheet)Application.ActiveSheet);

                try
                {
                    IResultCursor cursor = await session.RunAsync(cypherQuery);

                    var records = await cursor.ToListAsync();

                    LoadRowsFromRecords(records, worksheet);


                    var summary = await cursor.ConsumeAsync();

                    string summaryText = summary.ToString();

                    CurrentControl.SetMessage("Execution Summary :" + "\n\n" + summaryText);
                }
                finally
                {
                    await session.CloseAsync();
                }
            }
            catch (Neo4jException ex)
            {
                CurrentControl.SetMessage(ex.Message);
            }
            finally
            {
                await session.CloseAsync();
            }
        }
        private async Task DiscardUnconsumedResultAsync()
        {
            if (_result != null)
            {
                IResultCursor cursor = null;
                try
                {
                    cursor = await _result.ConfigureAwait(false);
                }
                catch (Exception)
                {
                    // ignored if the cursor failed to create
                }

                if (cursor != null)
                {
                    await cursor.ConsumeAsync().ConfigureAwait(false);
                }
            }
        }
        private async Task DiscardUnconsumed()
        {
            foreach (var result in _results)
            {
                IResultCursor cursor = null;
                try
                {
                    cursor = await result.ConfigureAwait(false);
                }
                catch (Exception)
                {
                    // ignore if cursor failed to create
                }

                if (cursor != null)
                {
                    await cursor.ConsumeAsync().ConfigureAwait(false);
                }
            }
        }
예제 #16
0
        private async void ExecuteCypher(object sender, ExecuteQueryArgs e)
        {
            var session = _driver.AsyncSession();

            try
            {
                if (_connected == false)
                {
                    var control = _customTaskPane.Control as ExecuteQuery;
                    ConnectDatabase(this, new ConnectDatabaseArgs {
                        ConnectionString = control.ConnectionString()
                    });
                }

                var worksheet = ((Worksheet)Application.ActiveSheet);

                try
                {
                    IResultCursor cursor = await session.RunAsync(e.Cypher);

                    var records = await cursor.ToListAsync();

                    var summary = await cursor.ConsumeAsync();

                    string message = summary.ToString();
                    CurrentControl.SetMessage(message);
                }
                finally
                {
                    await session.CloseAsync();
                }
            }
            catch (Neo4jException ex)
            {
                CurrentControl.SetMessage(ex.Message);
            }
            finally
            {
                await session.CloseAsync();
            }
        }
예제 #17
0
        public async Task <IRequestExecutor> CreateSchema()
        {
            IAsyncSession session = GetAsyncSession();
            IResultCursor cursor  = await session.RunAsync(seedCypher);

            await cursor.ConsumeAsync();

            return(await new ServiceCollection()
                   .AddSingleton(Driver)
                   .AddGraphQL()
                   .AddQueryType(d => d.Name("Query"))
                   .AddType <Queries>()
                   .AddNeo4JProjections()
                   .AddNeo4JFiltering()
                   .AddNeo4JSorting()
                   .UseDefaultPipeline()
                   .Services
                   .BuildServiceProvider()
                   .GetRequiredService <IRequestExecutorResolver>()
                   .GetRequestExecutorAsync());
        }
예제 #18
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();
            }
        }
        public async Task Run(ICommand[] commands, string databaseName, bool defaultDatabase)
        {
            IAsyncSession session = GetAsyncSession(databaseName, defaultDatabase);

            try
            {
                // transaction functions auto-retry
                //todo: configure retry? timeout? etc.

                LogRun("command(s)", databaseName, defaultDatabase);

                await session.WriteTransactionAsync(async tx =>
                {
                    foreach (ICommand command in commands)
                    {
                        IResultCursor result = await tx.RunAsync(command.Query);

                        var records       = await result.ToListAsync(r => r);
                        var resultSummary = await result.ConsumeAsync();

                        _logger.LogDebug("Query result available after: {ResultAvailableAfter}, consumed after: {ResultConsumedAfter}",
                                         resultSummary.ResultAvailableAfter, resultSummary.ResultConsumedAfter);

                        if (resultSummary.Notifications.Any())
                        {
                            _logger.LogWarning($"Query had notifications{Environment.NewLine}:{string.Join(Environment.NewLine, resultSummary.Notifications)}");
                        }

                        command.ValidateResults(records, resultSummary);
                    }
                });
            }
            finally
            {
                await session.CloseAsync();
            }
        }
예제 #20
0
        private static async Task CreateCommandAsync(string command)
        {
            IResultCursor cursor = await _session.RunAsync(command);

            await cursor.ConsumeAsync();
        }
예제 #21
0
 /// <summary>
 /// Calling this method will discard all remaining records to yield the summary
 /// </summary>
 public async Task <IResultSummary> GetResultSummaryAsync()
 {
     return(await _resultCursor.ConsumeAsync());
 }
예제 #22
0
        private async void CreateRelationships(object sender, SelectionArgs e)
        {
            if (_connected == false)
            {
                var control = _customTaskPane.Control as ExecuteQuery;
                ConnectDatabase(this, new ConnectDatabaseArgs {
                    ConnectionString = control.ConnectionString()
                });
            }
            var session = _driver.AsyncSession();

            try
            {
                var worksheet  = ((Worksheet)Application.ActiveSheet);
                var inputrange = e.SelectionRange;



                if (inputrange.Columns.Count <= 1)
                {
                    CurrentControl.SetMessage("Select 3 columns with nodes and relationship to create");
                    await session.CloseAsync();

                    return;
                }
                if (inputrange.Rows.Count <= 2)
                {
                    CurrentControl.SetMessage("Select 2 header rows and 1 data row");
                    await session.CloseAsync();

                    return;
                }

                string label1           = Convert.ToString(inputrange.Cells[1, 1].Value2);
                string label2           = Convert.ToString(inputrange.Cells[1, 2].Value2);
                string relationshiptype = Convert.ToString(inputrange.Cells[1, 3].Value2);

                if (label1.Length == 0 || label2.Length == 0 || relationshiptype.Length == 0)
                {
                    CurrentControl.SetMessage("Labels and relationship type must not be empty");
                    await session.CloseAsync();

                    return;
                }

                string[] properties = new string[inputrange.Columns.Count];
                for (int i = 1; i <= inputrange.Columns.Count; i++)
                {
                    try
                    {
                        properties[i - 1] = Convert.ToString(inputrange.Cells[2, i].Value2);
                    }
                    catch
                    {
                    }
                }

                for (int r = 3; r <= inputrange.Rows.Count; r++)
                {
                    var row   = inputrange.Rows[r];
                    var input = inputrange;

                    string cypher = "MATCH (a: {0}),(b: {1} ) WHERE a.`{2}` = '{3}' and b.`{4}` = '{5}' MERGE (a)-[r:`{6}`]->(b) {7}";


                    string relprop = "";
                    if (properties.Length > 2)
                    {
                        relprop = "SET r += { ";
                        bool addcoma = false;
                        for (int p = 2; p < properties.Length; p++)
                        {
                            string propvalue = Convert.ToString(inputrange.Cells[r, p].Value2);
                            if (properties[p].Length > 0 && propvalue.Length > 0)
                            {
                                string prop = "`{0}`:\"{1}\"";
                                prop = String.Format(prop, properties[p], propvalue);
                                if (addcoma)
                                {
                                    relprop += " , ";
                                }
                                addcoma  = true;
                                relprop += prop;
                            }
                        }
                        relprop += " }";
                        if (relprop.Length == "SET r += { ".Length)
                        {
                            relprop = "";
                        }
                    }


                    string formatedcypher = String.Format(
                        cypher,
                        label1,
                        label2,
                        properties[0],
                        inputrange.Cells[r, 1].Value2.ToString(),
                        properties[1],
                        inputrange.Cells[r, 2].Value2.ToString(),
                        relationshiptype, relprop);

                    try
                    {
                        IResultCursor cursor = await session.RunAsync(formatedcypher);

                        var records = await cursor.ToListAsync();

                        var summary = await cursor.ConsumeAsync();

                        if (r == inputrange.Rows.Count)
                        {
                            string message = summary.ToString();
                            CurrentControl.SetMessage(message);
                        }
                    }
                    catch (Exception ex)
                    {
                        CurrentControl.SetMessage(ex.Message);
                    }
                }

                await session.CloseAsync();
            }
            catch (Neo4jException ex)
            {
                CurrentControl.SetMessage(ex.Message);
            }
        }
 public IResultSummary Consume()
 {
     return(_executor.RunSync(() => _cursor.ConsumeAsync()));
 }
예제 #24
0
        private async void CreateNodes(object sender, SelectionArgs e)
        {
            var control = _customTaskPane.Control as ExecuteQuery;

            if (_connected == false)
            {
                ConnectDatabase(this, new ConnectDatabaseArgs {
                    ConnectionString = control.ConnectionString()
                });
            }
            var session = _driver.AsyncSession();

            try
            {
                var worksheet  = ((Worksheet)Application.ActiveSheet);
                var inputrange = e.SelectionRange;



                control.progress.Report(0);

                if (inputrange.Columns.Count <= 1)
                {
                    CurrentControl.SetMessage("Select more than 1 column");
                }

                string[] properties = new string[inputrange.Columns.Count];
                for (int i = 2; i <= inputrange.Columns.Count; i++)
                {
                    try
                    {
                        properties[i - 2] = Convert.ToString(inputrange.Cells[1, i].Value2);
                    }
                    catch
                    {
                        properties[i - 2] = "property" + (i - 1).ToString();
                    }
                }



                for (int r = 2; r <= inputrange.Rows.Count; r++)
                {
                    control.progress.Report(r / inputrange.Rows.Count * 100);
                    var row   = inputrange.Rows[r];
                    var label = "";
                    try
                    {
                        label = row.Cells[1, 1].Value2.ToString();
                    }
                    catch
                    {
                        label = "NewExcelNode";
                    }

                    string cypher = "MERGE (a: " + label + " { ";
                    int    i      = 2;
                    {
                        string propval = Convert.ToString(row.Cells[1, i].Value2);

                        if (properties[i - 2].Length > 0 && propval.Length > 0)
                        {
                            cypher += "`" + properties[i - 2] + "`" + ": \"" + propval + "\",";
                        }
                    }
                    cypher  = cypher.TrimEnd(',');
                    cypher += "})";



                    if (row.columns.count > 2)
                    {
                        cypher += " SET a += { ";
                        for (i = 3; i <= row.Columns.Count; i++)
                        {
                            string propval = Convert.ToString(row.Cells[1, i].Value2);

                            if (properties[i - 2] != null && propval != null)
                            {
                                if (properties[i - 2].Length > 0 && propval.Length > 0)
                                {
                                    cypher += "`" + properties[i - 2] + "`" + ": \"" + propval + "\",";
                                }
                            }
                        }
                        cypher  = cypher.TrimEnd(',');
                        cypher += "}";
                    }



                    try
                    {
                        IResultCursor cursor = await session.RunAsync(cypher);

                        var records = await cursor.ToListAsync();

                        var summary = await cursor.ConsumeAsync();

                        string message = summary.ToString();
                        if (r == inputrange.Rows.Count)
                        {
                            CurrentControl.SetMessage(message);
                        }
                    }
                    catch (Neo4jException ee)
                    {
                        CurrentControl.SetMessage(ee.Message);
                    }
                }
                await session.CloseAsync();
            }
            catch (Neo4jException ex)
            {
                CurrentControl.SetMessage(ex.Message);
            }
        }
예제 #25
0
        private async void UpdateActiveWorksheet(object sender, SelectionArgs e)
        {
            var control = _customTaskPane.Control as ExecuteQuery;

            if (_connected == false)
            {
                ConnectDatabase(this, new ConnectDatabaseArgs {
                    ConnectionString = control.ConnectionString()
                });
            }
            var session = _driver.AsyncSession();

            try
            {
                var worksheet  = ((Worksheet)Application.ActiveSheet);
                var inputrange = e.SelectionRange;
                inputrange = worksheet.UsedRange;
                int indexOfIdentifier = 0;

                control.progress.Report(0);

                if (inputrange.Columns.Count <= 1)
                {
                    CurrentControl.SetMessage("Select more than 1 column");
                }


                string[] properties = new string[inputrange.Columns.Count];
                for (int i = 0; i < inputrange.Columns.Count; i++)
                {
                    int excelIndex = i + 1;
                    try
                    {
                        string colName = Convert.ToString(inputrange.Cells[1, excelIndex].Value2);
                        properties[i] = colName;
                        string s = colName.ToLowerInvariant();
                        if (s == "uuid")
                        {
                            indexOfIdentifier = i;
                        }
                    }
                    catch
                    {
                        properties[i - 2] = "property" + (i - 1).ToString();
                    }
                }


                for (int r = 2; r <= inputrange.Rows.Count; r++)
                {
                    control.progress.Report(r / inputrange.Rows.Count * 100);
                    var row   = inputrange.Rows[r];
                    var label = "";
                    try
                    {
                        label = row.Cells[1, 1].Value2.ToString();
                        label = worksheet.Name;
                    }
                    catch
                    {
                        label = "NewExcelNode";
                    }

                    string cypher = "MERGE (a: " + label + " { ";

                    {
                        cypher += GetIdentifierPropertyValue(row, properties, indexOfIdentifier);
                    }
                    cypher  = cypher.TrimEnd(',');
                    cypher += "})";

                    // check if worksheet have 1 property column + 1 data column
                    if (row.columns.count > 1)
                    {
                        cypher += " SET a += { ";
                        for (int i = 0; i < row.Columns.Count; i++)
                        {
                            int excelIndex = i + 1;
                            // Skip first record as it is used in Merge identifier.
                            if (i == indexOfIdentifier)
                            {
                                continue;
                            }
                            string secondRecordValue = Convert.ToString(row.Cells[1, excelIndex].Value2);

                            if (properties[i] != null && secondRecordValue != null)
                            {
                                if (properties[i].Length > 0 && secondRecordValue.Length > 0)
                                {
                                    cypher += "`" + properties[i] + "`" + ": \"" + secondRecordValue + "\",";
                                }
                            }
                        }
                        cypher  = cypher.TrimEnd(',');
                        cypher += "}";
                    }



                    try
                    {
                        IResultCursor cursor = await session.RunAsync(cypher);

                        var records = await cursor.ToListAsync();

                        var summary = await cursor.ConsumeAsync();

                        string message = summary.ToString();
                        if (r == inputrange.Rows.Count)
                        {
                            CurrentControl.SetMessage(message);
                        }
                    }
                    catch (Neo4jException ee)
                    {
                        CurrentControl.SetMessage(ee.Message);
                    }
                }
                await session.CloseAsync();
            }
            catch (Neo4jException ex)
            {
                CurrentControl.SetMessage(ex.Message);
            }
        }