public static T Map <T>(this IStatementResult statementResult) where T : new()
        {
            var recordValue = statementResult?.FirstOrDefault()?[0];

            if (recordValue == null)
            {
                return(default);
Exemplo n.º 2
0
        public BasicNodeModel GetNodeAndRelationships(Guid id)
        {
            BasicNodeModel node = null;

            using (ISession session = driver.Session())
            {
                session.ReadTransaction(action =>
                {
                    IStatementResult statementResult = action.Run(kMatchNodeAndRelationshipsQuery, new Dictionary <string, object> {
                        { "id", id.ToString() }
                    });
                    // Get the relationships
                    foreach (IRecord record in statementResult)
                    {
                        if (node == null)
                        {
                            node = BasicNodeModel.FromINode(record[0].As <INode>());
                        }
                        node.AddRelationship(record["r"].As <IRelationship>(), record["e"].As <INode>());
                    }
                });
            }

            return(node);
        }
Exemplo n.º 3
0
        private object ParseDomainRelationships(IStatementResult result)
        {
            var nodes         = new List <NodeResult>();
            var relationships = new List <object>();
            int i             = 0;

            foreach (var record in result)
            {
                var target = i;
                nodes.Add(new NodeResult {
                    title = record["d"].As <string>(), label = "domain"
                });
                i += 1;

                var ips = record["ips"].As <List <string> >();
                foreach (var ip in ips)
                {
                    var source = nodes.FindIndex(c => c.title == ip);
                    if (source == -1)
                    {
                        nodes.Add(new NodeResult {
                            title = ip, label = "ip"
                        });
                        source = i;
                        i     += 1;
                    }
                    relationships.Add(new { source, target });
                }
            }

            return(new { nodes, links = relationships });
        }
        public void SetResult(IStatementResult result)
        {
            ThrowIfTerminated();

            Result    = result;
            HasResult = true;
        }
Exemplo n.º 5
0
        public bool DropRelationshipBetweenTwoNodes(
            string uuidIncoming,
            string uuidOutgoing,
            RelationshipAttribute relationshipAttribute)
        {
            if (string.IsNullOrWhiteSpace(uuidIncoming))
            {
                throw new ArgumentNullException("uuidIncoming");
            }

            if (string.IsNullOrWhiteSpace(uuidOutgoing))
            {
                throw new ArgumentNullException("uuidOutgoing");
            }

            if (relationshipAttribute == null)
            {
                throw new ArgumentNullException("relationshipAttribute");
            }

            var query = new StringFormatter(QueryTemplates.TEMPLATE_DROP_RELATIONSHIPBETWEENTWONODES);

            query.Add("@uuidIncoming", uuidIncoming);
            query.Add("@uuidOutgoing", uuidOutgoing);
            query.Add("@fromPartDirection", relationshipAttribute.Direction == DIRECTION.INCOMING ? "<-" : "-");
            query.Add("@toPartDirection", relationshipAttribute.Direction == DIRECTION.INCOMING ? "-" : "->");
            query.Add("@relationshipName", relationshipAttribute.Name);

            IStatementResult result = ExecuteQuery(query.ToString());

            return(result.Summary.Counters.RelationshipsDeleted > 0);
        }
Exemplo n.º 6
0
        public T Update <T>(
            T entity,
            string uuid,
            bool fetchResult = false) where T : EntityBase, new()
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            if (string.IsNullOrWhiteSpace(uuid))
            {
                throw new ArgumentNullException("uuid");
            }

            //entity.uuid = uuid;

            dynamic properties = entity.AsUpdateClause(TAG);
            dynamic clause     = properties.clause;
            IDictionary <string, object> parameters = properties.parameters;

            var query = new StringFormatter(QueryTemplates.TEMPLATE_UPDATE);

            query.Add("@label", entity.Label);
            query.Add("@Uuid", uuid);
            query.Add("@clause", clause);
            query.Add("@return", fetchResult ? string.Format("RETURN {0}", TAG) : string.Empty);

            IStatementResult result = ExecuteQuery(query.ToString(), parameters);

            return(result.Map <T>());
        }
Exemplo n.º 7
0
        public Actor(string name)
        {
            var driver  = GraphDatabase.Driver("bolt://localhost:7687", AuthTokens.Basic("neo4j", "root"));
            var session = driver.Session();

            string statement = "MATCH(p:Person{name:'" + name + "'}) return p";

            IStatementResult result = session.Run(statement);

            INode  node = null;
            string nameOut;
            string lastnameOut;
            int    bornOut;

            foreach (var record in result)
            {
                node        = record["p"].As <INode>();
                nameOut     = node["name"].As <string>();
                lastnameOut = node["lastname"].As <string>();
                bornOut     = node["born"].As <int>();

                this.name     = nameOut;
                this.lastname = lastnameOut;
                this.born     = bornOut;
            }
        }
Exemplo n.º 8
0
        public void getActorsOfMovie(string title)
        {
            var driver  = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("neo4j", "root"));
            var session = driver.Session();

            string statement = "MATCH(m:Movie{title:'" + title + "'})<-[:ACTED_IN]-(p:Person) return p";

            IStatementResult result = session.Run(statement);

            INode  node = null;
            string name;
            string nachname;
            int    born;

            Console.WriteLine("The following actors play in " + title + " : ");
            foreach (var record in result)
            {
                node     = record["p"].As <INode>();
                name     = node["name"].As <string>();
                nachname = node["lastname"].As <string>();
                born     = node["born"].As <int>();

                Console.WriteLine(name + " " + nachname + ", " + born);
            }
        }
