예제 #1
0
        public static SearchParameters CreateSearchParameters(string searchText, PortalQuery portalQuery, int startIndex = 1, int limit = 20, IList <string> favoriteItemIDs = null)
        {
            string         queryString = string.Format("{0} ({1})", searchText, "type:\"web map\" NOT type:\"web mapping application\"");
            string         sortField   = "";
            QuerySortOrder sortOrder   = QuerySortOrder.Descending;

            switch (portalQuery)
            {
            case PortalQuery.Default:
                //searchParamters.QueryString = "sdfgsdfhh type:\"web map\" NOT \"web mapping application\"";
                break;

            case PortalQuery.Recent:
                sortField = "uploaded";
                break;

            case PortalQuery.HighestRated:
                sortField = "avgrating";
                break;

            case PortalQuery.MostComments:
                sortField = "numcomments";
                break;

            case PortalQuery.MostPopular:
                sortField = "numviews";
                break;

            case PortalQuery.Favorites:
                queryString = GenerateFavoriteQueryFromIDs(favoriteItemIDs);
                break;

            case PortalQuery.MyGroups:
                break;

            case PortalQuery.MyMaps:
                break;

            case PortalQuery.Title:
                sortField = "title";
                sortOrder = QuerySortOrder.Ascending;
                break;

            case PortalQuery.Owner:
                sortField = "owner";
                sortOrder = QuerySortOrder.Ascending;
                break;
            }

            SearchParameters searchParamters = new SearchParameters(queryString);

            searchParamters.StartIndex = startIndex;
            searchParamters.Limit      = limit;
            searchParamters.SortField  = sortField;
            searchParamters.SortOrder  = sortOrder;
            return(searchParamters);
        }
예제 #2
0
        public async Task <HttpResponseMessage> GetDevicesAsync(
            [FromUri] string search            = null,
            [FromUri] string sortColumn        = null,
            [FromUri] QuerySortOrder sortOrder = QuerySortOrder.Ascending,
            [FromUri] int skip = 0,
            [FromUri] int take = 50,
            [FromUri] string[] filterColumn   = null,
            [FromUri] ClauseType[] clauseType = null,
            [FromUri] string[] clauseValue    = null)
        {
            var clauses = new List <Clause>();

            if (filterColumn != null && clauseType != null && clauseValue != null)
            {
                // valid filters must send ALL three values--ignore unmatched extras
                int validFiltersCount = Math.Min(filterColumn.Length, Math.Min(clauseType.Length, clauseValue.Length));
                for (int i = 0; i < validFiltersCount; ++i)
                {
                    var clause = new Clause()
                    {
                        ColumnName  = filterColumn[i],
                        ClauseType  = clauseType[i],
                        ClauseValue = clauseValue[i]
                    };

                    clauses.Add(clause);
                }
            }

            var filter = new DeviceListFilter()
            {
                SearchQuery = search,
                SortColumn  = sortColumn,
                SortOrder   = sortOrder,
                Skip        = skip,
                Take        = take,
                Clauses     = clauses
            };

            return(await GetServiceResponseAsync(async() => (await _deviceLogic.GetDevices(filter)).Results));
        }
        private IQueryable<DeviceModel> SortDeviceList(IQueryable<DeviceModel> deviceList, string sortColumn, QuerySortOrder sortOrder)
        {
            // if a sort column was not provided then return the full device list in its original sort
            if (string.IsNullOrWhiteSpace(sortColumn))
            {
                return deviceList;
            }

            Func<DeviceProperties, dynamic> getPropVal = ReflectionHelper.ProducePropertyValueExtractor(sortColumn, false, false);
            Func<DeviceModel, dynamic> keySelector = (item) =>
            {
                if (item?.DeviceProperties == null)
                {
                    return null;
                }

                if (string.Equals("hubEnabledState", sortColumn, StringComparison.CurrentCultureIgnoreCase))
                {
                    return item.DeviceProperties.GetHubEnabledState();
                }

                return getPropVal(item.DeviceProperties);
            };

            if (sortOrder == QuerySortOrder.Ascending)
            {
                return deviceList.OrderBy(keySelector).AsQueryable();
            }
            else
            {
                return deviceList.OrderByDescending(keySelector).AsQueryable();
            }
        }
