Beispiel #1
0
        public void test_WHEN_2_joins_are_specified_THEN_expressions_are_linked_correctly()
        {
            string xml =
                "<Joins>" +
                "<Join Type=\"LEFT\" ListAlias=\"Customers\">" +
                "<Eq>" +
                "<FieldRef Name=\"CustomerName\" RefType=\"Id\" />" +
                "<FieldRef List=\"Customers\" Name=\"Id\" />" +
                "</Eq>" +
                "</Join>" +
                "<Join Type=\"INNER\" ListAlias=\"CustomerCities\">" +
                "<Eq>" +
                "<FieldRef List=\"Customers\" Name=\"CityName\" RefType=\"Id\" />" +
                "<FieldRef List=\"CustomerCities\" Name=\"Id\" />" +
                "</Eq>" +
                "</Join>" +
                "</Joins>";

            var l = new ReLinkerFromCaml(null, null, null, null, XmlHelper.Get(xml), null);
            var g = new GroupByParams();

            Expression <Func <SPListItem, object> > ex1 = x => x["CustomerName"].ForeignList("Customers");
            Expression <Func <SPListItem, object> > ex2 = x => x["CityName"].PrimaryList("Customers").ForeignList("CustomerCities");
            var expr = l.Link(null, null, null, null, (new[] { new KeyValuePair <LambdaExpression, JoinType>(ex1, JoinType.Left), new KeyValuePair <LambdaExpression, JoinType>(ex2, JoinType.Inner) }).ToList(), null, g);

            Assert.That(expr.ToString(), Is.EqualTo("Query().Joins().Left(x => x.get_Item(\"CustomerName\").ForeignList(\"Customers\")).Inner(x => x.get_Item(\"CityName\").PrimaryList(\"Customers\").ForeignList(\"CustomerCities\"))"));
        }
Beispiel #2
0
        public void test_WHEN_fluent_part_and_view_fields_are_specified_THEN_exception_is_thrown()
        {
            var l = new ReLinkerFromCaml(null, null, null, null, null, null);
            var g = new GroupByParams();

            l.Link((Expression <Func <SPListItem, bool> >)(x => (int)x["foo"] == 1), null, null, (Expression <Func <SPListItem, object[]> >)(x => new[] { x["field1"], x["field2"] }), null, null, g);
        }
        public LambdaExpression TranslateGroupBy(out GroupByParams groupByParams)
        {
            groupByParams = new GroupByParams();
            if (this.GroupBy != null)
            {
                groupByParams.HasCollapse   = this.GroupBy.Attributes(Attributes.Collapse).Count() > 0;
                groupByParams.HasGroupLimit = this.GroupBy.Attributes(Attributes.GroupLimit).Count() > 0;

                groupByParams.Collapse   = false;
                groupByParams.GroupLimit = 0;

                if (groupByParams.HasCollapse)
                {
                    if (!bool.TryParse((string)this.GroupBy.Attribute(Attributes.Collapse), out groupByParams.Collapse))
                    {
                        throw new CantParseBooleanAttributeException(Attributes.Collapse);
                    }
                }
                if (groupByParams.HasGroupLimit)
                {
                    if (
                        !int.TryParse((string)this.GroupBy.Attribute(Attributes.GroupLimit),
                                      out groupByParams.GroupLimit))
                    {
                        throw new CantParseIntegerAttributeException(Attributes.GroupLimit);
                    }
                }
            }
            return(this.translateArrayOperation(this.analyzerForGroupBy, Tags.GroupBy));
        }
Beispiel #4
0
 private MethodInfoWithParams getMethodInfo(string methodName, GroupByParams groupByParams)
 {
     if (methodName == ReflectionHelper.WhereMethodName)
     {
         var mi = ReflectionHelper.GetMethodInfo(typeof(IQuery), methodName);
         return(new MethodInfoWithParams(mi, null));
     }
     if (methodName == ReflectionHelper.OrderByMethodName)
     {
         return(this.getOrderByMethodInfo());
     }
     if (methodName == ReflectionHelper.GroupByMethodName)
     {
         return(this.getGroupByMethodInfo(groupByParams));
     }
     if (methodName == ReflectionHelper.ViewFieldsMethodName)
     {
         return(this.getViewFieldsMethodInfo());
     }
     if (methodName == ReflectionHelper.LeftJoinMethodName)
     {
         return(this.getLeftJoinMethodInfo());
     }
     if (methodName == ReflectionHelper.InnerJoinMethodName)
     {
         return(this.getInnerJoinMethodInfo());
     }
     if (methodName == ReflectionHelper.FieldMethodName)
     {
         return(this.getFieldMethodInfo());
     }
     return(null);
 }
