summaryrefslogtreecommitdiff
path: root/external/aspnetwebstack/src/System.Web.Helpers/WebGrid/WebGrid.cs
blob: d4136d9d14f6ea5c2bdbde102bd92ebde050ec4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.Helpers.Resources;
using System.Web.WebPages;
using Microsoft.Internal.Web.Utils;

namespace System.Web.Helpers
{
    public class WebGrid
    {
        private const string AjaxUpdateScript = "$({1}).swhgLoad({0},{1}{2});";
        private readonly HttpContextBase _context;
        private readonly bool _canPage;
        private readonly bool _canSort;
        private readonly string _ajaxUpdateContainerId;
        private readonly string _ajaxUpdateCallback;
        private readonly string _defaultSort;
        private readonly string _pageFieldName = "page";
        private readonly string _sortDirectionFieldName = "sortdir";
        private readonly string _selectionFieldName = "row";
        private readonly string _sortFieldName = "sort";
        private readonly string _fieldNamePrefix;
        private int _pageIndex = -1;
        private bool _pageIndexSet;
        private int _rowsPerPage;
        private int _selectedIndex = -1;
        private bool _selectedIndexSet;
        private string _sortColumn;
        private bool _sortColumnSet;
        private bool _sortColumnExplicitlySet;
        private SortDirection _sortDirection;
        private bool _sortDirectionSet;
        private IWebGridDataSource _dataSource;
        private bool _dataSourceBound;
        private bool _dataSourceMaterialized;
        private IEnumerable<string> _columnNames;
        private Type _elementType;
        private IList<WebGridRow> _rows;

        /// <param name="source">Data source</param>
        /// <param name="columnNames">Data source column names. Auto-populated by default.</param>
        /// <param name="defaultSort">Default sort column.</param>
        /// <param name="rowsPerPage">Number of rows per page.</param>
        /// <param name="canPage"></param>
        /// <param name="canSort"></param>
        /// <param name="ajaxUpdateContainerId">ID for the grid's container element. This enables AJAX support.</param>
        /// <param name="ajaxUpdateCallback">Callback function for the AJAX functionality once the update is complete</param>
        /// <param name="fieldNamePrefix">Prefix for query string fields to support multiple grids.</param>
        /// <param name="pageFieldName">Query string field name for page number.</param>
        /// <param name="selectionFieldName">Query string field name for selected row number.</param>
        /// <param name="sortFieldName">Query string field name for sort column.</param>
        /// <param name="sortDirectionFieldName">Query string field name for sort direction.</param>
#if CODE_COVERAGE 
        [ExcludeFromCodeCoverage]
#endif
        public WebGrid(
            IEnumerable<dynamic> source = null,
            IEnumerable<string> columnNames = null,
            string defaultSort = null,
            int rowsPerPage = 10,
            bool canPage = true,
            bool canSort = true,
            string ajaxUpdateContainerId = null,
            string ajaxUpdateCallback = null,
            string fieldNamePrefix = null,
            string pageFieldName = null,
            string selectionFieldName = null,
            string sortFieldName = null,
            string sortDirectionFieldName = null)
            : this(new HttpContextWrapper(Web.HttpContext.Current), defaultSort: defaultSort, rowsPerPage: rowsPerPage, canPage: canPage,
                   canSort: canSort, ajaxUpdateContainerId: ajaxUpdateContainerId, ajaxUpdateCallback: ajaxUpdateCallback, fieldNamePrefix: fieldNamePrefix, pageFieldName: pageFieldName,
                   selectionFieldName: selectionFieldName, sortFieldName: sortFieldName, sortDirectionFieldName: sortDirectionFieldName)
        {
            if (source != null)
            {
                Bind(source, columnNames);
            }
        }