Exemplo n.º 9
0
        public static void Run()
        {
            using (var driver = GraphDatabase.Driver("bolt://localhost:7687"))
            {
                using (var session = driver.Session())
                {
                    using (var tx = session.BeginTransaction()) {
                        IStatementResult results = tx.Run("MATCH (m:Movie) RETURN m");
                        foreach (IRecord result in results)
                        {
                            var node     = result["m"].As <INode>();
                            var title    = node.Properties["title"]?.As <string>();
                            var released = node.Properties["released"]?.As <int>();
                            var tagline  = node.Properties.ContainsKey("tagline")
                                ? node.Properties["tagline"]?.As <string>()
                                : "No Tagline";

                            var movie = new Movie
                            {
                                Title    = title,
                                Released = released ?? -1,
                                Tagline  = tagline
                            };

                            Console.WriteLine(movie);
                        }
                    }
                }
            }
        }
Exemplo n.º 10
0
        public ResultWrapper getGraphWithoutDest(String src, String rl)
        {
            List <IRecord> list  = new List <IRecord>();
            String         query = "";

            using (var session = _driver.Session())
            {
                using (var tx = session.BeginTransaction())
                {
                    if (rl == "All")
                    {
                        query = (@"match(n {objectEntity: '" + src + "'" + "})-[r]-(v) return n,r,v");
                    }
                    else
                    {
                        query = (@"match(n {objectEntity: '" + src + "'" + "})-[r:" + rl + "]-(v) return n,r,v");
                    }
                    IStatementResult results = tx.Run(query);
                    foreach (IRecord result in results)
                    {
                        list.Add(result);
                    }
                    return(new ResultWrapper(list, query));
                }
            }
        }
Exemplo n.º 11
0
        public static int MergeUpdates(IEnumerable <object> updates, IDriver driver, string scanid)
        {
            Dictionary <string, object> scanprops = new Dictionary <string, object>();

            scanprops.Add("scanid", scanid);
            scanprops.Add("updates", updates);

            string query = "UNWIND $updates as update " +
                           "MERGE (n:" + Types.WUUpdate + " { id: update.ID }) " +
                           "SET n.name = update.Name " +
                           "SET n.IsDeclined = update.IsDeclined " +
                           "SET n.IsSuperseded = update.IsSuperseded " +
                           "SET n.UpdateType = update.UpdateType " +
                           "SET n.Description = update.Description " +
                           "SET n.IsDeclined = update.IsDeclined " +
                           "SET n.AdditionalInformation = update.AdditionalInformationUrls " +
                           "SET n.CreationDate = update.CreationDate " +
                           "SET n.KB = update.KB " +
                           "SET n.Classification = update.Classification " +
                           "SET n.Products = update.Products " +
                           "SET n.layout = 'tree' " +
                           "SET n.lastscan = $scanid " +
                           "RETURN n ";

            using (ISession session = driver.Session())
            {
                IStatementResult result = session.WriteTransaction(tx => tx.Run(query, scanprops));
                return(result.Summary.Counters.NodesCreated);
            }
        }
