コード例 #1
0
        public async Task <PaginatedResult <AutoPartProjection> > GetAutoParts(
            AutoPartsFilter filter,
            AutoPartsSortingOption sorting = AutoPartsSortingOption.Name,
            SortingDirection direction     = SortingDirection.Ascending)
        {
            if (filter == null)
            {
                throw new ArgumentNullException($"Parameter {nameof(filter)} of type {nameof(AutoPartsFilter)} cannot be null.");
            }

            var query = PrepareGetAutoPartsQuery(filter);

            var items = await query
                        .ApplyOrderByExpressionFromDictionary(autoPartsSortingExpressions, sorting, direction)
                        .GetPartition(filter.ItemsToSkip, filter.ItemsToTake)
                        .ProjectTo <AutoPartProjection>(mapper.ConfigurationProvider)
                        .ToArrayAsync();

            var totalNumberOfItems = await query
                                     .CountAsync();

            return(new PaginatedResult <AutoPartProjection>
            {
                Items = items,
                TotalNumberOfItems = totalNumberOfItems
            });
        }
コード例 #2
0
        private void RenderTitleCell(
            SortingDirection sortDirection,
            int sortIndex,
            string iconFilename,
            string iconAltText)
        {
            IBocColumnRenderer renderer = new BocSimpleColumnQuirksModeRenderer(new FakeResourceUrlFactory(), _bocListQuirksModeCssClassDefinition);

            renderer.RenderTitleCell(_renderingContext, sortDirection, sortIndex);

            var document = Html.GetResultDocument();

            var th = Html.GetAssertedChildElement(document, "th", 0);

            Html.AssertAttribute(th, "class", _bocListQuirksModeCssClassDefinition.TitleCell, HtmlHelperBase.AttributeValueCompareMode.Contains);
            Html.AssertAttribute(th, "class", c_columnCssClass, HtmlHelperBase.AttributeValueCompareMode.Contains);

            Assert.Less(0, th.ChildNodes.Count);
            var sortCommandLink = Html.GetAssertedChildElement(th, "a", 0);

            Html.AssertAttribute(sortCommandLink, "id", List.ClientID + "_0_SortCommand");
            Html.AssertTextNode(sortCommandLink, Column.ColumnTitleDisplayValue + HtmlHelper.WhiteSpace, 0);

            var sortOrderSpan = Html.GetAssertedChildElement(sortCommandLink, "span", 1);

            Html.AssertAttribute(
                sortOrderSpan, "class", _bocListQuirksModeCssClassDefinition.SortingOrder, HtmlHelperBase.AttributeValueCompareMode.Contains);

            var sortIcon = Html.GetAssertedChildElement(sortOrderSpan, "img", 0);

            Html.AssertAttribute(sortIcon, "src", iconFilename, HtmlHelperBase.AttributeValueCompareMode.Contains);
            Html.AssertAttribute(sortIcon, "alt", iconAltText);

            Html.AssertTextNode(sortOrderSpan, HtmlHelper.WhiteSpace + (sortIndex + 1), 1);
        }
コード例 #3
0
        /// <summary>
        /// Configure default sorting value for object type
        /// </summary>
        /// <typeparam name="TToProperty">Type default value configured for</typeparam>
        /// <param name="toPredicate">Property for default sorting</param>
        /// <param name="sortingDirection">Sorting direction</param>
        public FilterBuilder <TFromEntity, TToEntity> Default <TToProperty>(
            Expression <Func <TToEntity, TToProperty> > toPredicate,
            SortingDirection sortingDirection = SortingDirection.Asc)
        {
            //var defaultName = $"{typeof(TToEntity).FullName}.Default";
            var defaultName = $"{typeof(TFromEntity).FullName}.Default";

            var toMember = toPredicate.Body as MemberExpression;

            var propertyPath = GetPropertyPath(toPredicate.Body as MemberExpression);

            // create filter setting which stores all data about filter
            var filterSetting = new FilterSetting
            {
                Name             = defaultName,
                PropertyPath     = propertyPath,
                OperandType      = toMember.Member.DeclaringType,
                ParameterType    = toMember.Type,
                OperatorBetween  = OperatorBetween.None,
                MethodName       = Method.Equal,
                SortingDirection = sortingDirection
            };

            _filterSetting.Add(defaultName, filterSetting);

            return(this);
        }
