Beispiel #1
0
    public string GetGameRating(string title)
    {
        string retVal = "nothing";

        GraphClient client = new GraphClient(new Uri("http://localhost:7474/db/data"));

        client.Connect();

        var results = client.Cypher
                      .Match("(game:Game)<-[r:RATES]-()")
                      .Where((Game game) => game.title == title)
                      .Return(() => new
        {
            count = Return.As <int>("count(r)"),
            sum   = Return.As <double>("sum(r.rating)")
        }).Results;

        if (results.Count() > 0)
        {
            var result = results.First();
            retVal = toJson(result);
        }

        return(retVal);
    }
Beispiel #2
0
    public string[] GetDevelopersPagin(string filter, int page, int activeUser)
    {
        List <string> result = new List <string>();

        GraphClient client = new GraphClient(new Uri("http://localhost:7474/db/data"));

        client.Connect();

        var queryBuilder = client.Cypher
                           .Match("(n:Developer)")
                           .Where("n.name =~ {filter}")
                           .OrWhere("n.location =~ {filter}")
                           .OrWhere("n.owner =~ {filter}")
                           .WithParam("filter", ".*(?i)" + filter + ".*");

        var devNodes = queryBuilder
                       .Return <Developer>("n")
                       .OrderBy("tolower(n.title)")
                       .Skip((page - 1) * paginationAmount)
                       .Limit(paginationAmount)
                       .Results;

        foreach (var dev in devNodes)
        {
            result.Add(toJson(dev));
        }

        var gameCount = queryBuilder
                        .Return(() => Return.As <int>("count(n)"))
                        .Results.Single();

        result.Add(gameCount.ToString());

        return(result.ToArray());
    }
Beispiel #3
0
        public async Task Setup_EmptyBoard_ReturnsListOfGroups()
        {
            // Arrange
            string returnedId = await _uow.Boards.AddAsync(_defaultBoard, _username1);

            // Act
            string[] returnedGroups = await _uow.Boards.SetupAsync(returnedId, _defaultGroups);

            // Assert
            Assert.That(returnedGroups.Count(), Is.GreaterThan(0));

            for (int i = 0; i < returnedGroups.Length; i++)
            {
                string groupName = returnedGroups[i];
                Assert.That(groupName, Is.EqualTo(_defaultGroups[i]));

                bool groupWasAdded = (await _graphClient.Cypher
                                      .Match("(board:Board)-[:CHILD_GROUP]->(group:Group)")
                                      .Where((BoardTask board) => board.Id == returnedId)
                                      .AndWhere((GroupNode group) => group.Name == groupName)
                                      .Return((group) => Return.As <int>("count(group)"))
                                      .ResultsAsync)
                                     .Single() == 1;

                Assert.That(groupWasAdded, Is.True);
            }
        }
Beispiel #4
0
    public string GetBestRatedGame()
    {
        string res = "none";

        GraphClient client = new GraphClient(new Uri("http://localhost:7474/db/data"));

        client.Connect();

        var result = client.Cypher
                     .Match("(best:Game)<-[r:RATES]-(user:User)")
                     .Return((best, r) => new
        {
            game       = best.As <Game>(),
            rates      = Return.As <int>("count(r)"),
            totalRates = Return.As <int>("sum(r.rating)")   //r.CollectAs<Rates>()
        }).Results;

        result = result.OrderByDescending(x => x.totalRates / x.rates).ThenByDescending(x => x.rates);

        if (result.Count() > 0)
        {
            res = toJson(result.First());
        }


        return(res);
    }
