public static async Task <TReturn> MapSingleAsync <TReturn>(
     this IResultCursor resultCursor)
 {
     return((await resultCursor.SingleAsync().ConfigureAwait(false)).Map <TReturn>());
 }
 public static async Task <TReturn> MapSingleAsync <TValue1, TValue2, TValue3, TValue4, TValue5, TValue6, TValue7, TValue8, TValue9, TValue10, TValue11, TValue12, TValue13, TReturn>(
     this IResultCursor resultCursor,
     Func <TValue1, TValue2, TValue3, TValue4, TValue5, TValue6, TValue7, TValue8, TValue9, TValue10, TValue11, TValue12, TValue13, TReturn> mapFunc)
 {
     return((await resultCursor.SingleAsync().ConfigureAwait(false)).Map(mapFunc));
 }
 /// <summary>
 /// Return the only record in the result stream.
 /// </summary>
 /// <param name="result">The result stream</param>
 /// <returns>The only record in the result stream.</returns>
 /// <remarks>Throws <exception cref="InvalidOperationException"></exception>
 /// if the result contains more than one record or the result is empty.</remarks>
 public static Task <IRecord> SingleAsync(this IResultCursor result)
 {
     return(SingleAsync(result, record => record));
 }
Пример #4
0
 public async Task PopulateRecords(IResultCursor cursor)
 {
     await cursor.ForEachAsync(record => Records.Add(record)).ConfigureAwait(false);
 }
Пример #5
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);
            }
        }
Пример #6
0
        private static async Task CreateCommandAsync(string command)
        {
            IResultCursor cursor = await _session.RunAsync(command);

            await cursor.ConsumeAsync();
        }
Пример #7
0
 public RecordSet(IResultCursor cursor, BlockingExecutor executor)
 {
     _cursor   = cursor;
     _executor = executor;
 }
Пример #8
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);
            }
        }
Пример #9
0
 public static async Task <List <TReturn> > MapAsync <TReturn>(
     this IResultCursor resultCursor)
 {
     return(await resultCursor.MapAsync(
                record => record.Map <TReturn>()).ConfigureAwait(false));
 }
Пример #10
0
 /// <summary>
 ///     Gets a value from the <see cref="IResultCursor.Current" /> element. Throwing an exception if the
 ///     <paramref name="identifier" /> isn't there.
 /// </summary>
 /// <typeparam name="T">The <see cref="Type" /> to attempt to get the property as.</typeparam>
 /// <param name="cursor">The <see cref="IResultCursor" /> instance to pull the property from.</param>
 /// <param name="identifier">The name of the identifier to get.</param>
 /// <returns>The converted <typeparamref name="T" /> or <c>default</c></returns>
 /// <exception cref="NullReferenceException">
 ///     Thrown if the <paramref name="cursor" /> hasn't had
 ///     <see cref="IResultCursor.FetchAsync" /> called on it.
 /// </exception>
 public static T GetValueStrict <T>(this IResultCursor cursor, string identifier)
 {
     return(cursor.GetValueInternal <T>(identifier, true));
 }