コード例 #4
0
        public virtual void RenderTitleCell(
            BocColumnRenderingContext <TBocColumnDefinition> renderingContext, SortingDirection sortingDirection, int orderIndex)
        {
            ArgumentUtility.CheckNotNull("renderingContext", renderingContext);

            string cssClassTitleCell = CssClasses.TitleCell;

            if (!string.IsNullOrEmpty(renderingContext.ColumnDefinition.CssClass))
            {
                cssClassTitleCell += " " + renderingContext.ColumnDefinition.CssClass;
            }
            renderingContext.Writer.AddAttribute(HtmlTextWriterAttribute.Class, cssClassTitleCell);
            renderingContext.Writer.RenderBeginTag(HtmlTextWriterTag.Th);

            RenderTitleCellMarkers(renderingContext);
            RenderBeginTagTitleCellSortCommand(renderingContext);
            RenderTitleCellText(renderingContext);
            if (renderingContext.Control.IsClientSideSortingEnabled || renderingContext.Control.HasSortingKeys)
            {
                RenderTitleCellSortingButton(renderingContext, sortingDirection, orderIndex);
            }
            RenderEndTagTitleCellSortCommand(renderingContext.Writer);

            renderingContext.Writer.RenderEndTag();
        }
コード例 #5
0
        public void When_ListView_Creating_Sort_CollectionSource(SortingDirection sortingDirection, int first, int last)
        {
            using var application = PositionInListViewModuleModule().Application;
            var positionInListView = application.Model.ToReactiveModule <IModelReactiveModulesPositionInListView>()
                                     .PositionInListView.ListViewItems.AddNode <IModelPositionInListViewListViewItem>();

            positionInListView.ListView         = application.Model.BOModel.GetClass(typeof(PIL)).DefaultListView;
            positionInListView.SortingDirection = sortingDirection;
            var listViewColumn = positionInListView.ListView.Columns[nameof(PIL.Name)];

            listViewColumn.SortOrder = 0;
            listViewColumn.SortOrder = ColumnSortOrder.Ascending;
            var objectSpace = application.CreateObjectSpace();
            var pil1        = objectSpace.CreateObject <PIL>();

            pil1.Name = "c";
            var pil2 = objectSpace.CreateObject <PIL>();

            pil2.Name = "a";
            var pil3 = objectSpace.CreateObject <PIL>();

            pil3.Name = "b";
            objectSpace.CommitChanges();

            var listView = application.NewView(positionInListView.ListView).AsListView();

            application.CreateViewWindow().SetView(listView);

            var objects = listView.CollectionSource.Objects <PIL>().Select(pil => pil.Name).ToArray();

            objects[first].ShouldBe(pil1.Name);
            objects[1].ShouldBe(pil2.Name);
            objects[last].ShouldBe(pil3.Name);
        }
コード例 #6
0
        /// <summary>
        /// Maps property of filter object to certain object typed stored in database
        /// </summary>
        /// <typeparam name="TFromProperty">Property type to bind from</typeparam>
        /// <typeparam name="TToProperty">Property type to bind to</typeparam>
        /// <param name="fromPredicate">Property to bind from</param>
        /// <param name="toPredicate">Property to bind to</param>
        /// <param name="operatorBetween">Operator between conditions in db query</param>
        /// <param name="method">Method to call for property</param>
        /// <param name="sorting">Sorting type</param>
        public FilterBuilder <TFromEntity, TToEntity> Map <TFromProperty, TToProperty>(
            Expression <Func <TFromEntity, TFromProperty> > fromPredicate,
            Expression <Func <TToEntity, TToProperty> > toPredicate,
            OperatorBetween operatorBetween,
            Method method,
            SortingDirection sortingDirection = SortingDirection.Asc)
        {
            // get full property names
            var fromPropertyName = GetFullPropertyName(fromPredicate);

            var toMember = toPredicate.Body as MemberExpression;

            var propertyPath = GetPropertyPath(toPredicate.Body as MemberExpression);

            // create filter setting which stores all data about filter
            var filterSetting = new FilterSetting
            {
                Name             = fromPropertyName,
                PropertyPath     = propertyPath,
                OperandType      = toMember.Member.DeclaringType,
                ParameterType    = toMember.Type,
                OperatorBetween  = operatorBetween,
                MethodName       = method,
                SortingDirection = sortingDirection
            };

            _filterSetting.Add(fromPropertyName, filterSetting);

            return(this);
        }
コード例 #7
0
        /// <summary>
        /// Classic Select
        /// </summary>
        /// <remarks>
        /// Sorts to the right, picks up the smallest/largest (depending on if it's desc or asc)
        /// and puts it from left to right
        /// </remarks>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="sorting"></param>
        /// <returns></returns>
        public static SwappingSortingResult <T> SortUsingClassicSelect <T>(this T[] source,
                                                                           SortingDirection sorting = SortingDirection.Ascending)
            where T : struct, IComparable <T>
        {
            if (null == source)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var iterations = 0;
            var swaps      = 0;

            for (var i = 0; i < source.Length - 1; i++)
            {
                for (var j = i + 1; j < source.Length; j++)
                {
                    if (Helpers.ShoudSwap(source[i], source[j], sorting))
                    {
                        Helpers.Swap(ref source[i], ref source[j]);
                        swaps++;
                    }

                    iterations++;
                }
            }

            return(new SwappingSortingResult <T>(source, iterations, swaps));
        }