        // NOTE: WebGrid uses an IEnumerable<dynamic> data source instead of IEnumerable<T> to avoid generics in the syntax.
        internal WebGrid(
            HttpContextBase context,
            string defaultSort = null,
            int rowsPerPage = 10,
            bool canPage = true,
            bool canSort = true,
            string ajaxUpdateContainerId = null,
            string ajaxUpdateCallback = null,
            string fieldNamePrefix = null,
            string pageFieldName = null,
            string selectionFieldName = null,
            string sortFieldName = null,
            string sortDirectionFieldName = null)
        {
            Debug.Assert(context != null);

            if (rowsPerPage < 1)
            {
                throw new ArgumentOutOfRangeException("rowsPerPage", String.Format(CultureInfo.CurrentCulture,
                                                                                   CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 1));
            }

            _context = context;
            _defaultSort = defaultSort;
            _rowsPerPage = rowsPerPage;
            _canPage = canPage;
            _canSort = canSort;
            _ajaxUpdateContainerId = ajaxUpdateContainerId;
            _ajaxUpdateCallback = ajaxUpdateCallback;

            _fieldNamePrefix = fieldNamePrefix;

            if (!String.IsNullOrEmpty(pageFieldName))
            {
                _pageFieldName = pageFieldName;
            }
            if (!String.IsNullOrEmpty(selectionFieldName))
            {
                _selectionFieldName = selectionFieldName;
            }
            if (!String.IsNullOrEmpty(sortFieldName))
            {
                _sortFieldName = sortFieldName;
            }
            if (!String.IsNullOrEmpty(sortDirectionFieldName))
            {
                _sortDirectionFieldName = sortDirectionFieldName;
            }
        }

        public IEnumerable<string> ColumnNames
        {
            get
            {
                // Review: Assuming that the users always binds the source and provides column names / we infer the default columns names on binding
                // Would not work if we want to allow column names to be independently set.
                EnsureDataBound();
                return _columnNames;
            }
        }

        public bool CanSort
        {
            get { return _canSort; }
        }

        public string AjaxUpdateContainerId
        {
            get { return _ajaxUpdateContainerId; }
        }

        public bool IsAjaxEnabled
        {
            get { return !String.IsNullOrEmpty(_ajaxUpdateContainerId); }
        }

        public string AjaxUpdateCallback
        {
            get { return _ajaxUpdateCallback; }
        }

        public string FieldNamePrefix
        {
            get { return _fieldNamePrefix ?? String.Empty; }
        }

        public bool HasSelection
        {
            get { return SelectedIndex >= 0; }
        }

        public int PageCount
        {
            get
            {
                if (!_canPage)
                {
                    return 1;
                }
                return (int)Math.Ceiling((double)TotalRowCount / RowsPerPage);
            }
        }

        public string PageFieldName
        {
            get { return FieldNamePrefix + _pageFieldName; }
        }

        public int PageIndex
        {
            get
            {
                if (!_canPage)
                {
                    //Default page index is 0
                    return 0;
                }
                if (!_pageIndexSet)
                {
                    int page;
                    if (!_canPage || !Int32.TryParse(QueryString[PageFieldName], out page) || (page < 1))
                    {
                        page = 1;
                    }

                    if (_dataSourceBound && page > PageCount)
                    {
                        page = PageCount;
                    }

                    _pageIndex = page - 1;
                    _pageIndexSet = true;
                }
                return _pageIndex;
            }
            set
            {
                if (!_canPage)
                {
                    throw new NotSupportedException(HelpersResources.WebGrid_NotSupportedIfPagingIsDisabled);
                }

                if (!_dataSourceBound)
                {
                    // Allow the user to specify arbitrary non-negative values before data binding
                    if (value < 0)
                    {
                        throw new ArgumentOutOfRangeException("value", String.Format(CultureInfo.CurrentCulture,
                                                                                     CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));
                    }
                    else
                    {
                        _pageIndex = value;
                        _pageIndexSet = true;
                    }
                }
                else
                {
                    // Once data bound, perform bounds check on the PageIndex. Also ensure the data source has not been materialized.
                    if ((value < 0) || (value >= PageCount))
                    {
                        throw new ArgumentOutOfRangeException("value", String.Format(CultureInfo.CurrentCulture,
                                                                                     CommonResources.Argument_Must_Be_Between, 0, (PageCount - 1)));
                    }
                    else if (value != _pageIndex)
                    {
                        EnsureDataSourceNotMaterialized();
                        _pageIndex = value;
                        _pageIndexSet = true;
                    }
                }
            }
        }