Beispiel #5
0
        public void test_WHEN_where_is_specified_THEN_expressions_are_linked_correctly()
        {
            var l    = new ReLinkerFromCaml(null, null, null, null, null, null);
            var g    = new GroupByParams();
            var expr = l.Link((Expression <Func <SPListItem, bool> >)(x => (int)x["foo"] == 1), null, null, null, null, null, g);

            Assert.That(expr.ToString(), Is.EqualTo("Query().Where(x => (Convert(x.get_Item(\"foo\")) = 1))"));
        }
Beispiel #6
0
        public Expression Link(LambdaExpression where, LambdaExpression orderBy, LambdaExpression groupBy,
                               LambdaExpression viewFields, GroupByParams groupByParams)
        {
            // list of fluent calls
            var listFluent = new List <KeyValuePair <string, LambdaExpression> >();

            listFluent.Add(new KeyValuePair <string, LambdaExpression>(ReflectionHelper.WhereMethodName, where));
            listFluent.Add(new KeyValuePair <string, LambdaExpression>(ReflectionHelper.OrderByMethodName, orderBy));
            listFluent.Add(new KeyValuePair <string, LambdaExpression>(ReflectionHelper.GroupByMethodName, groupBy));

            // view fields is not fluent
            var listViewFields = new List <KeyValuePair <string, LambdaExpression> >();

            listViewFields.Add(new KeyValuePair <string, LambdaExpression>(ReflectionHelper.ViewFieldsMethodName, viewFields));

            if (listFluent.Any(kv => kv.Value != null) && listViewFields.Any(kv => kv.Value != null))
            {
                throw new OnlyOnePartOfQueryShouldBeNotNullException();
            }

            var list = listFluent.Any(kv => kv.Value != null) ? listFluent : listViewFields;

            if (list.All(kv => kv.Value == null))
            {
                throw new AtLeastOneCamlPartShouldNotBeEmptyException();
            }


            var queryMi   = ReflectionHelper.GetMethodInfo(typeof(Camlex), ReflectionHelper.QueryMethodName);
            var queryCall = Expression.Call(queryMi);

            var expr = queryCall;

            for (int i = 0; i < list.Count; i++)
            {
                var kv = list[i];
                if (kv.Value != null)
                {
                    var mi = this.getMethodInfo(kv.Key, groupByParams);
                    if (mi != null && mi.MethodInfo != null)
                    {
                        var args = new List <Expression>();
                        // 1st param is always lambda expression
                        args.Add(kv.Value);
                        if (mi.Params != null && mi.Params.Count > 0)
                        {
                            mi.Params.ForEach(p => args.Add(p));
                        }
                        // as we use fluent interfaces we just pass on next step value which we got from prev step
                        expr = Expression.Call(expr, mi.MethodInfo, args);
                    }
                }
            }
            return(expr);
        }
Beispiel #7
0
        public void test_WHEN_order_by_is_specified_but_is_empty_THEN_expression_is_empty()
        {
            var orderBy =
                "  <OrderBy>" +
                "  </OrderBy>";

            var l    = new ReLinkerFromCaml(null, XmlHelper.Get(orderBy), null, null, null, null);
            var g    = new GroupByParams();
            var expr = l.Link(null, (Expression <Func <SPListItem, object> >)(x => x["Title"] as Camlex.Asc), null, null, null, null, g);

            Assert.That(expr.ToString(), Is.EqualTo("Query()"));
        }
Beispiel #8
0
        public void test_WHEN_group_by_is_specified_THEN_expressions_are_linked_correctly()
        {
            var groupBy =
                "  <GroupBy>" +
                "    <FieldRef Name=\"field1\" />" +
                "  </GroupBy>";

            var l    = new ReLinkerFromCaml(null, null, XmlHelper.Get(groupBy), null, null, null);
            var g    = new GroupByParams();
            var expr = l.Link(null, null, (Expression <Func <SPListItem, object> >)(x => x["field1"]), null, null, null, g);

            Assert.That(expr.ToString(), Is.EqualTo("Query().GroupBy(x => x.get_Item(\"field1\"))"));
        }