コード例 #8
0
        /// <summary>
        /// Orders a <see cref="IQueryable"/> by given sorting. Order expression is being taken from sortingExpressions dictionary.
        /// If <see cref="SortingDirectionAttribute" /> is not provided on the sorting enum value the default sorting order is Ascending
        /// </summary>
        /// <typeparam name="TSource">
        /// <see cref="IQueryable"/> generic type parameter
        /// </typeparam>
        /// <typeparam name="TSortingEnum">
        /// Enum type which represents sorting option
        /// </typeparam>
        /// <param name="source"></param>
        /// <param name="sortingExpressions">Dictionary of expressions of sorting options</param>
        /// <param name="sorting">Enum value which represents sorting option</param>
        /// <param name="sortingDirection">Enum value which represents order of sorting options</param>
        public static IQueryable <TSource> ApplyOrderByExpressionFromDictionary <TSource, TSortingEnum>(
            this IQueryable <TSource> source,
            IReadOnlyDictionary <TSortingEnum, Expression <Func <TSource, object> > > sortingExpressions,
            TSortingEnum sorting,
            SortingDirection sortingDirection = SortingDirection.Descending
            )
            where TSortingEnum : struct, IConvertible
        {
            var sortingType = typeof(TSortingEnum);

            if (!sortingType.IsEnum)
            {
                throw new ArgumentException($"{nameof(TSortingEnum)} must be an enumerated type");
            }

            if (!sortingExpressions.ContainsKey(sorting))
            {
                return(source);
            }

            var sortingExpression = sortingExpressions[sorting];

            if (sortingDirection == SortingDirection.Ascending)
            {
                return(source.OrderBy(sortingExpression)
                       .AsQueryable());
            }

            return(source.OrderByDescending(sortingExpression)
                   .AsQueryable());
        }
コード例 #9
0
        public static double[] BubbleSort(double[] array, SortingDirection direction)
        {
            // A comparison cycle of the i-th element with subsequent elements of the array.
            for (int i = 0; i < array.Length - 1; i++)
            {
                for (int j = i + 1; j < array.Length; j++)
                {
                    // Sort the elements of the array in ascending or descending order depending on the selected sorting direction.
                    switch (direction)
                    {
                    case SortingDirection.Asc:
                        // If the i-th element of the array is greater than the j-th element.
                        if (array[i] > array[j])
                        {
                            // Swap elements which passed order condition.
                            Helper.Swap(array, i, j);
                        }
                        break;

                    case SortingDirection.Desc:
                        // If the i-th element of the array is less than the j-th element.
                        if (array[i] < array[j])
                        {
                            // Swap elements which passed order condition.
                            Helper.Swap(array, i, j);
                        }
                        break;
                    }
                }
            }
            return(array);
        }
コード例 #10
0
        /// <summary>
        /// Classic Insert sorting algorithm. Variation to reduce if statements
        /// </summary>
        /// <remarks>Sorts to the left</remarks>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="sorting"></param>
        /// <returns></returns>
        public static SwappingSortingResult <T> SortUsingClassiccInsertNoIfs <T>(this T[] source,
                                                                                 SortingDirection sorting = SortingDirection.Ascending)
            where T : struct, IComparable <T>
        {
            if (null == source)
            {
                throw new ArgumentNullException(nameof(source));
            }

            var iterations = 0;
            var swaps      = 0;

            for (var i = 1; i < source.Length; i++)
            {
                var j = i;

                while (j > 0 && Helpers.ShoudSwap(source[j - 1], source[j], sorting))
                {
                    Helpers.Swap(ref source[j - 1], ref source[j]);

                    j--;
                    swaps++;
                    iterations++;
                }
            }

            return(new SwappingSortingResult <T>(source, iterations, swaps));
        }
コード例 #11
0
ファイル: Sorter.cs プロジェクト: Ovsyann/Practice
        private void RememberCriteria(string propertyName, SortingDirection providerKind, Type propertyType)
        {
            MemberInfo       property           = this.type.GetProperty(propertyName, propertyType);
            MemberExpression propertyExpression = Expression.MakeMemberAccess(parameter, property);

            sortingСriteria.Add(new Tuple <SortingDirection, MemberExpression>(providerKind, propertyExpression));
        }
コード例 #12
0
 public UserScoreIndex(int IndexId, string IndexName, SortingDirection SortingDirection)
 {
     this.IndexId            = IndexId;
     this.IndexName          = IndexName;
     this.SortingDirection   = SortingDirection;
     this.Tree               = new RedBlackTreeWithStats <UserScore>(this);
     this.UserScoresByUserId = new Dictionary <uint, UserScore>();
 }
コード例 #13
0
ファイル: Helpers.cs プロジェクト: jupaol/Learning2
        public static void SwapIfNeeded <T>(ref T left, ref T right, SortingDirection sorting, Action onSwap = null)
            where T : struct, IComparable <T>
        {
            if (ShoudSwap(left, right, sorting))
            {
                Swap(ref left, ref right);

                onSwap?.Invoke();
            }
        }