        public IList<WebGridRow> Rows
        {
            get
            {
                EnsureDataBound();
                if (!_dataSourceMaterialized)
                {
                    _rows = _dataSource.GetRows(SortInfo, PageIndex);
                    _dataSourceMaterialized = true;
                }
                return _rows;
            }
        }

        public int RowsPerPage
        {
            get { return _rowsPerPage; }
        }

        public WebGridRow SelectedRow
        {
            get
            {
                if ((SelectedIndex >= 0) && (SelectedIndex < Rows.Count))
                {
                    return Rows[SelectedIndex];
                }
                return null;
            }
        }

        public int SelectedIndex
        {
            get
            {
                if (!_selectedIndexSet)
                {
                    int row;
                    // Range checking should not use Rows.Count since this will cause paging and sorting.
                    // Review: side effect is that HasSelection will return true if Rows.Count (current page's
                    // row count) is less than both SelectedIndex and RowsPerPage. This scenario should only
                    // happen if someone manually modifies the query string.
                    // If paging isn't enabled, this getter isn't doing a upper bounds check on the value.
                    if ((!Int32.TryParse(QueryString[SelectionFieldName], out row)) || (row < 1) || (_canPage && (row > RowsPerPage)))
                    {
                        row = 0;
                    }
                    _selectedIndex = row - 1;
                    _selectedIndexSet = true;
                }
                return _selectedIndex;
            }
            set
            {
                if (_selectedIndex != value)
                {
                    EnsureDataSourceNotMaterialized();
                    _selectedIndex = value;
                }
                _selectedIndexSet = true;
            }
        }

        public string SelectionFieldName
        {
            get { return FieldNamePrefix + _selectionFieldName; }
        }

        public string SortColumn
        {
            get
            {
                if (!_sortColumnSet)
                {
                    string sortColumn = QueryString[SortFieldName];
                    if (!_dataSourceBound || ValidateSortColumn(sortColumn))
                    {
                        _sortColumn = sortColumn;
                        _sortColumnSet = true;
                    }
                }
                if (String.IsNullOrEmpty(_sortColumn))
                {
                    return _defaultSort ?? String.Empty;
                }
                return _sortColumn;
            }
            set
            {
                EnsureDataBound();
                if (!SortColumn.Equals(value, StringComparison.OrdinalIgnoreCase))
                {
                    EnsureDataSourceNotMaterialized();
                    _sortColumn = value;
                }
                _sortColumnSet = true;
                _sortColumnExplicitlySet = true;
            }
        }

        public SortDirection SortDirection
        {
            get
            {
                if (!_sortDirectionSet)
                {
                    string sortDirection = QueryString[SortDirectionFieldName];
                    if (sortDirection != null)
                    {
                        if (sortDirection.Equals("DESC", StringComparison.OrdinalIgnoreCase) ||
                            sortDirection.Equals("DESCENDING", StringComparison.OrdinalIgnoreCase))
                        {
                            _sortDirection = SortDirection.Descending;
                        }
                    }
                    _sortDirectionSet = true;
                }
                return _sortDirection;
            }
            set
            {
                if (!_dataSourceBound)
                {
                    _sortDirection = value;
                }
                else if (_sortDirection != value)
                {
                    EnsureDataSourceNotMaterialized();
                    _sortDirection = value;
                }
                _sortDirectionSet = true;
            }
        }

        private SortInfo SortInfo
        {
            get { return new SortInfo { SortColumn = SortColumn, SortDirection = SortDirection }; }
        }

        public string SortDirectionFieldName
        {
            get { return FieldNamePrefix + _sortDirectionFieldName; }
        }

        public string SortFieldName
        {
            get { return FieldNamePrefix + _sortFieldName; }
        }

        public int TotalRowCount
        {
            get
            {
                EnsureDataBound();
                return _dataSource.TotalRowCount;
            }
        }

        private HttpContextBase HttpContext
        {
            get { return _context; }
        }

        private NameValueCollection QueryString
        {
            get { return HttpContext.Request.QueryString; }
        }