Beispiel #9
0
        public void test_WHEN_where_and_order_by_are_specified_THEN_expressions_are_linked_correctly()
        {
            var orderBy =
                "  <OrderBy>" +
                "    <FieldRef Name=\"Title\" Ascending=\"True\" />" +
                "  </OrderBy>";

            var l    = new ReLinkerFromCaml(null, XmlHelper.Get(orderBy), null, null, null, null);
            var g    = new GroupByParams();
            var expr = l.Link((Expression <Func <SPListItem, bool> >)(x => (int)x["foo"] == 1), (Expression <Func <SPListItem, object> >)(x => x["Title"] as Camlex.Asc), null, null, null, null, g);

            Assert.That(expr.ToString(), Is.EqualTo("Query().Where(x => (Convert(x.get_Item(\"foo\")) = 1)).OrderBy(x => (x.get_Item(\"Title\") As Asc))"));
        }
Beispiel #10
0
        public void test_WHEN_view_field_is_specified_THEN_expressions_are_linked_correctly()
        {
            string viewFields =
                "<ViewFields>" +
                "<FieldRef Name=\"field1\" />" +
                "</ViewFields>";

            var l    = new ReLinkerFromCaml(null, null, null, XmlHelper.Get(viewFields), null, null);
            var g    = new GroupByParams();
            var expr = l.Link(null, null, null, (Expression <Func <SPListItem, object> >)(x => x["field1"]), null, null, g);

            Assert.That(expr.ToString(), Is.EqualTo("Query().ViewFields(x => x.get_Item(\"field1\"), True)"));
        }
Beispiel #11
0
        public void test_WHEN_several_order_by_are_specified_THEN_expressions_are_linked_correctly()
        {
            var orderBy =
                "  <OrderBy>" +
                "    <FieldRef Name=\"Title\" />" +
                "    <FieldRef Name=\"Date\" Ascending=\"False\" />" +
                "  </OrderBy>";

            var l    = new ReLinkerFromCaml(null, XmlHelper.Get(orderBy), null, null, null, null);
            var g    = new GroupByParams();
            var expr = l.Link(null, (Expression <Func <SPListItem, object[]> >)(x => new[] { x["Title"], x["Date"] as Camlex.Desc }), null, null, null, null, g);

            Assert.That(expr.ToString(), Is.EqualTo("Query().OrderBy(x => new [] {x.get_Item(\"Title\"), (x.get_Item(\"Date\") As Desc)})"));
        }
Beispiel #12
0
        private MethodInfoWithParams getGroupByMethodInfo(GroupByParams groupByParams)
        {
            var count = this.groupBy.Descendants(Tags.FieldRef).Count();

            if (count == 0)
            {
                return(null);
            }

            var p = this.getGroupByParams(count, groupByParams.HasGroupLimit, groupByParams.HasCollapse,
                                          groupByParams.GroupLimit, groupByParams.Collapse);
            var mi = this.getGroupByMethodInfo(count, groupByParams.HasCollapse, groupByParams.HasGroupLimit);

            return(new MethodInfoWithParams(mi, p));
        }
Beispiel #13
0
        public void test_WHEN_1_projected_field_is_specified_THEN_expressions_are_linked_correctly()
        {
            string xml =
                "<ProjectedFields>" +
                "<Field Name=\"test\" Type=\"Lookup\" List=\"foo\" ShowField=\"bar\" />" +
                "</ProjectedFields>";

            var l = new ReLinkerFromCaml(null, null, null, null, null, XmlHelper.Get(xml));
            var g = new GroupByParams();

            Expression <Func <SPListItem, object> > ex = x => x["test"].List("foo").ShowField("bar");
            var expr = l.Link(null, null, null, null, null, (new[] { (LambdaExpression)ex }).ToList(), g);

            Assert.That(expr.ToString(), Is.EqualTo("Query().ProjectedFields().Field(x => x.get_Item(\"test\").List(\"foo\").ShowField(\"bar\"))"));
        }