コード例 #14
0
ファイル: MergeSort.cs プロジェクト: jupaol/Learning2
        /// <summary>
        /// Classic merge sort
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="sorting"></param>
        /// <returns></returns>
        public static SwappingSortingResult <T> SortUsingClassicMerge <T>(this T[] source,
                                                                          SortingDirection sorting = SortingDirection.Ascending)
            where T : struct, IComparable <T>
        {
            if (null == source)
            {
                throw new ArgumentNullException(nameof(source));
            }

            return(null);
        }
コード例 #15
0
        private void Sort(object columnName)
        {
            if (CanSort(columnName))
            {
                sortDirection = sortingColumn == (string)columnName && sortDirection == SortingDirection.Ascendung ?
                                sortDirection = SortingDirection.Descending : sortDirection = SortingDirection.Ascendung;
                sortingColumn = (string)columnName;

                ResetPageing();
            }
        }
コード例 #16
0
        public UserScoreIndex this[string IndexName]
        {
            get
            {
                lock (this)
                {
                    return(Indices[IndiceIdsByName.GetOrCreate(IndexName, () =>
                    {
                        SortingDirection SortingDirection = SortingDirection.Invalid;
                        var IndexNameMatch = new Regex(@"^([\+\-])[^:]+(:(\d+))?$", RegexOptions.Compiled).Match(IndexName);
                        if (!IndexNameMatch.Success)
                        {
                            throw(new Exception("Invalid Index Name '" + IndexName + "'"));
                        }
                        var DirectionString = IndexNameMatch.Groups[1].Value;
                        var CappedCountString = IndexNameMatch.Groups[3].Value;
                        int CappedCount = -1;

                        if (DirectionString == "+")
                        {
                            SortingDirection = SortingDirection.Ascending;
                        }
                        if (DirectionString == "-")
                        {
                            SortingDirection = SortingDirection.Descending;
                        }
                        if (CappedCountString.Length > 0)
                        {
                            CappedCount = int.Parse(CappedCountString);
                        }

                        if (SortingDirection == SortingDirection.Invalid)
                        {
                            throw(new Exception("The index must be called '-IndexName' or '+IndexName' wether is a descending index or ascending index."));
                        }
                        var Index = new UserScoreIndex(Indices.Count, IndexName, SortingDirection);
                        Index.CappedCount = CappedCount;
                        //Index.Tree.CappedToNumberOfElements = CappedCount;
                        Indices.Add(Index);

                        Console.WriteLine(
                            "Created Indexd: '{0}' :: IndexId({1}), Direction({2}), CappedCount({3})",
                            IndexName,
                            Index.IndexId,
                            Enum.GetName(typeof(SortingDirection), SortingDirection),
                            CappedCount
                            );

                        return Index.IndexId;
                    })]);
                }
            }
        }
コード例 #17
0
ファイル: Database.cs プロジェクト: nGenieDeveloper/MonczoDB
        public Task <List <DBRecord> > SortByAsync(string column, SortingDirection direction)
        {
            List <DBRecord>         sortedRecords = new List <DBRecord>(records);
            Task <List <DBRecord> > task          = Task <List <DBRecord> > .Factory.StartNew(() =>
            {
                RecordComparer comparer = new RecordComparer(column, direction);
                sortedRecords.Sort(comparer);
                return(sortedRecords);
            });

            return(task);
        }
コード例 #18
0
        private SingleChart GetElectricityChart(string id, string countryCode, string yearConfig, SortingDirection sortingDirection)
        {
            SingleChart result = null;
            Dictionary<string, Dictionary<string, List<string>>> config;
            DatabaseRepository db;
            IList<GetValuesResult> data;
            IList<int> years;
            int requestedCountryId;
            List<GetIndicatorsInfoResult> indicatorList;
            List<GetCountriesInfo_Result> countryList;
            List<GetSupportedIndicatorsResult> supportedIndicatorList;
            InitChartData(id, countryCode, yearConfig, false, true, true, out db, out data, out years,
                out requestedCountryId, out indicatorList, out countryList, out supportedIndicatorList, out config);

            var chartInfo = db.GetChartInfo(id);
            if (chartInfo != null)
            {
                var countries = countryList.ToDictionary(c => c.CountryId);

                var dataDictionary = data.ToDictionary(
                    d => new Tuple<int, int, int>(d.CountryId, d.IndicatorId, d.Year), d => d.IndicatorValue);

                var supportedIndicatorIds =
                    supportedIndicatorList.Select(s => s.SupportedIndicatorId).Distinct().ToDictionary(i => i);
                var cleanedData = data.Where(d => !supportedIndicatorIds.ContainsKey(d.IndicatorId)).ToList();

                List<int> categoryIds;
                if (sortingDirection != SortingDirection.None)
                {
                    GetCategoryOrder(requestedCountryId, cleanedData, countries, countryList,
                        sortingDirection == SortingDirection.Desc, out categoryIds);
                }
                else
                {
                    categoryIds =
                        data.Select(d => d.CountryId).Distinct().OrderBy(cId => countries[cId].CountryType).ToList();
                }

                List<string> cats;
                List<ChartSeries> sers;
                ConvertToSeries(cleanedData, categoryIds, countryList.ToDictionary(y => y.CountryId, y => y.Name), g => g.Year,
                    SeriesType.Bar,
                    years.ToDictionary(k => k, k => k.ToString()), g => g.CountryId, d => new Point { Value = d },
                    out cats, out sers);

                result = years.Count > 0 ? CreateChart(chartInfo, years.First(), years.Last(), cats, sers) : CreateChart(chartInfo);
                SetStartOrEndValue(result, PointToSet.Min);
                SetStartOrEndValue(result, PointToSet.Max);
            }

            return result;
        }