예제 #4
0
        public Tridion.ContentDelivery.DynamicContent.Query.Query ToTridionQuery()
        {
            string[] basedOnSchemas              = QuerySchemas;
            DateTime lastPublishedDate           = LastPublishedDate;
            IList <MetaQueryItem> metaQueryItems = MetaQueryValues;
            QueryLogic            metaQueryLogic = MetaQueryLogic;
            int maxmimumComponents = MaximumComponents;

            Query q = null;
            //PublicationCriteria publicationAndLastPublishedDateCriteria = new PublicationCriteria(PublicationId);
            PublicationCriteria publicationAndLastPublishedDateCriteria = new PublicationCriteria(PublicationId);
            //format DateTime // 00:00:00.000
            ItemLastPublishedDateCriteria dateLastPublished = new ItemLastPublishedDateCriteria(lastPublishedDate.ToString("yyyy-MM-dd HH:mm:ss.fff"), Criteria.GreaterThanOrEqual);
            //publicationAndLastPublishedDateCriteria.AddCriteria(dateLastPublished);

            Criteria basedOnSchemaAndInPublication;

            if (basedOnSchemas.Length > 0)
            {
                Criteria[] schemaCriterias = new Criteria[basedOnSchemas.Length];
                int        i = 0;
                foreach (var schema in basedOnSchemas)
                {
                    TcmUri schemaUri = new TcmUri(schema);
                    schemaCriterias.SetValue(new ItemSchemaCriteria(schemaUri.ItemId), i);
                    i++;
                }
                Criteria basedOnSchema = CriteriaFactory.Or(schemaCriterias);
                basedOnSchemaAndInPublication = CriteriaFactory.And(publicationAndLastPublishedDateCriteria, basedOnSchema);
            }
            else
            {
                basedOnSchemaAndInPublication = publicationAndLastPublishedDateCriteria;
            }

            // Add filtering for meta data
            Criteria schemasAndMetaData;

            if (metaQueryItems.Count > 0)
            {
                Criteria   metaQuery;
                Criteria[] metaCriterias = new Criteria[metaQueryItems.Count];
                int        metaCount     = 0;
                foreach (MetaQueryItem queryItem in metaQueryItems)
                {
                    CustomMetaKeyCriteria   metaField = new CustomMetaKeyCriteria(queryItem.MetaField);
                    CustomMetaValueCriteria metaCriteria;
                    FieldOperator           metaOperator = typeof(Criteria).GetField(queryItem.MetaOperator.ToString()).GetValue(null) as FieldOperator;

                    switch (queryItem.MetaValue.GetType().Name)
                    {
                    case "DateTime":
                        DateTime tempDate = (DateTime)queryItem.MetaValue;
                        metaCriteria = new CustomMetaValueCriteria(metaField, tempDate.ToString("yyyy-MM-dd HH:mm:ss.fff"), "yyyy-MM-dd HH:mm:ss.SSS", metaOperator);
                        break;

                    case "Float":
                        metaCriteria = new CustomMetaValueCriteria(metaField, (float)queryItem.MetaValue, metaOperator);
                        break;

                    case "String":
                        metaCriteria = new CustomMetaValueCriteria(metaField, queryItem.MetaValue as string, metaOperator);
                        break;

                    default:
                        throw new System.Exception("Unexpected query item data type; " + queryItem.MetaValue.GetType().Name);
                    }

                    metaCriterias.SetValue(metaCriteria, metaCount);
                    metaCount++;
                }

                if (MetaQueryLogic == QueryLogic.AllCriteriaMatch)
                {
                    metaQuery = CriteriaFactory.And(metaCriterias);
                }
                else
                {
                    metaQuery = CriteriaFactory.Or(metaCriterias);
                }
                schemasAndMetaData = CriteriaFactory.And(basedOnSchemaAndInPublication, metaQuery);
            }
            else
            {
                schemasAndMetaData = basedOnSchemaAndInPublication;
            }

            Criteria allConditions;

            if (KeywordValues.Count > 0)
            {
                Criteria[] keywordCriterias = new Criteria[KeywordValues.Count];
                int        keywordCount     = 0;
                foreach (KeywordItem keyCriteria in KeywordValues)
                {
                    TaxonomyKeywordCriteria keywordField = new TaxonomyKeywordCriteria(keyCriteria.CategoryUri, keyCriteria.KeywordUri, false);
                    keywordCriterias.SetValue(keywordField, keywordCount);
                    keywordCount++;
                }

                Criteria keyQuery;
                if (KeywordQueryLogic == QueryLogic.AllCriteriaMatch)
                {
                    keyQuery = CriteriaFactory.And(keywordCriterias);
                }
                else
                {
                    keyQuery = CriteriaFactory.Or(keywordCriterias);
                }
                allConditions = CriteriaFactory.And(schemasAndMetaData, keyQuery);
            }
            else
            {
                allConditions = schemasAndMetaData;
            }


            q = new Query(allConditions);
            if (maxmimumComponents != 0 && maxmimumComponents != int.MaxValue)
            {
                LimitFilter limitResults = new LimitFilter(maxmimumComponents);
                q.SetResultFilter(limitResults);
            }

            // Sort column should either be a standard or custom metaData field
            SortColumn paramSort;

            if (typeof(SortParameter).GetField(QuerySortField) != null)
            {
                paramSort = typeof(SortParameter).GetField(QuerySortField).GetValue(null) as SortColumn;
            }
            else
            {
                // Why do we need to tell Tridion what data type the field is! Its in the database already!
                /* FIX: Does not work (null pointer exception): var sType = typeof(MetadataType).GetField(SortType.ToString()).GetValue(null) as MetadataType;*/
                paramSort = new CustomMetaKeyColumn(QuerySortField, SortType);
            }
            SortDirection paramSortDirection = typeof(SortParameter).GetField(QuerySortOrder.ToString()).GetValue(null) as SortDirection;
            SortParameter sortParameter      = new SortParameter(paramSort, paramSortDirection);

            q.AddSorting(sortParameter);
            return(q);
        }
        /// <summary>
        /// Sorts the device list on the given column in the given order
        /// </summary>
        /// <param name="deviceList">List of devices to sort</param>
        /// <param name="sortColumn">Column to sort on</param>
        /// <param name="sortOrder">Order to sort (asc/desc)</param>
        /// <returns>Sorted device list</returns>
        private IQueryable<dynamic> SortDeviceList(IQueryable<dynamic> deviceList, string sortColumn, QuerySortOrder sortOrder)
        {
            Func<dynamic, dynamic> getPropVal;
            Func<dynamic, dynamic> keySelector;

            // if a sort column was not provided then return the full device list in its original sort
            if (string.IsNullOrWhiteSpace(sortColumn))
            {
                return deviceList;
            }

            getPropVal =
                ReflectionHelper.ProducePropertyValueExtractor(
                    sortColumn,
                    false,
                    false);

            keySelector =
                (item) =>
                {
                    dynamic deviceProperties;

                    if (item == null)
                    {
                        return null;
                    }

                    if (string.Equals(
                        "hubEnabledState",
                        sortColumn,
                        StringComparison.CurrentCultureIgnoreCase))
                    {
                        try
                        {
                            return DeviceSchemaHelper.GetHubEnabledState(item);
                        }
                        catch (DeviceRequiredPropertyNotFoundException)
                        {
                            return null;
                        }
                    }

                    try
                    {
                        deviceProperties =
                            DeviceSchemaHelper.GetDeviceProperties(item);
                    }
                    catch (DeviceRequiredPropertyNotFoundException)
                    {
                        return null;
                    }

                    return getPropVal(deviceProperties);
                };

            if (sortOrder == QuerySortOrder.Ascending)
            {
                return deviceList.OrderBy(keySelector).AsQueryable();
            }
            else
            {
                return deviceList.OrderByDescending(keySelector).AsQueryable();
            }
        }
        private IQueryable <DeviceModel> SortDeviceList(IQueryable <DeviceModel> deviceList, string sortColumn, QuerySortOrder sortOrder)
        {
            // if a sort column was not provided then return the full device list in its original sort
            if (string.IsNullOrWhiteSpace(sortColumn))
            {
                return(deviceList);
            }

            Func <DeviceProperties, dynamic> getPropVal  = ReflectionHelper.ProducePropertyValueExtractor(sortColumn, false, false);
            Func <DeviceModel, dynamic>      keySelector = (item) =>
            {
                if (item?.DeviceProperties == null)
                {
                    return(null);
                }

                if (string.Equals("hubEnabledState", sortColumn, StringComparison.CurrentCultureIgnoreCase))
                {
                    return(item.DeviceProperties.GetHubEnabledState());
                }

                return(getPropVal(item.DeviceProperties));
            };

            if (sortOrder == QuerySortOrder.Ascending)
            {
                return(deviceList.OrderBy(keySelector).AsQueryable());
            }
            else
            {
                return(deviceList.OrderByDescending(keySelector).AsQueryable());
            }
        }