Beispiel #14
0
        public void test_WHEN_group_by_with_collapse_and_group_limit_is_specified_THEN_expressions_are_linked_correctly()
        {
            var groupBy =
                "  <GroupBy Collapse=\"True\" GroupLimit=\"1\">" +
                "    <FieldRef Name=\"field1\" />" +
                "  </GroupBy>";

            var l = new ReLinkerFromCaml(null, null, XmlHelper.Get(groupBy), null, null, null);
            var g = new GroupByParams {
                HasCollapse = true, Collapse = true, HasGroupLimit = true, GroupLimit = 1
            };
            var expr = l.Link(null, null, (Expression <Func <SPListItem, object> >)(x => x["field1"]), null, null, null, g);

            Assert.That(expr.ToString(), Is.EqualTo("Query().GroupBy(x => x.get_Item(\"field1\"), True, 1)"));
        }
        public void test_THAT_group_by_IS_translated_correctly()
        {
            string xml =
                "  <GroupBy>" +
                "    <FieldRef Name=\"field1\" />" +
                "  </GroupBy>";

            var b    = new ReOperandBuilderFromCaml();
            var t    = new ReTranslatorFromCaml(null, null, new ReArrayAnalyzer(XmlHelper.Get(xml), b), null, null, null);
            var g    = new GroupByParams();
            var expr = t.TranslateGroupBy(out g);

            Assert.That(expr.ToString(), Is.EqualTo("x => x.get_Item(\"field1\")"));
            Assert.IsFalse(g.HasCollapse);
            Assert.IsFalse(g.HasGroupLimit);
        }
Beispiel #16
0
        public void test_WHEN_group_by_with_group_limit_is_specified_with_several_fied_refs_THEN_expressions_are_linked_correctly()
        {
            var groupBy =
                "  <GroupBy GroupLimit=\"1\">" +
                "    <FieldRef Name=\"field1\" />" +
                "    <FieldRef Name=\"field2\" />" +
                "  </GroupBy>";

            var l = new ReLinkerFromCaml(null, null, XmlHelper.Get(groupBy), null, null, null);
            var g = new GroupByParams {
                HasGroupLimit = true, GroupLimit = 1
            };
            var expr = l.Link(null, null, (Expression <Func <SPListItem, object[]> >)(x => new[] { x["field1"], x["field2"] }), null, null, null, g);

            Assert.That(expr.ToString(), Is.EqualTo("Query().GroupBy(x => new [] {x.get_Item(\"field1\"), x.get_Item(\"field2\")}, null, 1)"));
        }
Beispiel #17
0
            public async Task <LastQuery> Search()
            {
                // Get user input
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("Performing Search");
                Console.ForegroundColor = ConsoleColor.White;
                Console.WriteLine("Enter keywords: ");
                var userQuery = Console.ReadLine();

                // var userQuery = "laptop";
                Console.WriteLine("Enter filters:");
                var userAdvancedQuery = Console.ReadLine();
                // var userAdvancedQuery = "";

                // Build Facets
                var facet = new GroupByParams {
                    field = FACET,
                    maximumNumberOfValues           = 10,
                    sortCriteria                    = "occurrences",
                    injectionDepth                  = 1000,
                    completeFacetWithStandardValues = true,
                };

                GroupByParams[] facets = new GroupByParams[1];
                facets.SetValue(facet, 0);

                // Build Params
                var queryParam = new QueryParams {
                    q              = userQuery,
                    aq             = userAdvancedQuery,
                    organizationId = this.orgId,
                    searchHub      = SEARCH_HUB,
                    groupBy        = facets
                };

                // Build Request
                var url  = SEARCH_ENDPOINT;
                var body = new StringContent(JsonConvert.SerializeObject(queryParam), Encoding.UTF8, "application/json");

                // Get Response
                var response = await PostAsync(url, body);

                response.EnsureSuccessStatusCode();
                var     responseString = response.Content.ReadAsStringAsync();
                JObject responseJson   = JObject.Parse(responseString.Result);

                // Store Query Info
                var lastQuery = new LastQuery
                {
                    searchid     = responseJson["searchUid"].ToString(),
                    keyword      = queryParam.q,
                    aq           = queryParam.aq,
                    responseTime = int.Parse(responseJson["duration"].ToString()),
                    totalCount   = int.Parse(responseJson["totalCount"].ToString()),
                    results      = responseJson
                };

                // Print Query Info
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("✅ Query Success");
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine($"Results: {responseJson["totalCount"]}           Response Time: {responseJson["duration"]}ms");
                Console.WriteLine($" ");

                // Print Facet Info
                foreach (var facetResult in responseJson["groupByResults"])
                {
                    Console.WriteLine($"Filter {facetResult["field"]}");
                    foreach (var facetValue in facetResult["values"])
                    {
                        Console.WriteLine($"{facetValue["numberOfResults"]} - {facetValue["value"]} ");
                    }
                }
                Console.WriteLine($" ");


                // Print Result List
                Console.ForegroundColor = ConsoleColor.White;
                var i = 1;

                foreach (var result in responseJson["results"])
                {
                    Console.WriteLine($"{i} | {result["raw"]["coveodpunifiedbrand"].ToString()} | {result["title"].ToString()} | ${result["raw"]["dpretailprice"]} ➜ ${result["raw"]["dpsaleprice"]}");
                    Console.WriteLine($" ");
                    i++;
                }

                // Return last query for UA
                this.lastQuery = lastQuery;
                return(lastQuery);
            }