コード例 #19
0
        private static QueryMethod GetQueryMethod(SortingDirection direction, bool isFirst)
        {
            if (isFirst)
            {
                return direction == SortingDirection.Descending
                    ? QueryMethod.OrderByDescending
                    : QueryMethod.OrderBy;
            }

            return direction == SortingDirection.Descending
                ? QueryMethod.ThenByDescending
                : QueryMethod.ThenBy;
        }
コード例 #20
0
        private static QueryMethod GetQueryMethod(SortingDirection direction, bool isFirst)
        {
            if (isFirst)
            {
                return(direction == SortingDirection.Descending
                    ? QueryMethod.OrderByDescending
                    : QueryMethod.OrderBy);
            }

            return(direction == SortingDirection.Descending
                ? QueryMethod.ThenByDescending
                : QueryMethod.ThenBy);
        }
コード例 #21
0
 /// <summary>
 /// Fired when the Sorting Direction is changed update the indicators state.
 /// </summary>
 /// <param name="control"><see cref="GridSortIndicator"/> to update.</param>
 /// <param name="direction">New <see cref="SortingDirection"/> to set indication to.</param>
 protected virtual void OnSortingDirectionChanged(GridSortIndicator control, SortingDirection direction)
 {
     if (direction == SortingDirection.Asc)
     {
         control.uc_Polygon_Asc.Visibility  = Visibility.Visible;
         control.uc_Polygon_Desc.Visibility = Visibility.Collapsed;
     }
     else
     {
         control.uc_Polygon_Asc.Visibility  = Visibility.Collapsed;
         control.uc_Polygon_Desc.Visibility = Visibility.Visible;
     }
 }
コード例 #22
0
ファイル: Form1.cs プロジェクト: profkaygee/DirectAxis
        private DataTable SortDataByBirthDate(DataTable inputData, SortingDirection direction)
        {
            switch (direction)
            {
            case SortingDirection.Ascending:
                return(SortByAscending(inputData, null));

            case SortingDirection.Descending:
                return(SortByDescending(inputData, null));

            default:
                return(inputData);
            }
        }
コード例 #23
0
        private FiltersWithSorting GetFiltersWithSortingFromJson(JObject json)
        {
            var sorting        = json["sorting"].ToString();
            var name           = json["name"].ToString();
            var gameDates      = json["gameDates"].ToString();
            var remainingShips = json["remainingShips"].ToString() == "" ? -1 : json["remainingShips"].ToObject <int>();
            var gameTurns      = json["gameTurns"].ToString() == "" ? -1 : json["gameTurns"].ToObject <int>();

            var sortingItemElements = sorting.Split('/');
            var datesItems          = gameDates.Split(" - ");

            SortingDirection sortingDirection = sortingItemElements[0] switch
            {
                "desc" => SortingDirection.Descending,
                "asc" => SortingDirection.Ascending
            };
            SortingType sortingType = sortingItemElements[1] switch
            {
                "ship" => SortingType.RemainingShipsSorting,
                "date" => SortingType.DateSorting
            };
            DateTime       firstDate;
            DateTime       secondDate;
            List <IFilter> filters = new List <IFilter>();

            if (DateTime.TryParse(datesItems[0], out firstDate) && DateTime.TryParse(datesItems[1], out secondDate))
            {
                filters.Add(new DateFilter(firstDate, secondDate));
            }
            if (!string.IsNullOrEmpty(name))
            {
                filters.Add(new PlayerFilter(name));
            }
            if (remainingShips != -1)
            {
                filters.Add(new RemainingShipFilter(remainingShips));
            }
            if (gameTurns != -1)
            {
                filters.Add(new GameTurnFilter(gameTurns));
            }

            return(new FiltersWithSorting()
            {
                Filters = filters,
                Sorting = new SortingItem(sortingType, sortingDirection)
            });
        }
    }
}
コード例 #24
0
        // TODO: Proper exception handling
        private async Task SortTask(SortingDirection dir)
        {
            UpdateStatusText($"Sorting by {selectedColumn}...");
            try
            {
                DBInterface.db.records = await DBInterface.db.SortByAsync(selectedColumn, dir);

                UpdateStatusText("Ready");
            }
            catch (Exception)
            {
                UpdateStatusText("Cannot sort!");
            }
            await UpdateDBGrid();
        }