Пример #11
0
        public async Task <IEnumerable <LiveDbObject <T> > > ReturnAsync()
        {
            internalQ.Append("WITH ");
            for (int i = 0; i < PathCount; i++)
            {
                if (i > 0)
                {
                    internalQ.Append(" + ");
                }
                internalQ.Append($"collect(p{i})");
            }
            internalQ.Append($" AS paths{Environment.NewLine}");

            internalQ.Append($"UNWIND paths AS ret{Environment.NewLine}");
            internalQ = internalQ.AppendLine("RETURN ret as json");

            using (IDriver driver = clientFactory())
            {
                Query         q            = new Query(internalQ.ToString());
                IResultCursor resultCursor = await driver.AsyncSession().RunAsync(q);

                List <IRecord> results = await resultCursor.ToListAsync();

                Dictionary <string, INeo4jNode> nodeHeap = new Dictionary <string, INeo4jNode>();
                var raw = results.SelectMany(x =>
                {
                    var h = x["json"].As <IPath>();

                    List <INeo4jNode> nodes = h.Nodes.Select(a =>
                    {
                        INeo4jNode parentInstance;
                        if (!nodeHeap.TryGetValue(a["Id"].ToString(), out parentInstance))
                        {
                            Type parentType = ReflectionCache.BuildType(a["__type__"].As <string>());
                            parentInstance  = Activator.CreateInstance(parentType) as INeo4jNode;

                            ReflectionCache.Type typeData = ReflectionCache.GetTypeData(parentType);
                            foreach (KeyValuePair <string, object> k in a.Properties)
                            {
                                if (typeData.props.TryGetValue(k.Key, out ReflectionCache.Property prop))
                                {
                                    prop.PushValue(parentInstance, DBOps.Neo4jDecode(k.Value, prop.info.PropertyType));
                                }
                            }

                            nodeHeap.Add(a["Id"].ToString(), parentInstance);
                        }
                        return(parentInstance);
                    }).ToList();

                    return(h.Relationships
                           .Select((x, i) => (nodes[i].Id, nodes[i + 1].Id, x.Type))
                           .Cast <(string parentID, string childID, string relationship)>());
                }).ToList();

                var withProps = raw.Select(x => (x.Item1, x.Item2,
                                                 ReflectionCache.GetTypeData(nodeHeap[x.Item1]).props
                                                 .Where(y =>
                                                        y.Key == x.Item3
                                                        ||
                                                        (
                                                            y.Value.neo4JAttributes.Where(x => x is DbNameAttribute).Any()
                                                            &&
                                                            y.Value.neo4JAttributes.Select(x => x as DbNameAttribute).Where(x => x != null).FirstOrDefault()?.Name
                                                            ==
                                                            x.Item3
                                                        )
                                                        )
                                                 .SingleOrDefault()
                                                 .Value
                                                 )).ToList();

                var groupDedupe = withProps.GroupBy(x => x.Item1 + x.Item2).Select(x => x.First()).GroupBy(x => (x.Value, x.Item1));

                foreach (var g in groupDedupe)
                {
                    if (!g.Key.Value.isCollection)
                    {
                        var v = g.Single();
                        v.Item3.PushValue(nodeHeap[v.Item1], nodeHeap[v.Item2]);
                    }
                    else
                    {
                        System.Type     t    = g.Key.Value.info.PropertyType.GetGenericArguments()[0];
                        System.Type     lstT = typeof(List <>).MakeGenericType(t);
                        ConstructorInfo cotr = lstT.GetConstructors().Where(x => x.GetParameters().Length == 0).Single();

                        Type       enu   = typeof(Enumerable);
                        MethodInfo selct = enu.GetMethods()
                                           .Where(x => x.Name == "Select")
                                           .OrderBy(x => x.GetParameters().Length)
                                           .First()
                                           .MakeGenericMethod(typeof(string), t);
                        MethodInfo toLst = enu.GetMethods()
                                           .Where(x => x.Name == "ToList")
                                           .OrderBy(x => x.GetParameters().Length)
                                           .First()
                                           .MakeGenericMethod(t);

                        Type ndhpTyp = nodeHeap.GetType();

                        ParameterExpression ndhp = Expression.Parameter(ndhpTyp, "ndhp");
                        ParameterExpression ky   = Expression.Parameter(typeof(string), "ky");
                        var selExpr = Expression.Lambda(
                            Expression.Convert(Expression.Property(ndhp, "Item", ky), t),
                            ky
                            );

                        var expr = Expression.Lambda(
                            Expression.Call(
                                null,
                                toLst,
                                Expression.Call(
                                    null,
                                    selct,
                                    Expression.Constant(g.Select(x => x.Item2)),
                                    selExpr
                                    )
                                ),
                            ndhp
                            );

                        object psh = expr.Compile().DynamicInvoke(nodeHeap);

                        g.Key.Item1.PushValue(nodeHeap[g.Key.Item2],
                                              psh);
                    }
                }

                var ret = nodeHeap
                          .Select(x => x.Value)
                          .Where(x => x is T)
                          .Cast <T>()
                          .Distinct()
                          .Select(x => LiveDbObject <T> .Build(x, clientFactory, LiveObjectMode.LiveWrite | LiveObjectMode.DeferedRead))
                          .ToArray();

                return(ret);
            }
        }
Пример #12
0
        public void SetupCypherRequestResponse(string request, IDictionary <string, object> cypherQueryQueryParameters, IResultCursor response)
        {
            MockSession.Setup(s => s.RunAsync(request, It.IsAny <IDictionary <string, object> >())).Returns(Task.FromResult(response));
            var mockTransaction = new Mock <IAsyncTransaction>();

            mockTransaction.Setup(s => s.RunAsync(request, It.IsAny <IDictionary <string, object> >())).Returns(Task.FromResult(response));

            MockSession.Setup(s => s.WriteTransactionAsync(It.IsAny <Func <IAsyncTransaction, Task <List <IRecord> > > >()))
            .Returns <Func <IAsyncTransaction, Task <List <IRecord> > > >(async param => await param(mockTransaction.Object));

            MockSession.Setup(s => s.ReadTransactionAsync(It.IsAny <Func <IAsyncTransaction, Task <List <IRecord> > > >()))
            .Returns <Func <IAsyncTransaction, Task <List <IRecord> > > >(async param => await param(mockTransaction.Object));

            MockSession
            .Setup(s => s.BeginTransactionAsync(It.IsAny <Action <TransactionConfigBuilder> >()))
            .Returns(Task.FromResult(mockTransaction.Object));
            MockSession
            .Setup(s => s.BeginTransactionAsync())
            .Returns(Task.FromResult(mockTransaction.Object));
        }
Пример #13
0
 public async Task <string> ProcessResults(IResultCursor cursor)
 {
     return(await ResultHandler(cursor));
 }