Beispiel #5
0
        public async Task AddUser_AsCollaboratorToBoard()
        {
            // Arrange
            string boardId = await _uow.Boards.AddAsync(_defaultBoard, _username1);

            await _uow.Boards.SetupAsync(boardId, _defaultGroups);

            // Act
            await _uow.Boards.AddUserAsync(boardId, _username2);

            // Assert
            bool addedCorrectly = (await _graphClient.Cypher
                                   .Match("(user1:User)-[:CHILD_BOARD]->(board:Board)<-[:SHARED_BOARD]-(link:Link)")
                                   .Where("user1.username = {username1}")
                                   .WithParam("username1", _username1.ToLower())
                                   .AndWhere((BoardTask board) => board.Id == boardId)
                                   .Match("(user2:User)-[:CHILD_GROUP]->(:Group)-[:NEXT]->(link)")
                                   .Where("user2.username = {username2}")
                                   .WithParam("username2", _username2.ToLower())
                                   .Return((board) => Return.As <int>("count(board)"))
                                   .ResultsAsync)
                                  .Single() == 1;

            Assert.That(addedCorrectly, Is.True);
        }
        public Product GetNearest(string productName, double lat, double lon, int skip = 0, int take = 10)
        {
            var result = _client.Cypher.Match("(p:Product)-[r: ContainedIn]->(s:Shop)")
                         .Where <ORMProduct>(p => p.Name == productName)
                         .Return((p, s, r) => new
            {
                Product = p.As <ORMProduct>(),
                Cont    = r.As <ORMContainedIn>(),
                Shop    = s.As <ORMShop>(),
                Dist    = Return.As <double>("distance(point({ latitude: toFloat(s.Latitude), longitude: toFloat(s.Longitude)}),point({ latitude: " +
                                             lat + ", longitude: " + lon + "}))")
            }).OrderBy("Dist").Skip(skip).Limit(take).Results;

            ORMProduct pr      = result.First().Product;
            Product    product = new Product()
            {
                Id    = pr.Id,
                Name  = pr.Name,
                Shops = new Dictionary <Shop, ContainedIn>()
            };

            foreach (var res in result)
            {
                product.Shops.Add(res.Shop.ToShop(), res.Cont.ToContainedIn());
            }

            return(product);
        }
Beispiel #7
0
        public MappedContent edit(Content content, string username)
        {
            content.tagstr = removeTrailingComma(content.tagstr);

            // splits up the comma separated string into arrays and removes any empties.
            // each tag uses MERGE and connected to the the content node thru the HAS, e.g content-[:HAS]->tag
            // remember that MERGE will create if it doesn't exist otherwise based on the properties provided
            String[] tags = content.tagstr.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            MappedContent mappedContent = _graphClient.Cypher
                                          .Match(" (c:Content {contentId:{contentId}})-[:NEXTPOST*0..]-()-[:CURRENTPOST]-(user { username: {u}}) ")
                                          .WithParams(new { u = username, contentId = content.contentId })
                                          .Set(" c.title = {title}, c.url = {url}, c.tagstr = {tagstr} ")
                                          .WithParams(new { title = content.title, url = content.url, tagstr = content.tagstr })
                                          .ForEach(" (tagName in {tags} | " +
                                                   "MERGE (t:Tag {wordPhrase:tagName})" +
                                                   " MERGE (c)-[:HAS]->(t) " +
                                                   " )")
                                          .WithParam("tags", tags)
                                          .With("user, c")
                                          .Return(() => Return.As <MappedContent>(" { contentId: c.contentId, title: c.title, url: c.url," +
                                                                                  " tagstr: c.tagstr, timestamp: c.timestamp, userNameForPost: user.username, owner: true } "))
                                          .Results.Single();

            return(mappedContent);
        }
Beispiel #8
0
        public List <UserDTOn> ShortestPath(int id1, int id2)
        {
            if (id1 == id2)
            {
                return(new List <UserDTOn>());
            }
            var path = _client.Cypher
                       .Match("(u1:User{userId: {user_id1} }),(u2:User{userId: {user_id2} }),p = shortestPath((u1)-[:FRIEND*]-(u2))")
                       .WithParam("user_id1", id1)
                       .WithParam("user_id2", id2)
                       .Return((r, len) => new
            {
                shortestPath = Return.As <IEnumerable <Node <UserDTOn> > >("nodes(p)")
            }).Results;
            List <UserDTOn> result = new List <UserDTOn>();

            foreach (var step in path)
            {
                foreach (var s in step.shortestPath.ToList())
                {
                    result.Add(s.Data);
                }
            }
            return(result);
        }