        internal static Type GetElementType(IEnumerable<dynamic> source)
        {
            Debug.Assert(source != null, "source cannot be null");
            Type sourceType = source.GetType();

            if (source.FirstOrDefault() is IDynamicMetaObjectProvider)
            {
                return typeof(IDynamicMetaObjectProvider);
            }
            else if (sourceType.IsArray)
            {
                return sourceType.GetElementType();
            }
            Type elementType = sourceType.GetInterfaces().Select(GetGenericEnumerableType).FirstOrDefault(t => t != null);

            Debug.Assert(elementType != null);
            return elementType;
        }

        private static Type GetGenericEnumerableType(Type type)
        {
            Type enumerableType = typeof(IEnumerable<>);
            if (type.IsGenericType && enumerableType.IsAssignableFrom(type.GetGenericTypeDefinition()))
            {
                return type.GetGenericArguments()[0];
            }
            return null;
        }

        public WebGrid Bind(IEnumerable<dynamic> source, IEnumerable<string> columnNames = null, bool autoSortAndPage = true, int rowCount = -1)
        {
            if (_dataSourceBound)
            {
                throw new InvalidOperationException(HelpersResources.WebGrid_DataSourceBound);
            }
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (!autoSortAndPage && _canPage && rowCount == -1)
            {
                throw new ArgumentException(HelpersResources.WebGrid_RowCountNotSpecified, "rowCount");
            }

            _elementType = GetElementType(source);
            if (_columnNames == null)
            {
                _columnNames = columnNames ?? GetDefaultColumnNames(source, elementType: _elementType);
            }

            if (!autoSortAndPage)
            {
                _dataSource = new PreComputedGridDataSource(grid: this, values: source, totalRows: rowCount);
            }
            else
            {
                WebGridDataSource dataSource = new WebGridDataSource(grid: this, values: source, elementType: _elementType, canPage: _canPage, canSort: _canSort);
                dataSource.DefaultSort = new SortInfo { SortColumn = _defaultSort, SortDirection = SortDirection.Ascending };
                dataSource.RowsPerPage = _rowsPerPage;
                _dataSource = dataSource;
            }
            _dataSourceBound = true;
            ValidatePreDataBoundValues();
            return this;
        }

        // todo: add templating from file support
        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Non-static for syntax, and in case we want to check column existence.")]
        public WebGridColumn Column(string columnName = null, string header = null, Func<dynamic, object> format = null, string style = null,
                                    bool canSort = true)
        {
            if (String.IsNullOrEmpty(columnName))
            {
                if (format == null)
                {
                    throw new ArgumentException(HelpersResources.WebGrid_ColumnNameOrFormatRequired, "columnName");
                }
            }

            return new WebGridColumn { ColumnName = columnName, Header = header, Format = format, Style = style, CanSort = canSort };
        }