コード例 #25
0
        protected virtual void RenderTitleCell(
            BocColumnRenderingContext <TBocColumnDefinition> renderingContext,
            SortingDirection sortingDirection,
            int orderIndex)
        {
            ArgumentUtility.CheckNotNull("renderingContext", renderingContext);

            string cssClassTitleCell = CssClasses.TitleCell;

            if (!string.IsNullOrEmpty(renderingContext.ColumnDefinition.CssClass))
            {
                cssClassTitleCell += " " + renderingContext.ColumnDefinition.CssClass;
            }
            renderingContext.Writer.AddAttribute(HtmlTextWriterAttribute.Class, cssClassTitleCell);
            if (_renderingFeatures.EnableDiagnosticMetadata)
            {
                var columnItemID = renderingContext.ColumnDefinition.ItemID;
                if (!string.IsNullOrEmpty(columnItemID))
                {
                    renderingContext.Writer.AddAttribute(DiagnosticMetadataAttributes.ItemID, columnItemID);
                }

                var columnTitle = renderingContext.ColumnDefinition.ColumnTitleDisplayValue;
                if (!string.IsNullOrEmpty(columnTitle))
                {
                    renderingContext.Writer.AddAttribute(DiagnosticMetadataAttributes.Content, HtmlUtility.StripHtmlTags(columnTitle));
                }

                var oneBasedCellIndex = renderingContext.VisibleColumnIndex + 1;
                renderingContext.Writer.AddAttribute(DiagnosticMetadataAttributesForObjectBinding.BocListCellIndex, oneBasedCellIndex.ToString());

                renderingContext.Writer.AddAttribute(
                    DiagnosticMetadataAttributesForObjectBinding.BocListColumnHasDiagnosticMetadata,
                    HasDiagnoticMetadata.ToString().ToLower());
            }
            renderingContext.Writer.RenderBeginTag(HtmlTextWriterTag.Th);

            RenderTitleCellMarkers(renderingContext);
            RenderBeginTagTitleCellSortCommand(renderingContext);
            RenderTitleCellText(renderingContext);
            if (renderingContext.Control.IsClientSideSortingEnabled || renderingContext.Control.HasSortingKeys)
            {
                RenderTitleCellSortingButton(renderingContext, sortingDirection, orderIndex);
            }
            RenderEndTagTitleCellSortCommand(renderingContext);

            renderingContext.Writer.RenderEndTag();
        }
コード例 #26
0
        private IQueryable <T> ExecuteSorting(IQueryable <T> rows, GridStateModel gridState)
        {
            if (gridState.FilterState == null)
            {
                return(rows);
            }

            SortingDirection sortingDirection  = gridState.FilterState.SortingDirection;
            string           sortingColumn     = gridState.FilterState.SortingColumn;
            Type             sortingColumnType = gridState.FilterState.SortingPropertyType;

            if (string.IsNullOrWhiteSpace(sortingColumn) || sortingDirection == SortingDirection.Undefined)
            {
                return(rows);
            }

            // If the source type is Interface, which inherits another Interface, and the property belongs to this base Interface,
            // 'Expression' will throw an error. Then, sorting needs to be done by this base Interface type.
            Type sortingType = this.GetExpressionType(sortingColumn);

            // If the source type is Interface, and if the property, by which sorting is executing, is not declared on the source type,
            // but on the Interfaces that this source Interface inherits, than the sorting must be done in the Interface which declares
            // the property by which sorting is executing
            object sortingRows = this.CastSourceRowsToTheProperExpressionType(sortingType, rows);

            ParameterExpression sortingParameter    = Expression.Parameter(sortingType, "p");
            Expression          parameterExpression = Expression.PropertyOrField(sortingParameter, sortingColumn);
            LambdaExpression    sortingExpression   = Expression.Lambda(parameterExpression, new[] { sortingParameter });
            string sortingMethodName = string.Empty;

            switch (sortingDirection)
            {
            case SortingDirection.Ascending:
                sortingMethodName = "OrderBy";
                break;

            case SortingDirection.Descending:
                sortingMethodName = "OrderByDescending";
                break;
            }

            MethodInfo sortingMethod        = typeof(Queryable).GetMethods().Where(m => m.Name.Equals(sortingMethodName)).Where(m => m.GetParameters().Length == 2).Single();
            MethodInfo genericSortingMethod = sortingMethod.MakeGenericMethod(new[] { sortingType, parameterExpression.Type });

            object sortedRows = genericSortingMethod.Invoke(null, new object[] { rows, sortingExpression });

            return(this.CastRowsToTheSourceType(sortingType, sortedRows));
        }