Beispiel #9
0
        public async Task <IEnumerable <GroupDTO> > GetGroupsPage(string filters, string userFilter, string orderBy, bool descending, int from, int to)
        {
            var a = _client.Cypher
                    .Match("(g:Group), (s:Student), (ow)-[:OWNER]-(g)")
                    .Where(userFilter);

            if (!string.IsNullOrEmpty(filters))
            {
                a = a.AndWhere(filters);
            }

            a = a.With("g, {Id: ID(ow), Student: ow} as st");

            ICypherFluentQuery <GroupDTO> ret = a.Return((g, st) => new GroupDTO
            {
                Id      = Return.As <int>("ID(g)"),
                Group   = Return.As <Group>("g"),
                Student = st.As <StudentDTO>()
            });

            if (descending)
            {
                ret = ret.OrderByDescending(orderBy);
            }
            else
            {
                ret = ret.OrderBy(orderBy);
            }

            return(await ret.Skip(from).Limit(to).ResultsAsync);
        }
Beispiel #10
0
    public string GetBestDeveloper()
    {
        string res = "none";

        GraphClient client = new GraphClient(new Uri("http://localhost:7474/db/data"));

        client.Connect();

        var result = client.Cypher
                     .Match("(best:Developer)-[DEVELOPS]->(game:Game)", "(game:Game)<-[r:RATES]-(u:User)")
                     .Return((best, r, game) => new
        {
            dev        = best.As <Developer>(),
            rates      = Return.As <int>("count(r)"),
            totalRates = Return.As <int>("sum(r.rating)"),
            gameCount  = Return.As <int>("count(game)")
        }).Results;

        result = result.OrderByDescending(x => x.totalRates / x.rates).ThenByDescending(x => x.gameCount).ThenByDescending(x => x.rates);

        if (result.Count() > 0)
        {
            res = toJson(result.First());
        }


        return(res);
    }
Beispiel #11
0
        //public List<Bend> vratiBendoveSearch(/*GraphClient client,*/ string input)
        //{

        //    string query = "match (n:Bend) where n.name=~'.*(?i)" + input + ".*' return n";
        //    var qu = vratiRezultat(query);
        //    List<Bend> vrati = ((IRawGraphClient)client).ExecuteGetCypherResults<Bend>(qu).ToList();
        //    return vrati;
        //}
        //public List<Izvodjac> vratiIzvodjaceSearch(/*GraphClient client,*/ string input)
        //{

        //    string query = "match (n:Izvodjac) where n.name=~'.*(?i)" + input + ".*' return n";
        //    var qu = vratiRezultat(query);
        //    List<Izvodjac> vrati = ((IRawGraphClient)client).ExecuteGetCypherResults<Izvodjac>(qu).ToList();
        //    return vrati;
        //}
        //public List<Pesma> vratiPesmeSearch(/*GraphClient client,*/ string input)
        //{

        //    string query = "match (n:Pesma) where n.name=~'.*(?i)" + input + ".*' return n";
        //    var qu = vratiRezultat(query);
        //    List<Pesma> vrati = ((IRawGraphClient)client).ExecuteGetCypherResults<Pesma>(qu).ToList();
        //    return vrati;
        //}
        //public List<Producent> vratiProducentSearch(/*GraphClient client,*/ string input)
        //{

        //    string query = "match (n:Producent) where n.name=~'.*(?i)" + input + ".*' return n";
        //    var qu = vratiRezultat(query);
        //    List<Producent> vrati = ((IRawGraphClient)client).ExecuteGetCypherResults<Producent>(qu).ToList();
        //    return vrati;
        //}
        public Res vratiPretraga(/*GraphClient client,*/ Strana input)
        {
            ////string query = "match (n) where n.name=~'.*(?i)" + input.search + ".*' and not n:Pesma return n.id as Id, n.name as Name, labels(n)[0] as type";
            var qu = client.Cypher.Match("(n)")
                     .Where("n.name=~'.*(?i)" + input.Pretraga + ".*' and not n:Pesma")
                     //.Return((n) => n.As<Pretraga>());
                     .Return(n => new
            {
                id   = Return.As <long>("n.id"),
                name = Return.As <string>("n.name"),
                tip  = n.Labels()
            });
            //var qu = query(input);
            int c = qu.Results.Count();

            qu = qu.Skip(input.Offset).Limit(input.Limit);
            var rez = qu.Results.Select(x => new Pretraga
            {
                id   = x.id,
                name = x.name,
                type = x.tip.FirstOrDefault()
            }).ToList <Pretraga>();


            return(new Res {
                count = c, p = (List <Pretraga>)rez
            });
        }