Beispiel #18
0
        public Expression Link(LambdaExpression @where, LambdaExpression orderBy, LambdaExpression groupBy, LambdaExpression viewFields,
                               List <KeyValuePair <LambdaExpression, JoinType> > joins, List <LambdaExpression> projectedFields, GroupByParams groupByParams)
        {
            // list of fluent calls
            var listFluent = new List <KeyValuePair <string, LambdaExpression> >();

            listFluent.Add(new KeyValuePair <string, LambdaExpression>(ReflectionHelper.WhereMethodName, where));
            listFluent.Add(new KeyValuePair <string, LambdaExpression>(ReflectionHelper.OrderByMethodName, orderBy));
            listFluent.Add(new KeyValuePair <string, LambdaExpression>(ReflectionHelper.GroupByMethodName, groupBy));

            // view fields are not fluent
            var listViewFields = new List <KeyValuePair <string, LambdaExpression> >();

            listViewFields.Add(new KeyValuePair <string, LambdaExpression>(ReflectionHelper.ViewFieldsMethodName, viewFields));

            // joins are not fluent
            var listJoins = new List <KeyValuePair <string, LambdaExpression> >();

            if (joins != null)
            {
                foreach (var kv in joins)
                {
                    listJoins.Add(new KeyValuePair <string, LambdaExpression>(
                                      (kv.Value == JoinType.Inner ? ReflectionHelper.InnerJoinMethodName : ReflectionHelper.LeftJoinMethodName), kv.Key));
                }
            }

            // projected fields are not fluent
            var listProjectedFields = new List <KeyValuePair <string, LambdaExpression> >();

            if (projectedFields != null)
            {
                foreach (var pr in projectedFields)
                {
                    listProjectedFields.Add(new KeyValuePair <string, LambdaExpression>(ReflectionHelper.FieldMethodName, pr));
                }
            }

            int parts = 0;

            if (listFluent.Any(kv => kv.Value != null))
            {
                parts++;
            }
            if (listViewFields.Any(kv => kv.Value != null))
            {
                parts++;
            }
            if (listJoins.Any(kv => kv.Value != null))
            {
                parts++;
            }
            if (listProjectedFields.Any(kv => kv.Value != null))
            {
                parts++;
            }
            if (parts > 1)
            {
                throw new OnlyOnePartOfQueryShouldBeNotNullException();
            }
            else if (parts == 0)
            {
                throw new AtLeastOneCamlPartShouldNotBeEmptyException();
            }

            var list = listFluent.Any(kv => kv.Value != null) ? listFluent : (listViewFields.Any(kv => kv.Value != null) ? listViewFields : (listJoins.Any(kv => kv.Value != null) ? listJoins : listProjectedFields));

            var queryMi   = ReflectionHelper.GetMethodInfo(typeof(Camlex), ReflectionHelper.QueryMethodName);
            var queryCall = Expression.Call(queryMi);

            var expr = queryCall;

            if (list == listJoins)
            {
                // for joins need to call Query().Joins() first
                var joinsMethodInfo = ReflectionHelper.GetMethodInfo(typeof(IQueryEx), ReflectionHelper.JoinsMethodName);
                expr = Expression.Call(queryCall, joinsMethodInfo);
            }
            if (list == listProjectedFields)
            {
                // for joins need to call Query().ProjectedFields() first
                var joinsMethodInfo = ReflectionHelper.GetMethodInfo(typeof(IQueryEx), ReflectionHelper.ProjectedFieldsMethodName);
                expr = Expression.Call(queryCall, joinsMethodInfo);
            }
            for (int i = 0; i < list.Count; i++)
            {
                var kv = list[i];
                if (kv.Value != null)
                {
                    var mi = this.getMethodInfo(kv.Key, groupByParams);
                    if (mi != null && mi.MethodInfo != null)
                    {
                        var args = new List <Expression>();
                        // 1st param is always lambda expression
                        args.Add(kv.Value);
                        if (mi.Params != null && mi.Params.Count > 0)
                        {
                            mi.Params.ForEach(p => args.Add(p));
                        }
                        // as we use fluent interfaces we just pass on next step value which we got from prev step
                        expr = Expression.Call(expr, mi.MethodInfo, args);
                    }
                }
            }
            return(expr);
        }