コード例 #27
0
        public static void Sort(XPBaseCollection collection, string property, SortingDirection direction)
        {
            bool isSortingAdded = false;

            foreach (SortProperty sortProperty in collection.Sorting)
            {
                if (sortProperty.Property.Equals(CriteriaOperator.Parse(property)))
                {
                    isSortingAdded = true;
                }
            }
            if (!isSortingAdded)
            {
                collection.Sorting.Add(new SortProperty(property, direction));
            }
        }
コード例 #28
0
        internal void ParsesCorrectly(string query, string[] properties, SortingDirection[] directions)
        {
            var context = new SortingContext(GetQuery(query));
            var expected = properties.Zip(directions, (s, d) => new
            {
                Name = s,
                Direction = d
            }).ToList();
            var actual = context.Properties.Select(p => new
            {
                p.Name,
                p.Direction
            }).ToList();

            Assert.Equal(expected, actual);
        }
        private SortingCollection GetSorting(IEnumerable <GridViewColumnState> sortedColumns, bool isAlwaysSorted)
        {
            SortingCollection sorting = new SortingCollection();

            foreach (GridViewColumnState sortedColumn in sortedColumns)
            {
                SortingDirection sortingDirection = GetSortingDirection(sortedColumn.SortOrder);
                SortProperty     sortProperty     = new SortProperty(sortedColumn.FieldName, sortingDirection);
                sorting.Add(sortProperty);
            }
            if (sorting.Count == 0 && isAlwaysSorted)
            {
                SortProperty sortProperty = new SortProperty(ClassInfo.KeyProperty.Name, SortingDirection.Ascending);
                sorting.Add(sortProperty);
            }
            return(sorting);
        }