Beispiel #12
0
        // consumption filter for marketing (matching tags) / tag is optional
        public List <MappedProductUserTag> usersWithMatchingTags(string tag)
        {
            List <MappedProductUserTag> mappedProductUserTags = null;

            if (!String.IsNullOrEmpty(tag))
            {
                mappedProductUserTags = _graphClient.Cypher
                                        .Match("(t:Tag { wordPhrase: {wp} })")
                                        .WithParam("wp", tag)
                                        .Match(" (p:Product)-[:HAS]->(t)<-[:USES]-(u:User) ")
                                        .Return(() => Return.As <MappedProductUserTag>("{ title: p.title , " +
                                                                                       "users: collect(u.username), tags: collect(distinct t.wordPhrase) }"))
                                        .Results.ToList();
            }
            else
            {
                mappedProductUserTags = _graphClient.Cypher
                                        .Match(" (p:Product)-[:HAS]->(t)<-[:USES]-(u:User) ")
                                        .Return(() => Return.As <MappedProductUserTag>("{ title: p.title ,  " +
                                                                                       "users: collect(u.username), tags: collect(distinct t.wordPhrase) }"))
                                        .Results.ToList();
            }



            return(mappedProductUserTags);
        }
Beispiel #13
0
        public void ReturnCustomStatementOnItsOwn()
        {
            Expression <Func <long> > expression = () => Return.As <long>("custom statement");
            var returnExpression = CypherReturnExpressionBuilder.BuildText(expression, CypherCapabilities.Default, GraphClient.DefaultJsonConverters);

            Assert.AreEqual("custom statement", returnExpression.Text);
        }
Beispiel #14
0
        // count tags in aggregate
        public GraphStory tagsInMyNetwork(GraphStory graphStory)
        {
            graphStory.tagsInNetwork = _graphClient.Cypher
                                       .Start(new { u = graphStory.user.noderef })
                                       .Match("u-[:FOLLOWS]->f")
                                       .With("distinct f")
                                       .Match(" f-[:CURRENTPOST]-lp-[:NEXTPOST*0..]-c")
                                       .With("distinct c")
                                       .Match(" c-[ct:HAS]->(t)")
                                       .With("distinct ct, t")
                                       .Return(() => Return.As <MappedContentTag>("{name: t.wordPhrase, label: t.wordPhrase, " +
                                                                                  " id: count(*) }"))
                                       .OrderByDescending("count(*) ")
                                       .Results.ToList();

            graphStory.userTags = _graphClient.Cypher
                                  .Start(new { u = graphStory.user.noderef })
                                  .Match("u-[:CURRENTPOST]-lp-[:NEXTPOST*0..]-c")
                                  .With("distinct c")
                                  .Match(" c-[ct:HAS]->(t)")
                                  .With("distinct ct, t")
                                  .Return(() => Return.As <MappedContentTag>(" {name: t.wordPhrase, label: t.wordPhrase, " +
                                                                             " id: count(*) }"))
                                  .OrderByDescending("count(*) ")
                                  .Results.ToList();


            return(graphStory);
        }
Beispiel #15
0
        public IEnumerable <Recipe> GetRecipe(string[] ingredients)
        {
            using (var graphClient = new GraphClient(new Uri(_connectionString), _userName, _password))
            {
                graphClient.Connect();

                var resultRecipes = graphClient.Cypher.Match("(recipe:Recipe)-[contains:Contains]->(ingredientExists:Ingredient)")
                                    .Where("any(name in {ingredientNames} WHERE ingredientExists.Name =~ name)")
                                    .WithParam("ingredientNames", ingredients.Select(ing => string.Format("{0}.*", ing)))
                                    .Match("(recipe:Recipe)-[contains:Contains]->(ingredientExists:Ingredient)")
                                    .With("recipe, count(ingredientExists) AS countExists")
                                    .Match("(recipe:Recipe)-[contains2:Contains]->(ingredient:Ingredient)")
                                    .With("recipe, countExists, count(contains2) AS allCount, collect(distinct ingredient.Name) AS ingredientsList")
                                    .Return((recipe, ingredientsList) => new Recipe
                {
                    Name        = Return.As <string>("recipe.Name"),
                    Ingredients = ingredientsList.As <IEnumerable <string> >()
                })
                                    .OrderBy("countExists DESC, allCount - countExists")
                                    .Limit(100)
                                    .Results.ToList();

                return(resultRecipes);
            }
        }