Exemplo n.º 12
0
 private IList <Position> runCypher(string script)
 {
     using (var session = _driver.Session())
     {
         IList <Position> greeting = session.WriteTransaction(tx =>
         {
             IStatementResult result = tx.Run(script);
             IList <Position> ret    = new List <Position>();
             foreach (IRecord value in result)
             {
                 var n = value["n"].As <INode>();
                 var r = new Position
                 {
                     PositionNum = (string)n["PositionNum"],
                     WorkerCd    = (string)n["WorkerCd"]
                 };
                 if (n.Properties.Keys.Contains("PersonnelNum"))
                 {
                     r.PersonnelNum = (string)n["PersonnelNum"];
                 }
                 ret.Add(r);
             }
             return(ret);
         });
         return(greeting);
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Generates a single row of products for the tree, given the list of parent product ids
        /// </summary>
        /// <param name="parentProductIdentifiers">the list of parent products for which a number of child products has to be generated</param>
        /// <param name="breadthPerLevel">the number of child products that have to be generated per parent product</param>
        /// <returns>a list of the id's of the child products that have been created</returns>
        private List <int> GenerateProductRowAndRelations(int[] parentProductIdentifiers, int breadthPerLevel)
        {
            List <int> childProductsCreated = new List <int>();

            for (int i = 0; i < parentProductIdentifiers.Length; i++)
            {
                for (int j = 0; j < breadthPerLevel; j++)
                {
                    int childProductId;
                    // first insert the product
                    using (ISession session = connector.Connection.Session())
                    {
                        // string statement = "CREATE (n:Product { name: 'Product #c" + (chainId + 1) + "-p" + (i + 1) + "-p" + (j + 1) + "' }) RETURN ID(n) AS id";
                        string           statement = InsertProduct(false, parentProductIdentifiers[i] * 2 + j);
                        IStatementResult res       = session.WriteTransaction(tx => tx.Run(statement));
                        IRecord          record    = res.Peek();
                        childProductId = record["id"].As <int>();
                    }
                    // add it to the products created list
                    childProductsCreated.Add(childProductId);

                    // then create the relation for the product hierarchy
                    using (ISession session = connector.Connection.Session())
                    {
                        string statement = "MATCH (p:Product), (c:Product)" +
                                           " WHERE ID(p) = " + parentProductIdentifiers[i] +
                                           " AND ID(c) =" + childProductId +
                                           " CREATE (p)-[:CONSISTS_OF]->(c)";
                        session.WriteTransaction(tx => tx.Run(statement));
                    }
                }
            }
            return(childProductsCreated);
        }
Exemplo n.º 14
0
        public bool IsUserLikeComment(string userId, string commentID)
        {
            string query = $"Match (u:User)-[:LikeComment]->(c:Comment) " +
                           $"Where u.UserId=\"{userId}\" " +
                           $"And c.CommentID=\"{commentID}\" " +
                           $"Return u";

            IStatementResult posts = session.Run(query);

            List <User> users = new List <User>();

            foreach (var item in posts)
            {
                var props = JsonConvert.SerializeObject(item[0].As <INode>().Properties);
                users.Add(JsonConvert.DeserializeObject <User>(props));
            }
            if (users.Count > 0)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemplo n.º 15
0
        private List <TResult> ParseResults <TResult>(IStatementResult result, CypherQuery query)
        {
            var deserializer = new CypherJsonDeserializer <TResult>(this, query.ResultMode, query.ResultFormat, false, true);
            var results      = new List <TResult>();

            if (typeof(TResult).IsAnonymous())
            {
                foreach (var record in result)
                {
                    results.AddRange(deserializer.Deserialize(record.ParseAnonymous(this)));
                }
            }
            else
            {
                StatementResultHelper.JsonSettings = new JsonSerializerSettings
                {
                    Converters       = JsonConverters,
                    ContractResolver = JsonContractResolver
                };

                List <IEnumerable <TResult> > converted = new List <IEnumerable <TResult> >();
                foreach (var record in result)
                {
                    var des = record.Deserialize(deserializer, query.ResultMode);
                    converted.Add(des);
                }

                foreach (var enumerable in converted)
                {
                    results.AddRange(enumerable);
                }
            }

            return(results);
        }
Exemplo n.º 16
0
        public string GetAllFrames()
        {
            string   jsonFrameStack = null;
            ISession session        = GetSession();

            if (session == null)
            {
                return(null);
            }
            using (session) {
                string           cypher      = @"
MATCH (f:Frame) 
WITH f ORDER BY f.name 
WITH f MATCH (mf:MainFrame) 
WITH {nodetype:'mainframe', title:mf.name} + collect({nodetype:'frame', title:f.name}) as frames 
RETURN frames
";
                IStatementResult result      = session.Run(cypher);
                IRecord          frameRecord = result.FirstOrDefault();
                if (frameRecord != null)
                {
                    jsonFrameStack = JsonConvert.SerializeObject(frameRecord.Values["frames"]);
                }
                return(jsonFrameStack);
            }
        }
Exemplo n.º 17
0
        public IStatementResult DropIndex <T>(T entity, string propertyName) where T : EntityBase
        {
            var query = $"DROP  INDEX ON: {entity.Label}({propertyName})";
            IStatementResult result = ExecuteQuery(query.ToString());

            return(result);
        }
Exemplo n.º 18
0
        private List <string> ParseStringListResults(IStatementResult neoresult)
        {
            List <string> results = new List <string>();

            if (neoresult == null)
            {
                return(results);
            }
            ;

            try
            {
                foreach (IRecord record in neoresult)
                {
                    foreach (string key in record.Keys)
                    {
                        results.Add(record[key].ToString());
                    }
                }
            }
            catch (Exception e)
            {
                this._logger.LogError("Error in ParseStringListResults: " + e.Message);
            }

            return(results);
        }
Exemplo n.º 19
0
        public IStatementResult DeleteAll()
        {
            var query = new StringFormatter(QueryTemplates.TEMPLATE_DELETE_ALL);
            IStatementResult result = ExecuteQuery(query.ToString());

            return(result);
        }
Exemplo n.º 20
0
        public bool MergeRelationship(
            string uuidFrom,
            string uuidTo,
            RelationshipAttribute relationshipAttribute)
        {
            if (string.IsNullOrWhiteSpace(uuidFrom))
            {
                throw new ArgumentNullException("uuidFrom");
            }

            if (string.IsNullOrWhiteSpace(uuidTo))
            {
                throw new ArgumentNullException("uuidTo");
            }

            if (relationshipAttribute == null)
            {
                throw new ArgumentNullException("relationshipAttribute");
            }

            var query = new StringFormatter(QueryTemplates.TEMPLATE_MERGE_RELATIONSHIP);

            query.Add("@uuidFrom", uuidFrom);
            query.Add("@uuidTo", uuidTo);
            query.Add("@fromPartDirection", relationshipAttribute.Direction == DIRECTION.INCOMING ? "<-" : "-");
            query.Add("@toPartDirection", relationshipAttribute.Direction == DIRECTION.INCOMING ? "-" : "->");
            query.Add("@relationshipName", relationshipAttribute.Name);

            IStatementResult result = ExecuteQuery(query.ToString());

            return(result.Any());
        }
Exemplo n.º 21
0
        /// <summary>
        /// Returns a collection of nodes whose release date falls before
        /// </summary>
        /// <param name="start">The DateTime to use as the lower bound of the search</param>
        /// <param name="end">The DateTime to use as the upper bound of the search</param>
        /// <returns>A collection of nodes whose release date is in the specified range</returns>
        public List <BasicNodeModel> GetNodesBetweenDates(DateTime start, DateTime end)
        {
            List <BasicNodeModel> nodeModels = new List <BasicNodeModel>();

            using (ISession session = driver.Session())
            {
                // Create a transaction
                session.ReadTransaction(action =>
                {
                    IStatementResult result = action.Run("MATCH (n) WHERE (n.releaseDate >= $lowerBound AND n.releaseDate <= $upperBound) OR (n.deathDate >= $lowerBound AND n.deathDate <= $upperBound) RETURN n",
                                                         new Dictionary <string, object>
                    {
                        { "lowerBound", DateValueConverter.ToLongValue(start) },
                        { "upperBound", DateValueConverter.ToLongValue(end) }
                    });
                    // Add the nodes
                    foreach (IRecord record in result)
                    {
                        nodeModels.Add(BasicNodeModel.FromINode(record[0].As <INode>()));
                    }
                });
            }

            return(nodeModels);
        }
Exemplo n.º 22
0
        private object ParseSingleIPRelationships(IStatementResult result)
        {
            var node            = new NodeResult();
            var tempDomainNodes = new List <NodeResult>();
            var relationships   = new List <object>();
            int i = 0;

            foreach (var record in result)
            {
                var target = i;
                node = new NodeResult {
                    title = record["i"].As <string>(), label = "ip"
                };
                i += 1;

                var domains = record["domains"].As <List <string> >();
                foreach (var domain in domains)
                {
                    var source = tempDomainNodes.FindIndex(c => c.title == domain);
                    if (source == -1)
                    {
                        tempDomainNodes.Add(new NodeResult {
                            title = domain, label = "domain"
                        });
                        source = i;
                        i     += 1;
                    }
                    relationships.Add(new { target, source });
                }
            }

            return(new { node, links = tempDomainNodes });
        }
Exemplo n.º 23
0
        public void RunCustomCypherQuery()
        {
            using (var client = new NeoClient(URL, USER, PASSWORD, CONFIG))
            {
                client.Connect();

                string cypherCreateQuery = @"CREATE (Neo:Crew {name:'Neo'}), 
                (Morpheus:Crew {name: 'Morpheus'}), 
                (Trinity:Crew {name: 'Trinity'}), 
                (Cypher:Crew:Matrix {name: 'Cypher'}), 
                (Smith:Matrix {name: 'Agent Smith'}), 
                (Architect:Matrix {name:'The Architect'}),
                (Neo)-[:KNOWS]->(Morpheus), 
                (Neo)-[:LOVES]->(Trinity), 
                (Morpheus)-[:KNOWS]->(Trinity),
                (Morpheus)-[:KNOWS]->(Cypher), 
                (Cypher)-[:KNOWS]->(Smith), 
                (Smith)-[:CODED_BY]->(Architect)";

                IStatementResult createResult = client.RunCustomQuery(
                    query: cypherCreateQuery
                    );

                createResult.Should().NotBeNull();
                createResult.Summary.Counters.LabelsAdded.Should().Be(7);
                createResult.Summary.Counters.NodesCreated.Should().Be(6);
                createResult.Summary.Counters.PropertiesSet.Should().Be(6);
                createResult.Summary.Counters.RelationshipsCreated.Should().Be(6);
            }
        }
Exemplo n.º 24
0
        public static void Main()
        {
            const string stmt0 = "RETURN \"Hello World\"";
            const string stmt1 = "CREATE path=(acme:Company {name:\"Acme Corporation\"})" +
                                 " -[:owns]-> " +
                                 "(tesla:Car {make: 'tesla', model: 'modelX'})" +
                                 "RETURN path, acme, tesla, 7890, 1.2, ['a', 'b', 'c'] AS abc ";

            const string stmt3 = "MATCH path=(co:Company)-[r:owns]->(car:Car) RETURN path, co, r, car, " +
                                 "5678, 1.4, timestamp() AS unixepoctime, ['a', 'b', 'c'] AS abc LIMIT 5";
            const string stmt4 = "MATCH (n:Car) RETURN n.make LIMIT 5";
            const string stmt5 = "MATCH (n:Car) RETURN 1234 LIMIT 5";
            const string stmt6 = "MATCH (n) RETURN DISTINCT labels(n)";
            const string stmt7 = "MATCH (n) RETURN DISTINCT labels(n), count(*) AS NumofNodes, " +
                                 "avg(size(keys(n))) AS AvgNumOfPropPerNode, min(size(keys(n))) AS MinNumPropPerNode, max(size(keys(n))) AS MaxNumPropPerNode, " +
                                 "avg(size((n)-[]-())) AS AvgNumOfRelationships, min(size((n)-[]-())) AS MinNumOfRelationships, max(size((n)-[]-())) AS MaxNumOfRelationships ";
            const string stmt8  = "CALL db.labels() YIELD label RETURN label, timestamp() AS unixepoctime";
            const string stmt9  = "RETURN ['a', 'b', 'c'] AS abc, ['d', 123, 456.5] AS def";
            const string stmt10 = "RETURN 1 <> 0";
            const string stmta  = "CREATE (co:Company {name:\"Able Corporation\"}) RETURN co";
            const string stmtb  = "CREATE (co:Company {name:\"Baker Corporation\"}) RETURN co";
            const string stmtc  = "CREATE (co:Company {name:\"Charlie Corporation\"}) RETURN co";
            const string stmtd  = "CREATE (co:Company {name:\"Delta Corporation\"}) RETURN co";

            const string stmtd0 = "MATCH (n) DETACH DELETE n RETURN Count(*)";
            const string stmtd1 = "MATCH (n:Car) DETACH DELETE n RETURN Count(*)";
            const string stmtd2 = "MATCH (n:Company) DETACH DELETE n RETURN Count(*)";

            //_driver = GraphDatabase.Driver("bolt://52.207.74.86:33912", AuthTokens.Basic("neo4j", "gun-november-trips"));
            _driver = GraphDatabase.Driver("bolt://localhost:7687");

            using (var session = _driver.Session())
            {
                IStatementResult resultRecords0 = session.Run(stmtd0);

                IStatementResult resultRecords = session.Run(stmt1);

                List <string> entityKeys = (List <string>)resultRecords.Keys; // variable names & constants in RETURN clause
                var           recordList = resultRecords.ToList <IRecord>();

                foreach (IRecord record in recordList) // for each match in the Cypher statement
                {
                    ProcessRecord(record, entityKeys);
                }

                using (var tx = session.BeginTransaction())
                {
                    resultRecords = tx.Run(stmta);
                    resultRecords = tx.Run(stmtb);
                    resultRecords = tx.Run(stmtc);
                    resultRecords = tx.Run(stmtd);
                    tx.Success();
                }
            }
            _driver.Close();

            Console.WriteLine("Press Enter to exit...");
            Console.ReadLine();
        }
Exemplo n.º 25
0
 public TransactionResult(IStatementResult dbresult)
 {
     this.CreatedNodeCount    = dbresult.Summary.Counters.NodesCreated;
     this.DeletedNodeCount    = dbresult.Summary.Counters.NodesDeleted;
     this.CreatedEdgeCount    = dbresult.Summary.Counters.RelationshipsCreated;
     this.DeletedEdgeCount    = dbresult.Summary.Counters.RelationshipsDeleted;
     this.ElapsedMilliseconds = dbresult.Summary.ResultConsumedAfter;
 }
Exemplo n.º 26
0
        public static SqlObject ScalarValue(this IStatementResult result)
        {
            if (!(result is StatementScalarResult))
            {
                throw new InvalidOperationException("The result is not Scalar");
            }

            return(((StatementScalarResult)result).Value);
        }
Exemplo n.º 27
0
        public static SqlStatementException Error(this IStatementResult result)
        {
            if (!(result is StatementErrorResult))
            {
                throw new InvalidOperationException("The result is not an Error");
            }

            return(((StatementErrorResult)result).Error);
        }
        public void WhenTheDriverAsksTheServerToEchoThisValueBack()
        {
            var expected = ScenarioContext.Current.Get <object>(KeyExpected);
            var session  = TckHooks.CreateSession();

            _statementResult = session.Run("Return {input}", new Dictionary <string, object> {
                { "input", expected }
            });
        }
Exemplo n.º 29
0
 public IStatementResult Run(string command)
 {
     using (ISession session = Program.driver.Session())
     {
         IStatementResult result = session.Run(command);
         return(result);
     }
     //Program.driver.Dispose();
 }
Exemplo n.º 30
0
        public static long TestFunction(long seed, int count)
        {
            long result = seed;

            for (int i = 0; i < count; ++i)
            {
                result ^= i ^ seed; // Some useless bit operations
            }
            return(result);
        }