コード例 #30
0
ファイル: Task.cs プロジェクト: wh1t3cAt1k/taskman
            public ComparisonStep(
                string propertyName,
                SortingDirection direction = SortingDirection.Ascending)
            {
                this.Property = typeof(Task).GetProperty(
                    propertyName,
                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

                this.Direction = direction;

                if (this.Property == null)
                {
                    throw new TaskManException(
                              Messages.CannotSortNoSuchProperty,
                              propertyName);
                }
            }
コード例 #31
0
 private void IsSorted(int[] sortedInput, SortingDirection sortingDirection)
 {
     if (sortingDirection == SortingDirection.Ascending)
     {
         for (int i = 0; i < sortedInput.Length - 1; i++)
         {
             Assert.LessOrEqual(sortedInput[i], sortedInput[i + 1], "Ascending Sorting is Failed! There is Item in sorted sequence which is more than next one.");
         }
     }
     if (sortingDirection == SortingDirection.Descending)
     {
         for (int i = 0; i < sortedInput.Length - 1; i++)
         {
             Assert.GreaterOrEqual(sortedInput[i], sortedInput[i + 1], "Descending Sorting is Failed! There is Item in sorted sequence which is less than next one.");
         }
     }
 }
コード例 #32
0
 /// <summary>
 /// Adds sorting to query according to parameters from UI
 /// </summary>
 /// <param name="sortField">The sort field.</param>
 /// <param name="sortDirection">The sort direction.</param>
 /// <param name="query">The query to change.</param>
 /// <returns>IQueryable{BonusAggregate}.</returns>
 public IQueryable<BonusAggregate> BuildQuery(string sortField, SortingDirection sortDirection, IQueryable<BonusAggregate> query)
 {
     switch (sortField)
     {
         case "EmployeeLastName":
             query = sortDirection == SortingDirection.Asc
                         ? query.OrderBy(x => x.Employee.LastName)
                         : query.OrderByDescending(x => x.Employee.LastName);
             break;
         case "Date":
             query = sortDirection == SortingDirection.Asc
                         ? query.OrderBy(x => x.Date)
                         : query.OrderByDescending(x => x.Date);
             break;
         case "Amount":
             query = sortDirection == SortingDirection.Asc
                         ? query.OrderBy(x => x.Amount)
                         : query.OrderByDescending(x => x.Amount);
             break;
         case "Comment":
             query = sortDirection == SortingDirection.Asc
                         ? query.OrderBy(x => x.Comment)
                         : query.OrderByDescending(x => x.Comment);
             break;
         case "IsActive":
             query = sortDirection == SortingDirection.Asc
                         ? query.OrderBy(x => x.IsActive)
                         : query.OrderByDescending(x => x.IsActive);
             break;
         case "Ulc":
             query = sortDirection == SortingDirection.Asc
                         ? query.OrderBy(x => x.Ulc)
                         : query.OrderByDescending(x => x.Ulc);
             break;
         case "Dlc":
             query = sortDirection == SortingDirection.Asc
                         ? query.OrderBy(x => x.Dlc)
                         : query.OrderByDescending(x => x.Dlc);
             break;
         default:
             query = query.OrderByDescending(x => x.BonusId);
             break;
     }
     return query;
 }
コード例 #33
0
        private IResourceUrl GetImageUrl(SortingDirection sortingDirection)
        {
            //  Button Asc -> Button Desc -> No Button
            switch (sortingDirection)
            {
            case SortingDirection.Ascending:
                return(ResourceUrlFactory.CreateThemedResourceUrl(typeof(BocColumnRendererBase <>), ResourceType.Image, c_sortAscendingIcon));

            case SortingDirection.Descending:
                return(ResourceUrlFactory.CreateThemedResourceUrl(typeof(BocColumnRendererBase <>), ResourceType.Image, c_sortDescendingIcon));

            case SortingDirection.None:
                return(null);

            default:
                throw new ArgumentOutOfRangeException("sortingDirection");
            }
        }
コード例 #34
0
        public static SortingCollection GetListViewSorting(IModelListView modelListView)
        {
            List <SortProperty> sorting = new List <SortProperty>(modelListView.Columns.Count);

            foreach (IModelColumn column in modelListView.Columns)
            {
                if (column.SortOrder != ColumnSortOrder.None && column.SortIndex >= 0)
                {
                    SortingDirection direction = SortingDirection.Ascending;
                    if (column.SortOrder == ColumnSortOrder.Descending)
                    {
                        direction = SortingDirection.Descending;
                    }
                    sorting.Insert(column.SortIndex, new SortProperty(column.PropertyName, direction));
                }
            }
            return(new SortingCollection(sorting.ToArray()));
        }
コード例 #35
0
        private SingleChart GetContractEnforcementTimeChart(string id, string countryCode, string yearConfig, SortingDirection sortingDirection)
        {
            SingleChart result = null;
            Dictionary<string, Dictionary<string, List<string>>> config;
            DatabaseRepository db;
            IList<GetValuesResult> data;
            IList<int> years;
            int requestedCountryId;
            List<GetIndicatorsInfoResult> indicatorList;
            List<GetCountriesInfo_Result> countryList;
            List<GetSupportedIndicatorsResult> supportedIndicatorList;
            InitChartData(id, countryCode, yearConfig, true, true, false, out db, out data, out years,
                out requestedCountryId, out indicatorList, out countryList, out supportedIndicatorList, out config);

            var chartInfo = db.GetChartInfo(id);
            if (chartInfo != null)
            {
                var countries = countryList.ToDictionary(c => c.CountryId);

                var dataDictionary = data.ToDictionary(
                    d => new Tuple<int, int, int>(d.CountryId, d.IndicatorId, d.Year), d => d.IndicatorValue);

                var supportedIndicatorIds =
                    supportedIndicatorList.Select(s => s.SupportedIndicatorId).Distinct().ToDictionary(i => i);
                var cleanedData = data.Where(d => !supportedIndicatorIds.ContainsKey(d.IndicatorId)).ToList();

                var categoryIds = new List<int>();

                switch (sortingDirection)
                {
                    case SortingDirection.None:
                        categoryIds =
                            data.Select(d => d.CountryId).Distinct().OrderBy(cId => countries[cId].CountryType).ToList();
                        break;
                    case SortingDirection.Asc:
                    case SortingDirection.Desc:
                        GetCategoryOrder(requestedCountryId, cleanedData, countries, countryList, sortingDirection == SortingDirection.Desc, out categoryIds);
                        break;
                }

                List<string> cats;
                List<ChartSeries> sers;
                ConvertToSeries(cleanedData, categoryIds, countryList.ToDictionary(y => y.CountryId, y => y.Name), g => g.Year,
                    SeriesType.Bar,
                    years.ToDictionary(k => k, k => k.ToString()), g => g.CountryId, d => new AdditionalDataPoint { Value = d, AdditionalLabel = null },
                    out cats, out sers);

                foreach (var serie in sers)
                {
                    for (int i = 0; i < serie.Values.Count; i++)
                    {
                        var point = serie.Values[i] as AdditionalDataPoint;
                        decimal? rank;
                        if (
                            dataDictionary.TryGetValue(
                                new Tuple<int, int, int>(countryList[i].CountryId, supportedIndicatorIds.First().Key, serie.Id),
                                out rank))
                        {
                            point.AdditionalLabel = String.Format("Rank: {0}", ((int?)Math.Round(rank.Value)).ToStrWithSuffix());
                        }
                    }
                }

                result = years.Count > 0 ? CreateChart(chartInfo, years.First(), years.Last(), cats, sers) : CreateChart(chartInfo);
                SetStartOrEndValue(result, PointToSet.Min);
                SetStartOrEndValue(result, PointToSet.Max);
            }

            return result;
        }
コード例 #36
0
ファイル: Project1.cs プロジェクト: jdoyleslc/DoyleCode
        //2. Create an overload of method #1 that provides an ascending or descending sorted List<Int32> of all numbers based on an ascending/descending parameter.
        public List<Int32> GetInts(SortingDirection direction)
        {
            var tmpdata = new List<Int32>(mData);
            tmpdata.Sort();

            if (direction == SortingDirection.DESCENDING)
                tmpdata.Reverse();

            return tmpdata;
        }