        // Should we keep this no-op API for improved WebGrid syntax? Alternatives are:
        // 1. columns: grid.Columns(
        //        grid.Column(...), grid.Column(...)
        //    )
        // 2. columns: new[] {
        //        grid.Column(...), grid.Column(...)
        //    }
        [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Review: No-op API for syntax simplification?")]
        public WebGridColumn[] Columns(params WebGridColumn[] columnSet)
        {
            return columnSet;
        }

        public IHtmlString GetContainerUpdateScript(string path)
        {
            var script = String.Format(CultureInfo.InvariantCulture, AjaxUpdateScript,
                                       HttpUtility.JavaScriptStringEncode(path, addDoubleQuotes: true),
                                       HttpUtility.JavaScriptStringEncode('#' + AjaxUpdateContainerId, addDoubleQuotes: true),
                                       !String.IsNullOrEmpty(AjaxUpdateCallback) ? ',' + HttpUtility.JavaScriptStringEncode(AjaxUpdateCallback) : String.Empty);

            return new HtmlString(HttpUtility.HtmlAttributeEncode(script));
        }

        /// <summary>
        /// Gets the HTML for a table with a pager.
        /// </summary>
        /// <param name="tableStyle">Table class for styling.</param>
        /// <param name="headerStyle">Header row class for styling.</param>
        /// <param name="footerStyle">Footer row class for styling.</param>
        /// <param name="rowStyle">Row class for styling (odd rows only).</param>
        /// <param name="alternatingRowStyle">Row class for styling (even rows only).</param>
        /// <param name="selectedRowStyle">Selected row class for styling.</param>
        /// <param name="displayHeader">Whether the header row should be displayed.</param>
        /// <param name="caption">The string displayed as the table caption</param>
        /// <param name="fillEmptyRows">Whether the table can add empty rows to ensure the rowsPerPage row count.</param>
        /// <param name="emptyRowCellValue">Value used to populate empty rows. This property is only used when <paramref name="fillEmptyRows"/> is set</param>
        /// <param name="columns">Column model for customizing column rendering.</param>
        /// <param name="exclusions">Columns to exclude when auto-populating columns.</param>
        /// <param name="mode">Modes for pager rendering.</param>
        /// <param name="firstText">Text for link to first page.</param>
        /// <param name="previousText">Text for link to previous page.</param>
        /// <param name="nextText">Text for link to next page.</param>
        /// <param name="lastText">Text for link to last page.</param>
        /// <param name="numericLinksCount">Number of numeric links that should display.</param>
        /// <param name="htmlAttributes">An object that contains the HTML attributes to set for the element.</param>
        public IHtmlString GetHtml(
            string tableStyle = null,
            string headerStyle = null,
            string footerStyle = null,
            string rowStyle = null,
            string alternatingRowStyle = null,
            string selectedRowStyle = null,
            string caption = null,
            bool displayHeader = true,
            bool fillEmptyRows = false,
            string emptyRowCellValue = null,
            IEnumerable<WebGridColumn> columns = null,
            IEnumerable<string> exclusions = null,
            WebGridPagerModes mode = WebGridPagerModes.NextPrevious | WebGridPagerModes.Numeric,
            string firstText = null,
            string previousText = null,
            string nextText = null,
            string lastText = null,
            int numericLinksCount = 5,
            object htmlAttributes = null)
        {
            Func<dynamic, object> footer = null;
            if (_canPage && (PageCount > 1))
            {
                footer = item => Pager(mode, firstText, previousText, nextText, lastText, numericLinksCount, explicitlyCalled: false);
            }

            return Table(tableStyle, headerStyle, footerStyle, rowStyle, alternatingRowStyle, selectedRowStyle, caption, displayHeader,
                         fillEmptyRows, emptyRowCellValue, columns, exclusions, footer: footer,
                         htmlAttributes: htmlAttributes);
        }

        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Strings are easier for Plan9 developer to work with")]
        public string GetPageUrl(int pageIndex)
        {
            if (!_canPage)
            {
                throw new NotSupportedException(HelpersResources.WebGrid_NotSupportedIfPagingIsDisabled);
            }
            if ((pageIndex < 0) || (pageIndex >= PageCount))
            {
                throw new ArgumentOutOfRangeException("pageIndex", String.Format(CultureInfo.CurrentCulture,
                                                                                 CommonResources.Argument_Must_Be_Between, 0, (PageCount - 1)));
            }

            NameValueCollection queryString = new NameValueCollection(1);
            queryString[PageFieldName] = (pageIndex + 1L).ToString(CultureInfo.CurrentCulture);
            return GetPath(queryString, SelectionFieldName);
        }

        [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Strings are easier for Plan9 developer to work with")]
        public string GetSortUrl(string column)
        {
            if (!_canSort)
            {
                throw new NotSupportedException(HelpersResources.WebGrid_NotSupportedIfSortingIsDisabled);
            }
            if (String.IsNullOrEmpty(column))
            {
                throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "column");
            }

            var sort = SortColumn;
            var sortDir = SortDirection.Ascending;
            if (column.Equals(sort, StringComparison.OrdinalIgnoreCase))
            {
                if (SortDirection == SortDirection.Ascending)
                {
                    sortDir = SortDirection.Descending;
                }
            }

            NameValueCollection queryString = new NameValueCollection(2);
            queryString[SortFieldName] = column;
            queryString[SortDirectionFieldName] = GetSortDirectionString(sortDir);
            return GetPath(queryString, PageFieldName, SelectionFieldName);
        }

        /// <summary>
        /// Gets the HTML for a pager.
        /// </summary>
        /// <param name="mode">Modes for pager rendering.</param>
        /// <param name="firstText">Text for link to first page.</param>
        /// <param name="previousText">Text for link to previous page.</param>
        /// <param name="nextText">Text for link to next page.</param>
        /// <param name="lastText">Text for link to last page.</param>
        /// <param name="numericLinksCount">Number of numeric links that should display.</param>
        public HelperResult Pager(
            WebGridPagerModes mode = WebGridPagerModes.NextPrevious | WebGridPagerModes.Numeric,
            string firstText = null,
            string previousText = null,
            string nextText = null,
            string lastText = null,
            int numericLinksCount = 5)
        {
            return Pager(mode, firstText, previousText, nextText, lastText, numericLinksCount, explicitlyCalled: true);
        }

        /// <param name="mode">Modes for pager rendering.</param>
        /// <param name="firstText">Text for link to first page.</param>
        /// <param name="previousText">Text for link to previous page.</param>
        /// <param name="nextText">Text for link to next page.</param>
        /// <param name="lastText">Text for link to last page.</param>
        /// <param name="numericLinksCount">Number of numeric links that should display.</param>
        /// <param name="explicitlyCalled">The Pager can be explicitly called by the public API or is called by the WebGrid when no footer is provided.
        /// In the explicit scenario, we would need to render a container for the pager to allow identifying the pager links.
        /// In the implicit scenario, the grid table would be the container.
        /// </param>
        private HelperResult Pager(
            WebGridPagerModes mode,
            string firstText,
            string previousText,
            string nextText,
            string lastText,
            int numericLinksCount,
            bool explicitlyCalled)
        {
            if (!_canPage)
            {
                throw new NotSupportedException(HelpersResources.WebGrid_NotSupportedIfPagingIsDisabled);
            }
            if (!ModeEnabled(mode, WebGridPagerModes.FirstLast) && (firstText != null))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
                                                          HelpersResources.WebGrid_PagerModeMustBeEnabled, "FirstLast"), "firstText");
            }
            if (!ModeEnabled(mode, WebGridPagerModes.NextPrevious) && (previousText != null))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
                                                          HelpersResources.WebGrid_PagerModeMustBeEnabled, "NextPrevious"), "previousText");
            }
            if (!ModeEnabled(mode, WebGridPagerModes.NextPrevious) && (nextText != null))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
                                                          HelpersResources.WebGrid_PagerModeMustBeEnabled, "NextPrevious"), "nextText");
            }
            if (!ModeEnabled(mode, WebGridPagerModes.FirstLast) && (lastText != null))
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
                                                          HelpersResources.WebGrid_PagerModeMustBeEnabled, "FirstLast"), "lastText");
            }
            if (numericLinksCount < 0)
            {
                throw new ArgumentOutOfRangeException("numericLinksCount",
                                                      String.Format(CultureInfo.CurrentCulture, CommonResources.Argument_Must_Be_GreaterThanOrEqualTo, 0));
            }

            return WebGridRenderer.Pager(this, HttpContext, mode: mode, firstText: firstText, previousText: previousText, nextText: nextText, lastText: lastText,
                                         numericLinksCount: numericLinksCount, renderAjaxContainer: explicitlyCalled);
        }

        /// <summary>
        /// Gets the HTML for a table with a pager.
        /// </summary>
        /// <param name="tableStyle">Table class for styling.</param>
        /// <param name="headerStyle">Header row class for styling.</param>
        /// <param name="footerStyle">Footer row class for styling.</param>
        /// <param name="rowStyle">Row class for styling (odd rows only).</param>
        /// <param name="alternatingRowStyle">Row class for styling (even rows only).</param>
        /// <param name="selectedRowStyle">Selected row class for styling.</param>
        /// <param name="caption">The table caption</param>
        /// <param name="displayHeader">Whether the header row should be displayed.</param>
        /// <param name="fillEmptyRows">Whether the table can add empty rows to ensure the rowsPerPage row count.</param>
        /// <param name="emptyRowCellValue">Value used to populate empty rows. This property is only used when <paramref name="fillEmptyRows"/> is set</param>
        /// <param name="columns">Column model for customizing column rendering.</param>
        /// <param name="exclusions">Columns to exclude when auto-populating columns.</param>
        /// <param name="footer">Table footer template.</param>
        /// <param name="htmlAttributes">An object that contains the HTML attributes to set for the element.</param>
        public IHtmlString Table(
            string tableStyle = null,
            string headerStyle = null,
            string footerStyle = null,
            string rowStyle = null,
            string alternatingRowStyle = null,
            string selectedRowStyle = null,
            string caption = null,
            bool displayHeader = true,
            bool fillEmptyRows = false,
            string emptyRowCellValue = null,
            IEnumerable<WebGridColumn> columns = null,
            IEnumerable<string> exclusions = null,
            Func<dynamic, object> footer = null,
            object htmlAttributes = null)
        {
            if (columns == null)
            {
                columns = GetDefaultColumns(exclusions);
            }
            // In order of precedence, the parameters that affect the visibility of columns in WebGrid - 
            // (1) "columns" argument of this method 
            // (2) "exclusion" argument of this method 
            // (3) "columnNames" argument of the constructor. 
            // At the time of binding we can verify if a simple property specified in the query string is a column that would be visible to the user. 
            // However, for complex properties or if either of (1) or (2) arguments are specified, we can only verify at this point. 
            EnsureColumnIsSortable(columns);

            if (emptyRowCellValue == null)
            {
                emptyRowCellValue = "&nbsp;";
            }

            return WebGridRenderer.Table(this, HttpContext, tableStyle: tableStyle, headerStyle: headerStyle, footerStyle: footerStyle, rowStyle: rowStyle,
                                         alternatingRowStyle: alternatingRowStyle, selectedRowStyle: selectedRowStyle, caption: caption, displayHeader: displayHeader, fillEmptyRows: fillEmptyRows,
                                         emptyRowCellValue: emptyRowCellValue, columns: columns, exclusions: exclusions, footer: footer, htmlAttributes: htmlAttributes);
        }

        /// <param name="columns">The set of columns that are rendered to the client.</param>
        private void EnsureColumnIsSortable(IEnumerable<WebGridColumn> columns)
        {
            // Fix for bug 941102
            // The ValidateSortColumn can validate a few regular cases for sorting and reset those values to default. However, for sort columns that are complex expressions,
            // or if the user specifies a subset of columns in the GetHtml method (via columns / exclusions), the method is ineffective. 
            // Review: Should this method not throw if the data was not explicitly sorted and paged by the user
            if (_canSort && !_sortColumnExplicitlySet && !String.IsNullOrEmpty(SortColumn) && !StringComparer.OrdinalIgnoreCase.Equals(_defaultSort, SortColumn)
                && !columns.Select(c => c.ColumnName).Contains(SortColumn, StringComparer.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, HelpersResources.WebGrid_ColumnNotFound, SortColumn));
            }
        }

        internal static dynamic GetMember(WebGridRow row, string name)
        {
            object result;
            if (row.TryGetMember(name, out result))
            {
                return result;
            }
            throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture,
                                                              HelpersResources.WebGrid_ColumnNotFound, name));
        }

        // review: make sure this is ordered
        internal string GetPath(NameValueCollection queryString, params string[] exclusions)
        {
            NameValueCollection temp = new NameValueCollection(QueryString);
            // update current query string in case values were set programmatically
            if (temp.AllKeys.Contains(PageFieldName))
            {
                temp.Set(PageFieldName, (PageIndex + 1L).ToString(CultureInfo.CurrentCulture));
            }
            if (temp.AllKeys.Contains(SelectionFieldName))
            {
                if (SelectedIndex < 0)
                {
                    temp.Remove(SelectionFieldName);
                }
                else
                {
                    temp.Set(SelectionFieldName, (SelectedIndex + 1L).ToString(CultureInfo.CurrentCulture));
                }
            }
            if (temp.AllKeys.Contains(SortFieldName))
            {
                if (String.IsNullOrEmpty(SortColumn))
                {
                    temp.Remove(SortFieldName);
                }
                else
                {
                    temp.Set(SortFieldName, SortColumn);
                }
            }
            if (temp.AllKeys.Contains(SortDirectionFieldName))
            {
                temp.Set(SortDirectionFieldName, GetSortDirectionString(SortDirection));
            }

            // remove fields from exclusions list
            foreach (var key in exclusions)
            {
                temp.Remove(key);
            }
            // replace with new field values
            foreach (string key in queryString.Keys)
            {
                temp.Set(key, queryString[key]);
            }
            queryString = temp;

            StringBuilder sb = new StringBuilder(HttpContext.Request.Path);

            sb.Append("?");
            for (int i = 0; i < queryString.Count; i++)
            {
                if (i > 0)
                {
                    sb.Append("&");
                }
                sb.Append(HttpUtility.UrlEncode(queryString.Keys[i]));
                sb.Append("=");
                sb.Append(HttpUtility.UrlEncode(queryString[i]));
            }
            return sb.ToString();
        }

        internal static string GetSortDirectionString(SortDirection sortDir)
        {
            return (sortDir == SortDirection.Ascending) ? "ASC" : "DESC";
        }

        private void EnsureDataBound()
        {
            if (!_dataSourceBound)
            {
                throw new InvalidOperationException(HelpersResources.WebGrid_NoDataSourceBound);
            }
        }

        private void EnsureDataSourceNotMaterialized()
        {
            if (_dataSourceMaterialized)
            {
                throw new InvalidOperationException(HelpersResources.WebGrid_PropertySetterNotSupportedAfterDataBound);
            }
        }

        private void ValidatePreDataBoundValues()
        {
            if (_canPage && _pageIndexSet && PageIndex > PageCount)
            {
                PageIndex = PageCount;
            }
            else if (_canSort && _sortColumnSet && !ValidateSortColumn(SortColumn))
            {
                SortColumn = _defaultSort;
            }
        }

        private bool ValidateSortColumn(string value)
        {
            Debug.Assert(ColumnNames != null);

            // Navigation columns that contain '.' will be validated during the Sort operation
            // Validate other properties up-front and ignore any bad columns passed via the query string
            return _sortColumnExplicitlySet
                   || String.IsNullOrEmpty(value)
                   || StringComparer.OrdinalIgnoreCase.Equals(_defaultSort, value)
                   || ColumnNames.Contains(value, StringComparer.OrdinalIgnoreCase)
                   || value.Contains('.');
        }

        private static IEnumerable<string> GetDefaultColumnNames(IEnumerable<dynamic> source, Type elementType)
        {
            var dynObj = source.FirstOrDefault() as IDynamicMetaObjectProvider;
            if (dynObj != null)
            {
                return DynamicHelper.GetMemberNames(dynObj);
            }
            else
            {
                return (from p in elementType.GetProperties()
                        where IsBindableType(p.PropertyType) && (p.GetIndexParameters().Length == 0)
                        select p.Name).OrderBy(n => n, StringComparer.OrdinalIgnoreCase).ToArray();
            }
        }

        private IEnumerable<WebGridColumn> GetDefaultColumns(IEnumerable<string> exclusions)
        {
            IEnumerable<string> names = ColumnNames;
            if (exclusions != null)
            {
                names = names.Except(exclusions);
            }
            return (from n in names
                    select new WebGridColumn { ColumnName = n, CanSort = true }).ToArray();
        }

        // see: DataBoundControlHelper.IsBindableType
        private static bool IsBindableType(Type type)
        {
            Debug.Assert(type != null);

            Type underlyingType = Nullable.GetUnderlyingType(type);
            if (underlyingType != null)
            {
                type = underlyingType;
            }
            return (type.IsPrimitive ||
                    type.Equals(typeof(string)) ||
                    type.Equals(typeof(DateTime)) ||
                    type.Equals(typeof(Decimal)) ||
                    type.Equals(typeof(Guid)) ||
                    type.Equals(typeof(DateTimeOffset)) ||
                    type.Equals(typeof(TimeSpan)));
        }

        private static bool ModeEnabled(WebGridPagerModes mode, WebGridPagerModes modeCheck)
        {
            return (mode & modeCheck) == modeCheck;
        }
    }
}