예제 #7
0
        /// <summary>
        /// Sorts the device list on the given column in the given order
        /// </summary>
        /// <param name="deviceList">List of devices to sort</param>
        /// <param name="sortColumn">Column to sort on</param>
        /// <param name="sortOrder">Order to sort (asc/desc)</param>
        /// <returns>Sorted device list</returns>
        private IQueryable <dynamic> SortDeviceList(IQueryable <dynamic> deviceList, string sortColumn, QuerySortOrder sortOrder)
        {
            Func <dynamic, dynamic> getPropVal;
            Func <dynamic, dynamic> keySelector;

            // if a sort column was not provided then return the full device list in its original sort
            if (string.IsNullOrWhiteSpace(sortColumn))
            {
                return(deviceList);
            }

            getPropVal =
                ReflectionHelper.ProducePropertyValueExtractor(
                    sortColumn,
                    false,
                    false);

            keySelector =
                (item) =>
            {
                dynamic deviceProperties;

                if (item == null)
                {
                    return(null);
                }

                if (string.Equals(
                        "hubEnabledState",
                        sortColumn,
                        StringComparison.CurrentCultureIgnoreCase))
                {
                    try
                    {
                        return(DeviceSchemaHelper.GetHubEnabledState(item));
                    }
                    catch (DeviceRequiredPropertyNotFoundException)
                    {
                        return(null);
                    }
                }

                try
                {
                    deviceProperties =
                        DeviceSchemaHelper.GetDeviceProperties(item);
                }
                catch (DeviceRequiredPropertyNotFoundException)
                {
                    return(null);
                }

                return(getPropVal(deviceProperties));
            };

            if (sortOrder == QuerySortOrder.Ascending)
            {
                return(deviceList.OrderBy(keySelector).AsQueryable());
            }
            else
            {
                return(deviceList.OrderByDescending(keySelector).AsQueryable());
            }
        }
        private IQueryable <Twin> SortDeviceList(IQueryable <Twin> deviceList, string sortColumn, QuerySortOrder sortOrder)
        {
            // if a sort column was not provided then return the full device list in its original sort
            if (string.IsNullOrWhiteSpace(sortColumn))
            {
                return(deviceList);
            }

            Func <Twin, dynamic> keySelector = twin => twin.Get(sortColumn);

            if (sortOrder == QuerySortOrder.Ascending)
            {
                return(deviceList.OrderBy(keySelector).AsQueryable());
            }
            else
            {
                return(deviceList.OrderByDescending(keySelector).AsQueryable());
            }
        }