Beispiel #16
0
        // capture view and return all views
        public List <MappedProductUserViews> createUserViewAndReturnViews(string username, long productNodeId)
        {
            DateTime datetime       = DateTime.UtcNow;
            string   timestampAsStr = datetime.ToString("MM/dd/yyyy") + " at " +
                                      datetime.ToString("h:mm tt");
            long timestampAsLong = (long)(datetime.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

            List <MappedProductUserViews> mappedProductUserViews = _graphClient.Cypher
                                                                   .Match(" (p:Product), (u:User { username:{u} }) ")
                                                                   .WithParam("u", username)
                                                                   .Where("id(p) = {productNodeId}")
                                                                   .WithParam("productNodeId", productNodeId)
                                                                   .With(" u,p")
                                                                   .Merge(" (u)-[r:VIEWED]->(p)")
                                                                   .Set(" r.dateAsStr={d}, r.timestamp={t} ")
                                                                   .WithParams(new { d = timestampAsStr, t = timestampAsLong })
                                                                   .With(" u ")
                                                                   .Match("  (u)-[r:VIEWED]->(p) ")
                                                                   .Return(() => Return.As <MappedProductUserViews>("{ title: p.title, " +
                                                                                                                    "dateAsStr: r.dateAsStr }"))
                                                                   .OrderByDescending("r.timestamp")
                                                                   .Results.ToList();

            return(mappedProductUserViews);
        }
        public Dictionary <Shop, decimal> GetNearest(IEnumerable <string> products, double lat, double lon)
        {
            var results = _client.Cypher.With("[" + ConstructWith(products) + "] as names")
                          .Match("(p: Product) -[l: ContainedIn]->(s: Shop)")
                          .Where("p.Name in names")
                          .With("s, size(names) as inputCnt, count(DISTINCT p) as cnt, sum(l.Price) as sum," +
                                $"distance(point({{ latitude: toFloat(s.Latitude), longitude: toFloat(s.Longitude)}}),point({{ latitude: {lat}, longitude: {lon}}})) as dist")
                          .Where("cnt = inputCnt")
                          .Return((s, sum) => new
            {
                Shop  = s.As <ORMShop>(),
                Price = Return.As <decimal>("sum"),
                Dist  = Return.As <double>("dist")
            })
                          .OrderBy("dist").Results;


            Dictionary <Shop, decimal> dict = new Dictionary <Shop, decimal>();

            foreach (var res in results)
            {
                dict.Add(res.Shop.ToShop(), res.Price);
            }

            return(dict);
        }
        public async Task <List <Document> > GetDocumentsAsync(IEnumerable <string> documentIds)
        {
            using var client = _graphClientFactory.Create();

            await client.ConnectAsync();

            var idList = documentIds.ToList();

            Task <List <Document> > getDocAndAuthorsTask = Run(async() =>
            {
                var query = client.Cypher
                            .Unwind(idList, "docId")
                            .Match("(d:Document)")
                            .Where("d.id = docId")
                            .OptionalMatch("(a:Author)-[:AUTHORED]->(d)")
                            .Return((d, a) => new
                {
                    Document = d.As <Document>(),
                    Authors  = a.CollectAs <Author>()
                });

                return((await query.ResultsAsync).Select(r =>
                {
                    r.Document.Authors = r.Authors.ToList();
                    return r.Document;
                })
                       .ToList());
            });

            var getCiteCountTask = Run(async() =>
            {
                var query = client.Cypher
                            .Unwind(idList, "docId")
                            .Match("(d:Document)")
                            .Where("d.id = docId")
                            .Match("(r:Document)-[:CITES]->(d)")
                            .Return(r => new
                {
                    DocumentId = Return.As <string>("d.id"),
                    CiteCount  = r.Count()
                });

                return((await query.ResultsAsync).ToDictionary(r => r.DocumentId, r => r.CiteCount));
            });

            await Task.WhenAll(getDocAndAuthorsTask, getCiteCountTask);

            List <Document>           documents    = getDocAndAuthorsTask.Result;
            Dictionary <string, long> citeCountMap = getCiteCountTask.Result;

            foreach (var doc in documents)
            {
                if (citeCountMap.TryGetValue(doc.Id, out long citeCount))
                {
                    doc.CiteCount = (int)citeCount;
                }
            }

            return(documents);
        }
        public RepRelatedClients RelatedUserOrders(string pUserId)
        {
            var query = _client.Cypher
                        .Match("(user:User)<--(ord:Order)-->(p:Place)")
                        .Where("user._id={userId}")
                        .Match("(user2:User)<--(ord2:Order)-->(p2:Place)")
                        .Where("not user2._id={userId} and p2.`_id`=p.`_id`")
                        .WithParam("userId", pUserId)
                        .Return((user, p, user2, ord2, p2) => new {
                ClientId    = Return.As <string>("user._id"),
                ClientName  = Return.As <string>("user.name"),
                ClientLName = Return.As <string>("user.lastName"),
                Stores      = Return.As <IEnumerable <Stores> >("collect(distinct {Place_Id : p.`_id`, " +
                                                                "Place_Name : p.name, Place_Desc : p.description})"),
                OtherUsers = Return.As <IEnumerable <RelatedUsers> >("collect(distinct {UserId:user2.`_id`, UserName:user2.name, " +
                                                                     "UserLastName:user2.lastName, PlaceId:p2.`_id`, PlaceName:p2.name, " +
                                                                     "Date:ord2.dateTime, OrderId:ord2.`_id`})")
            });

            var results = query.Results.ToList();
            List <RepRelatedClients> orders = new List <RepRelatedClients>();


            RepRelatedClients data = new RepRelatedClients();

            data.ClientId    = results[0].ClientId;
            data.ClientName  = results[0].ClientName;
            data.ClientLName = results[0].ClientLName;
            data.Stores      = results[0].Stores.ToList();
            data.OtherUsers  = results[0].OtherUsers.ToList();

            return(data);
        }
Beispiel #20
0
        internal static async void GetDistance(UserPageStream userPageStream)
        {
            var window = ViewsController.GetParentWindow(userPageStream);
            var client = await GetClient();

            int distance = 0;
            await client.ConnectAsync();

            User user1 = new User
            {
                Email = window.User.Email
            };
            User user2 = new User
            {
                Email = userPageStream.User.Email
            };

            if (user1.Email == user2.Email)
            {
                distance = 0;
            }
            else
            {
                var path = client.Cypher
                           .Match("path = shortestPath((u1:User)-[:Follows*]->(u2:User))")
                           .Where((User u1) => u1.Email == user1.Email)
                           .AndWhere((User u2) => u2.Email == user2.Email)
                           .Return(() => Return.As <IEnumerable <string> >("[n IN nodes(path) | n.email]"));

                if (!(path.Results.SingleOrDefault() is null))
                {
                    distance = path.Results.Single().ToList().Count() - 1;
                }
 public async Task <VersionInfo> GetInfo()
 {
     return(await _graphRepository.Client.Cypher
            .Match("(v:Version)")
            .Return(v => Return.As <VersionInfo>("v"))
            .ResultsAsync
            .FirstOrDefault());
 }
 public async Task <IEnumerable <Pathway> > GetAllPathways(bool startingOnly, string gender, int age)
 {
     return(await GetPathwayQuery(startingOnly)
            .Where(string.Join(" and ", new List <string> {
         GenderIs(gender), AgeIsAboveMinimum(age), AgeIsBelowMaximum(age)
     }))
            .Return(p => Return.As <Pathway>("p"))
            .ResultsAsync);
 }
Beispiel #23
0
        public async Task <bool> CheckHealth()
        {
            var result = await _graphRepository.Client.Cypher.
                         Match("(p:Pathway)").
                         Return(p => Return.As <int>("count(p)")).
                         ResultsAsync.FirstOrDefault();

            return(result > 0);
        }
        public async Task <IEnumerable <GroupedPathways> > GetGroupedPathways(bool startingOnly)
        {
            var query = GetPathwayQuery(startingOnly)
                        .Return(p => new GroupedPathways {
                Group = Return.As <string>("distinct(m.digitalDescription)"), PathwayNumbers = Return.As <IEnumerable <string> >("collect(distinct(m.pathwayNo))")
            });

            return(await query.ResultsAsync);
        }
        public void ShouldReturnCustomFunctionCall()
        {
            var client = Substitute.For <IRawGraphClient>();
            var query  = new CypherFluentQuery(client)
                         .Return(() => Return.As <long>("sum(foo.bar)"))
                         .Query;

            Assert.AreEqual("RETURN sum(foo.bar)", query.QueryText);
        }
 private async Task <IEnumerable <QuestionWithAnswers> > GetJustToBeSafeQuestions(string justToBeSafePart)
 {
     return(await _graphRepository.Client.Cypher.
            Match(string.Format("(q:Question {{ jtbs: \"{0}\" }})-[a:Answer]->()", justToBeSafePart)).
            Return(q => new QuestionWithAnswers {
         Question = Return.As <Question>("q"), Answers = Return.As <List <Answer> >(string.Format("collect(a)")), Labels = q.Labels()
     }).
            ResultsAsync);
 }
        public async Task <IEnumerable <Answer> > GetAnswersForQuestion(string id)
        {
            var res = await _graphRepository.Client.Cypher.
                      //Match(string.Format("(:Question {{ id: \"{0}\" }})-[a:Answer]->()", id)).
                      Match(string.Format("({{ id: \"{0}\" }})-[a]->()", id)).
                      Return(a => Return.As <Answer>("a")).
                      ResultsAsync;

            return(res);
        }
Beispiel #28
0
        public IEnumerable <string> ConnectingPaths(Person person1, Person person2)
        {
            var query = _graphClient.Cypher
                        .Match("path = shortestPath((p1:Person)-[:FOLLOW*..6]->(p2:Person))")
                        .Where((Person p1) => p1.NickName == person1.NickName)
                        .AndWhere((Person p2) => p2.NickName == person2.NickName)
                        .Return(() => Return.As <IEnumerable <string> >("[n IN nodes(path) | n.nickname]"));

            return(query.Results.Single());
        }
        public IHttpActionResult GetWorkerBranch(string id)
        {
            var query = WebApiConfig.GraphClient.Cypher
                        .Match("(w:Worker)-[e:WORKSIN]->(b:Branch)")
                        .Where((Worker w) => w.id == id)
                        .Return((w, b) => new
            {
                worker = w.As <Worker>(),
                branch = Return.As <string>("collect(b.number)")
            });

            var queryData = query.Results.ToList();

            var workerBranches = new List <WorkerBranch>();

            foreach (var item in queryData)
            {
                WorkerBranch workerBranch = new WorkerBranch
                {
                    workerNumber = item.worker.number,
                    firstName    = item.worker.firstName,
                    lastName     = item.worker.lastName,
                    BranchNumber = item.branch
                };
                workerBranches.Add(workerBranch);
            }


            UberDocument uberDocument = new UberDocument {
                Version = "1.0", Data = new List <Data>()
            };

            if (workerBranches.Count > 0)
            {
                Data data = new Data();
                data.Rel = new List <string>();
                data.Rel.Add("self");
                data.Rel.Add(Request.Headers.Host + "/api/worker/" + id + "/branch");
                List <Data> result = new List <Data>();

                foreach (WorkerBranch wb in workerBranches)
                {
                    result.Add(GetBranchData(id, wb));
                }

                data.Children = result;
                uberDocument.Data.Add(data);
            }

            string uber = JsonConvert.SerializeObject(uberDocument, Formatting.None, new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            return(Ok(new { uber }));
        }
Beispiel #30
0
        public MappedUserLocation getUserLocation(string currentusername)
        {
            MappedUserLocation mappedUserLocation = _graphClient.Cypher
                                                    .Match(" (u:User { username : {u} } )-[:HAS]-(l:Location) ")
                                                    .WithParam("u", currentusername)
                                                    .Return(() => Return.As <MappedUserLocation>("{ username: u.username, address: l.address," +
                                                                                                 " city:l.city, state: l.state, zip: l.zip, lat: l.lat, lon: l.lon} "))
                                                    .Results.First();

            return(mappedUserLocation);
        }