예제 #9
0
        /// <summary>
        /// Applies a specified sort order to an <see cref="IQueryable[]"/>.
        /// </summary>
        /// <typeparam name="TSource">The type of the element in the <see cref="IQueryable[]"/>.</typeparam>
        /// <param name="instance">The instance of <see cref="IQueryable[]"/> to be extended.</param>
        /// <param name="property">The name of the property to be the order by key.</param>
        /// <param name="sortOrder">The type of sort order to apply to the <see cref="IQueryable[]"/></param>
        /// <returns>A sorted <see cref="IOrderedQueryable[]"/></returns>
        public static IOrderedQueryable <TSource> ApplyOrder <TSource>(this IQueryable <TSource> instance, string property, QuerySortOrder sortOrder)
        {
            string[]            props = property.Split('.');
            Type                type  = typeof(TSource);
            ParameterExpression arg   = Expression.Parameter(type, "x");
            Expression          expr  = arg;

            foreach (string prop in props)
            {
                // use reflection (not ComponentModel) to mirror LINQ
                PropertyInfo pi = type.GetProperty(prop);
                expr = Expression.Property(expr, pi);
                type = pi.PropertyType;
            }

            Type             delegateType = typeof(Func <,>).MakeGenericType(typeof(TSource), type);
            LambdaExpression lambda       = Expression.Lambda(delegateType, expr, arg);

            object result = typeof(Queryable).GetMethods().Single(
                method => method.Name == sortOrder.ToString() &&
                method.IsGenericMethodDefinition &&
                method.GetGenericArguments().Length == 2 &&
                method.GetParameters().Length == 2)
                            .MakeGenericMethod(typeof(TSource), type)
                            .Invoke(null, new object[] { instance, lambda });

            return((IOrderedQueryable <TSource>)result);
        }