PageRenderTime 55ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/CMSAdminControls/UI/UniGrid/UniGrid.ascx.cs

https://bitbucket.org/mchudo89/cms.io.rackspace-with-kentico
C# | 2818 lines | 1963 code | 388 blank | 467 comment | 394 complexity | 7cd997de0b11da87452ab4c9c81277d1 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Data;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. using System.Web;
  8. using System.Web.UI;
  9. using System.Web.UI.WebControls;
  10. using System.Xml;
  11. using CMS.CMSHelper;
  12. using CMS.Controls;
  13. using CMS.DataEngine;
  14. using CMS.EventLog;
  15. using CMS.ExtendedControls;
  16. using CMS.FormControls;
  17. using CMS.FormEngine;
  18. using CMS.GlobalHelper;
  19. using CMS.IO;
  20. using CMS.SettingsProvider;
  21. using CMS.UIControls;
  22. using CMS.UIControls.UniGridConfig;
  23. using CMS.URLRewritingEngine;
  24. using Action = CMS.UIControls.UniGridConfig.Action;
  25. public partial class CMSAdminControls_UI_UniGrid_UniGrid : UniGrid, IUniPageable
  26. {
  27. #region "Constants"
  28. private const int halfPageCountLimit = 1000;
  29. #endregion
  30. #region "Variables"
  31. private Button showButton = null;
  32. private int rowIndex = 1;
  33. private bool resetSelection = false;
  34. private bool visiblePagesSet = false;
  35. private static string DEFAULT_ACTIONS_MENU = "~/CMSAdminControls/UI/UniGrid/Controls/UniGridMenu.ascx";
  36. private bool mShowObjectMenu = true;
  37. private bool mCheckRelative = false;
  38. #endregion
  39. #region "Properties"
  40. /// <summary>
  41. /// Indicates if control is used on live site
  42. /// </summary>
  43. public override bool IsLiveSite
  44. {
  45. get
  46. {
  47. return base.IsLiveSite;
  48. }
  49. set
  50. {
  51. base.IsLiveSite = value;
  52. plcMess.IsLiveSite = value;
  53. }
  54. }
  55. /// <summary>
  56. /// Messages placeholder
  57. /// </summary>
  58. public override MessagesPlaceHolder MessagesPlaceHolder
  59. {
  60. get
  61. {
  62. return plcMess;
  63. }
  64. }
  65. /// <summary>
  66. /// Gets or sets GridView control of UniGrid.
  67. /// </summary>
  68. public override GridView GridView
  69. {
  70. get
  71. {
  72. return UniGridView;
  73. }
  74. }
  75. /// <summary>
  76. /// Hidden field containing selected items.
  77. /// </summary>
  78. public override HiddenField SelectionHiddenField
  79. {
  80. get
  81. {
  82. return hidSelection;
  83. }
  84. }
  85. /// <summary>
  86. /// Gets or sets UniGrid pager control of UniGrid.
  87. /// </summary>
  88. public override UniGridPager Pager
  89. {
  90. get
  91. {
  92. return pagerElem;
  93. }
  94. }
  95. /// <summary>
  96. /// If true, relative ancestor div is checked in context menu
  97. /// </summary>
  98. public bool CheckRelative
  99. {
  100. get
  101. {
  102. return mCheckRelative;
  103. }
  104. set
  105. {
  106. mCheckRelative = value;
  107. }
  108. }
  109. /// <summary>
  110. /// Gets selected items from UniGrid.
  111. /// </summary>
  112. public override List<string> SelectedItems
  113. {
  114. get
  115. {
  116. return GetSelectedItems();
  117. }
  118. set
  119. {
  120. SetSectedItems(value);
  121. }
  122. }
  123. /// <summary>
  124. /// Gets selected items from UniGrid.
  125. /// </summary>
  126. public override List<string> DeselectedItems
  127. {
  128. get
  129. {
  130. return GetDeselectedItems();
  131. }
  132. }
  133. /// <summary>
  134. /// Gets selected items from UniGrid.
  135. /// </summary>
  136. public override List<string> NewlySelectedItems
  137. {
  138. get
  139. {
  140. return GetNewlySelectedItems();
  141. }
  142. }
  143. /// <summary>
  144. /// Gets filter placeHolder from Unigrid.
  145. /// </summary>
  146. public override PlaceHolder FilterPlaceHolder
  147. {
  148. get
  149. {
  150. return filter;
  151. }
  152. }
  153. /// <summary>
  154. /// Gets page size dropdown from Unigrid Pager.
  155. /// </summary>
  156. public override DropDownList PageSizeDropdown
  157. {
  158. get
  159. {
  160. return Pager.PageSizeDropdown;
  161. }
  162. }
  163. /// <summary>
  164. /// Defines whether to show object menu (menu containing relationships, export/backup, destroy object, ... functionality)
  165. /// </summary>
  166. public bool ShowObjectMenu
  167. {
  168. get
  169. {
  170. return mShowObjectMenu;
  171. }
  172. set
  173. {
  174. mShowObjectMenu = value;
  175. }
  176. }
  177. /// <summary>
  178. /// Gets filter form.
  179. /// </summary>
  180. public override BasicForm FilterForm
  181. {
  182. get
  183. {
  184. return filterForm;
  185. }
  186. }
  187. #endregion
  188. #region "Page events"
  189. /// <summary>
  190. /// Control's init event handler.
  191. /// </summary>
  192. protected void Page_Init(object sender, EventArgs e)
  193. {
  194. advancedExportElem.UniGrid = this;
  195. }
  196. /// <summary>
  197. /// Control's load event handler.
  198. /// </summary>
  199. protected void Page_Load(object sender, EventArgs e)
  200. {
  201. if (StopProcessing)
  202. {
  203. Visible = false;
  204. FilterForm.StopProcessing = true;
  205. }
  206. else
  207. {
  208. SetPager();
  209. if (LoadGridDefinition())
  210. {
  211. // Do not load on callback
  212. if (!RequestHelper.IsCallback())
  213. {
  214. ActionsHidden = hidActions;
  215. ActionsHashHidden = hidActionsHash;
  216. // Check whether current request is row action command and if so, raise action
  217. if (!String.IsNullOrEmpty(hidCmdName.Value) && (Request.Form["__EVENTTARGET"] == UniqueID) && ((Request.Form["__EVENTARGUMENT"] == "UniGridAction")))
  218. {
  219. HandleAction(hidCmdName.Value, hidCmdArg.Value);
  220. }
  221. // Set order by clause
  222. ProcessSorting();
  223. // Set filter form
  224. if (!string.IsNullOrEmpty(FilterFormName))
  225. {
  226. SetBasicFormFilter();
  227. if (!EventRequest() && !DelayedReload)
  228. {
  229. ReloadData();
  230. }
  231. }
  232. // Get data from database and set them to the grid view
  233. else if (FilterByQueryString)
  234. {
  235. if (displayFilter)
  236. {
  237. SetFilter(true);
  238. }
  239. else
  240. {
  241. if (!EventRequest() && !DelayedReload)
  242. {
  243. ReloadData();
  244. }
  245. }
  246. }
  247. else
  248. {
  249. // Load the default filter value
  250. if (!RequestHelper.IsPostBack() && displayFilter)
  251. {
  252. SetFilter(true);
  253. }
  254. else if (!EventRequest() && !DelayedReload)
  255. {
  256. ReloadData();
  257. }
  258. }
  259. }
  260. }
  261. }
  262. // Clear hidden action on load event. If unigrid is invisible, page pre render is not fired
  263. ClearActions();
  264. }
  265. /// <summary>
  266. /// Control's PreRender event handler.
  267. /// </summary>
  268. protected override void OnPreRender(EventArgs e)
  269. {
  270. base.OnPreRender(e);
  271. if (FilterIsSet)
  272. {
  273. // Check for FilteredZeroRowsText
  274. if ((GridView.Rows.Count == 0) && !String.IsNullOrEmpty(FilteredZeroRowsText))
  275. {
  276. // Display filter zero rows text
  277. lblInfo.Text = FilteredZeroRowsText;
  278. lblInfo.Visible = true;
  279. pagerElem.Visible = false;
  280. }
  281. else
  282. {
  283. lblInfo.Visible = false;
  284. pagerElem.Visible = true;
  285. }
  286. }
  287. else
  288. {
  289. // Check for ZeroRowsText
  290. if (GridView.Rows.Count == 0)
  291. {
  292. if (!HideControlForZeroRows && !String.IsNullOrEmpty(ZeroRowsText))
  293. {
  294. // Display zero rows text
  295. lblInfo.Text = ZeroRowsText;
  296. lblInfo.Visible = true;
  297. pagerElem.Visible = false;
  298. // Check additional filter visibility
  299. CheckFilterVisibility();
  300. }
  301. else
  302. {
  303. lblInfo.Visible = false;
  304. pagerElem.Visible = false;
  305. filter.Visible = false;
  306. }
  307. }
  308. else
  309. {
  310. lblInfo.Visible = false;
  311. pagerElem.Visible = true;
  312. // Check additional filter visibility
  313. CheckFilterVisibility();
  314. }
  315. }
  316. if (Visible && !StopProcessing)
  317. {
  318. RegisterCmdScripts();
  319. }
  320. if (Pager.CurrentPage > halfPageCountLimit)
  321. {
  322. // Enlarge direct page textbox
  323. TextBox txtPage = ControlsHelper.GetChildControl(pagerElem, typeof(TextBox), "txtPage") as TextBox;
  324. if (txtPage != null)
  325. {
  326. txtPage.Style.Add(HtmlTextWriterStyle.Width, "50px");
  327. }
  328. }
  329. advancedExportElem.Visible = ShowActionsMenu;
  330. // Hide info label when error message is displayed
  331. lblInfo.Visible = lblInfo.Visible && string.IsNullOrEmpty(plcMess.ErrorText);
  332. }
  333. #endregion
  334. #region "Public methods"
  335. /// <summary>
  336. /// Clears UniGrid's information on recently performed action. Under normal circumstances there is no need to perform this action.
  337. /// However sometimes forcing grid to clear the actions is required.
  338. /// </summary>
  339. public void ClearActions()
  340. {
  341. // Clear hidden fields
  342. hidCmdName.Value = null;
  343. hidCmdArg.Value = null;
  344. }
  345. /// <summary>
  346. /// Clears all selected items from hidden values.
  347. /// </summary>
  348. public void ClearSelectedItems()
  349. {
  350. ClearHiddenValues(SelectionHiddenField);
  351. }
  352. /// <summary>
  353. /// Loads the XML configuration of the grid.
  354. /// </summary>
  355. public bool LoadXmlConfiguration()
  356. {
  357. // If no configuration is given, do not process
  358. if (string.IsNullOrEmpty(GridName))
  359. {
  360. return true;
  361. }
  362. string xmlFilePath = Server.MapPath(GridName);
  363. // Check the configuration file
  364. if (!File.Exists(xmlFilePath))
  365. {
  366. ShowError(String.Format(GetString("unigrid.noxmlfile"), xmlFilePath));
  367. return false;
  368. }
  369. // Load the XML configuration
  370. XmlDocument document = new XmlDocument();
  371. document.Load(xmlFilePath);
  372. XmlNode node = document.DocumentElement;
  373. if (node != null)
  374. {
  375. // Load options definition
  376. XmlNode optionNode = node.SelectSingleNode("options");
  377. if (optionNode != null)
  378. {
  379. GridOptions = new UniGridOptions(optionNode);
  380. }
  381. // Load actions definition
  382. XmlNode actionsNode = node.SelectSingleNode("actions");
  383. if (actionsNode != null)
  384. {
  385. GridActions = new UniGridActions(actionsNode);
  386. }
  387. // Load pager definition
  388. XmlNode pagerNode = node.SelectSingleNode("pager");
  389. if (pagerNode != null)
  390. {
  391. PagerConfig = new UniGridPagerConfig(pagerNode);
  392. }
  393. // Select list of "column" nodes
  394. XmlNode columnsNode = node.SelectSingleNode("columns");
  395. if (columnsNode != null)
  396. {
  397. GridColumns = new UniGridColumns(columnsNode);
  398. }
  399. // Try to get ObjectType from definition
  400. XmlNode objectTypeNode = node.SelectSingleNode("objecttype");
  401. if (objectTypeNode != null)
  402. {
  403. // Get object type information
  404. LoadObjectTypeDefinition(objectTypeNode);
  405. }
  406. else
  407. {
  408. // Get query information
  409. XmlNode queryNode = node.SelectSingleNode("query");
  410. LoadQueryDefinition(queryNode);
  411. }
  412. return true;
  413. }
  414. return false;
  415. }
  416. /// <summary>
  417. /// Loads the grid definition.
  418. /// </summary>
  419. public override bool LoadGridDefinition()
  420. {
  421. if (GridView.Columns.Count == 0)
  422. {
  423. using (Table filterTable = new Table())
  424. {
  425. filterTable.CssClass = "UniGridFilterTable";
  426. filter.Controls.Clear();
  427. // Clear all columns from the grid view
  428. UniGridView.Columns.Clear();
  429. UniGridView.GridLines = GridLines.Horizontal;
  430. if (!LoadXmlConfiguration())
  431. {
  432. return false;
  433. }
  434. // Load options
  435. if (GridOptions != null)
  436. {
  437. LoadOptionsDefinition(GridOptions, filterTable);
  438. }
  439. if (GridActions == null && ShowActionsMenu)
  440. {
  441. EmptyAction emptyAction = new EmptyAction();
  442. GridActions = new UniGridActions();
  443. GridActions.Actions.Add(emptyAction);
  444. }
  445. // Actions
  446. if (GridActions != null)
  447. {
  448. LoadActionsDefinition(GridActions);
  449. }
  450. // Load pager configuration
  451. if (PagerConfig != null)
  452. {
  453. LoadPagerDefinition(PagerConfig);
  454. }
  455. // Set direct page control id from viewstate
  456. if (ViewState["DirectPageControlID"] != null)
  457. {
  458. Pager.DirectPageControlID = ViewState["DirectPageControlID"].ToString();
  459. }
  460. // Raise load columns event
  461. RaiseLoadColumns();
  462. // Load columns
  463. if (GridColumns != null)
  464. {
  465. foreach (Column col in GridColumns.Columns)
  466. {
  467. // Load column definition
  468. LoadColumnDefinition(col, filterTable);
  469. }
  470. }
  471. if (displayFilter)
  472. {
  473. // Finish filter form with "Show" button
  474. CreateFilterButton(filterTable);
  475. }
  476. }
  477. }
  478. return true;
  479. }
  480. /// <summary>
  481. /// Reloads the grid data.
  482. /// </summary>
  483. public override void ReloadData()
  484. {
  485. try
  486. {
  487. // Ensure grid definition before realod data
  488. LoadGridDefinition();
  489. RestoreState();
  490. RaiseOnBeforeDataReload();
  491. rowIndex = 1;
  492. // Get Current TOP N
  493. if (CurrentPageSize > 0)
  494. {
  495. int currentPageIndex = Pager.CurrentPage;
  496. int pageSize = (CurrentPageSize > 0) ? CurrentPageSize : UniGridView.PageSize;
  497. CurrentTopN = pageSize * (currentPageIndex + Pager.CurrentPagesGroupSize);
  498. }
  499. if (CurrentTopN < TopN)
  500. {
  501. CurrentTopN = TopN;
  502. }
  503. // If first/last button and direct page contol in pager is hidden use current topN for better performance
  504. if (!Pager.ShowDirectPageControl && !Pager.ShowFirstLastButtons)
  505. {
  506. TopN = CurrentTopN;
  507. }
  508. // Retrieve data
  509. UniGridView.DataSource = RetrieveData();
  510. RaiseOnAfterDataReload();
  511. SetUnigridControls();
  512. // Check if datasource is loaded
  513. if (DataHelper.DataSourceIsEmpty(GridView.DataSource) && (pagerElem.CurrentPage > 1))
  514. {
  515. pagerElem.UniPager.CurrentPage = 1;
  516. ReloadData();
  517. }
  518. // Resolve the edit action URL
  519. if (!String.IsNullOrEmpty(EditActionUrl))
  520. {
  521. EditActionUrl = CMSContext.ResolveMacros(EditActionUrl);
  522. }
  523. SortColumns.Clear();
  524. UniGridView.DataBind();
  525. mRowsCount = DataHelper.GetItemsCount(UniGridView.DataSource);
  526. CheckFilterVisibility();
  527. }
  528. catch (Exception ex)
  529. {
  530. // Display tooltip only development mode is enabled
  531. string desc = null;
  532. if (SettingsKeyProvider.DevelopmentMode)
  533. {
  534. desc = ex.Message;
  535. }
  536. ShowError(GetString("unigrid.error.reload"), desc, null);
  537. // Log exception
  538. EventLogProvider ev = new EventLogProvider();
  539. ev.LogEvent("UniGrid", "RELOADDATA", ex.InnerException ?? ex);
  540. }
  541. }
  542. /// <summary>
  543. /// Gets a dataset with data based on UniGrid's settings.
  544. /// </summary>
  545. /// <returns>DataSet with data</returns>
  546. public override DataSet RetrieveData()
  547. {
  548. DataSet ds = null;
  549. // If datasource for unigrid is query (not dataset), then execute query
  550. if (!string.IsNullOrEmpty(Query))
  551. {
  552. // Reload the data with current parameters
  553. ds = ConnectionHelper.ExecuteQuery(Query, QueryParameters, CompleteWhereCondition, CurrentOrder, TopN, Columns, CurrentOffset, CurrentPageSize, ref pagerForceNumberOfResults);
  554. }
  555. // If UniGrid is in ObjectType mode, get the data according to given object type.
  556. else if (InfoObject != null)
  557. {
  558. // Get the result set
  559. ds = InfoObject.GetData(QueryParameters, CompleteWhereCondition, CurrentOrder, TopN, Columns, false, CurrentOffset, CurrentPageSize, ref pagerForceNumberOfResults);
  560. }
  561. // External dataset is used
  562. else
  563. {
  564. ds = RaiseDataReload();
  565. SortUniGridDataSource(ds);
  566. ds = DataHelper.TrimDataSetPage(ds, CurrentOffset, CurrentPageSize, ref pagerForceNumberOfResults);
  567. }
  568. // Add empty dataset
  569. if (ds == null)
  570. {
  571. ds = new DataSet();
  572. ds.Tables.Add();
  573. }
  574. // Raise event 'OnRetrieveData'
  575. ds = RaiseAfterRetrieveData(ds);
  576. return ds;
  577. }
  578. /// <summary>
  579. /// Returns where condition from unigrid filters.
  580. /// </summary>
  581. public override string GetFilter(bool isDataTable)
  582. {
  583. string where = string.Empty;
  584. // Count of the conditions in the 'where clause'
  585. int whereConditionCount = 0;
  586. // Process all filter fields
  587. foreach (UniGridFilterField filterField in FilterFields.Values)
  588. {
  589. string filterFormat = filterField.Format;
  590. // AND in 'where clause'
  591. string andExpression;
  592. Control mainControl = filterField.OptionsControl;
  593. Control valueControl = filterField.ValueControl;
  594. string filterPath = filterField.ControlPath;
  595. if (valueControl is CMSAbstractBaseFilterControl)
  596. {
  597. // Custom filters (loaded controls)
  598. CMSAbstractBaseFilterControl customFilter = (CMSAbstractBaseFilterControl)valueControl;
  599. string customWhere = customFilter.WhereCondition;
  600. if (!String.IsNullOrEmpty(customWhere))
  601. {
  602. andExpression = (whereConditionCount > 0) ? " AND " : "";
  603. where += andExpression + customWhere;
  604. whereConditionCount++;
  605. }
  606. // Prepare query string
  607. if (FilterByQueryString && RequestHelper.IsPostBack())
  608. {
  609. queryStringHashTable[customFilter.ID] = customFilter.Value;
  610. }
  611. }
  612. else if (mainControl is DropDownList)
  613. {
  614. // Dropdown list filter
  615. DropDownList ddlistControl = (DropDownList)mainControl;
  616. TextBox txtControl = (TextBox)valueControl;
  617. string textboxValue = txtControl.Text;
  618. string textboxID = txtControl.ID;
  619. // Empty field -> no filter is set for this field
  620. if (textboxValue != "")
  621. {
  622. string op = ddlistControl.SelectedValue;
  623. string value = textboxValue.Replace("\'", "''");
  624. string columnName = ddlistControl.ID.Trim().TrimStart('[').TrimEnd(']').Trim();
  625. // Format {0} = column name, {1} = operator, {2} = value, {3} = default condition
  626. string defaultFormat = null;
  627. if (textboxID.EndsWithCSafe("TextValue"))
  628. {
  629. switch (op.ToLowerCSafe())
  630. {
  631. // LIKE operators
  632. case "like":
  633. defaultFormat = isDataTable ? "[{0}] {1} '%{2}%'" : "[{0}] {1} N'%{2}%'";
  634. break;
  635. case "not like":
  636. defaultFormat = isDataTable ? "([{0}] is null or [{0}] {1} '%{2}%')" : "([{0}] is null or [{0}] {1} N'%{2}%')";
  637. break;
  638. case "<>":
  639. defaultFormat = isDataTable ? "([{0}] is null or [{0}] {1} '{2}')" : "([{0}] is null or [{0}] {1} N'{2}')";
  640. break;
  641. // Standard operators
  642. default:
  643. defaultFormat = isDataTable ? "[{0}] {1} '{2}'" : "[{0}] {1} N'{2}'";
  644. break;
  645. }
  646. }
  647. else // textboxID.EndsWithCSafe("NumberValue")
  648. {
  649. if (ValidationHelper.IsDouble(value) || ValidationHelper.IsInteger(value))
  650. {
  651. defaultFormat = "[{0}] {1} {2}";
  652. if (op == "<>")
  653. {
  654. defaultFormat = "([{0}] is null or [{0}] {1} {2})";
  655. }
  656. }
  657. }
  658. if (!String.IsNullOrEmpty(defaultFormat))
  659. {
  660. string defaultCondition = String.Format(defaultFormat, columnName, op, value);
  661. string condition = defaultCondition;
  662. if (filterFormat != null)
  663. {
  664. condition = String.Format(filterFormat, columnName, op, value, defaultCondition);
  665. }
  666. andExpression = (whereConditionCount > 0 ? " AND " : string.Empty);
  667. // ddlistControl.ID - column name
  668. // ddlistControl.SelectedValue - condition option
  669. // textboxSqlValue - condition value
  670. where += String.Format("{0}({1})", andExpression, condition);
  671. whereConditionCount++;
  672. }
  673. }
  674. // Prepare query string
  675. if (FilterByQueryString)
  676. {
  677. queryStringHashTable[ddlistControl.ID] = String.Format("{0};{1}", ddlistControl.SelectedValue, textboxValue);
  678. }
  679. }
  680. else if (valueControl is DropDownList)
  681. {
  682. // Checkbox filter
  683. DropDownList currentControl = (DropDownList)valueControl;
  684. string value = currentControl.SelectedValue;
  685. if (value != "")
  686. {
  687. string columnName = currentControl.ID;
  688. string condition = String.Format("{0} = {1}", columnName, value);
  689. if (filterFormat != null)
  690. {
  691. condition = String.Format(filterFormat, columnName, "=", value, condition);
  692. }
  693. andExpression = (whereConditionCount > 0 ? " AND " : string.Empty);
  694. where += String.Format("{0}({1})", andExpression, condition);
  695. whereConditionCount++;
  696. }
  697. // Prepare query string
  698. if (FilterByQueryString)
  699. {
  700. queryStringHashTable[currentControl.ID] = ";" + value;
  701. }
  702. }
  703. }
  704. return where;
  705. }
  706. /// <summary>
  707. /// Uncheck all checkboxes in selection column.
  708. /// </summary>
  709. public override void ResetSelection()
  710. {
  711. ResetSelection(true);
  712. }
  713. /// <summary>
  714. /// Uncheck all checkboxes in selection column.
  715. /// </summary>
  716. /// <param name="reset">Indicates if reset selection javascript should be registered</param>
  717. public void ResetSelection(bool reset)
  718. {
  719. SelectionHiddenField.Value = String.Empty;
  720. hidNewSelection.Value = String.Empty;
  721. hidDeSelection.Value = String.Empty;
  722. resetSelection = reset;
  723. }
  724. #endregion
  725. #region "UniGrid events"
  726. /// <summary>
  727. /// Process data from filter.
  728. /// </summary>
  729. protected void ShowButton_Click(object sender, EventArgs e)
  730. {
  731. ApplyFilter(sender, e);
  732. }
  733. protected void ResetButton_Click(object sender, EventArgs e)
  734. {
  735. Reset();
  736. }
  737. protected void pageSizeDropdown_SelectedIndexChanged(object sender, EventArgs e)
  738. {
  739. RaisePageSizeChanged();
  740. }
  741. protected void UniGridView_Sorting(object sender, EventArgs e)
  742. {
  743. RaiseBeforeSorting(sender, e);
  744. }
  745. /// <summary>
  746. /// After data bound event.
  747. /// </summary>
  748. protected void UniGridView_DataBound(object sender, EventArgs e)
  749. {
  750. // Set actions hash into hidden field
  751. SetActionsHash();
  752. SetPager();
  753. // Call page binding event
  754. if (OnPageBinding != null)
  755. {
  756. OnPageBinding(this, null);
  757. }
  758. }
  759. protected void UniGridView_RowCreating(object sender, GridViewRowEventArgs e)
  760. {
  761. // If row type is header
  762. if (e.Row.RowType == DataControlRowType.Header)
  763. {
  764. // Add sorting definition to list of sort columns
  765. SortColumns.Add(SortDirect.ToLowerCSafe());
  766. // Parse the sort expression
  767. string sort = SortDirect.ToLowerCSafe().Replace("[", "").Replace("]", "").Trim();
  768. if (sort.StartsWithCSafe("cast("))
  769. {
  770. sort = sort.Substring(5);
  771. }
  772. Match sortMatch = OrderByRegex.Match(sort);
  773. string sortColumn = null;
  774. string sortDirection = null;
  775. if (sortMatch.Success)
  776. {
  777. // Get column name
  778. if (sortMatch.Groups[1].Success)
  779. {
  780. sortColumn = sortMatch.Groups[1].Value;
  781. }
  782. // Get sort direction
  783. sortDirection = sortMatch.Groups[2].Success ? sortMatch.Groups[2].Value : "asc";
  784. }
  785. else
  786. {
  787. // Get column name from sort expression
  788. int space = sort.IndexOfAny(new char[] { ' ', ',' });
  789. sortColumn = space > -1 ? sort.Substring(0, space) : sort;
  790. sortDirection = "asc";
  791. }
  792. // Check if displaying arrow indicating sorting is requested
  793. if (showSortDirection)
  794. {
  795. // Prepare the columns
  796. foreach (TableCell Cell in e.Row.Cells)
  797. {
  798. // If there is some sorting expression
  799. DataControlFieldCell dataField = (DataControlFieldCell)Cell;
  800. string fieldSortExpression = dataField.ContainingField.SortExpression;
  801. if (!DataHelper.IsEmpty(fieldSortExpression))
  802. {
  803. SortColumns.Add(fieldSortExpression.ToLowerCSafe());
  804. // If actual sorting expressions is this cell
  805. if (CMSString.Equals(sortColumn, fieldSortExpression.Replace("[", "").Replace("]", "").Trim(), true))
  806. {
  807. // Initialize sort arrow
  808. Literal sortArrow = new Literal()
  809. {
  810. Text = String.Format("<span class=\"UniGridSort{0}\" >&nbsp;&nbsp;&nbsp;</span>", ((sortDirection == "desc") ? "Down" : "Up"))
  811. };
  812. if (DataHelper.IsEmpty(Cell.Text))
  813. {
  814. if ((Cell.Controls.Count != 0) && (Cell.Controls[0] != null))
  815. {
  816. // Add original text
  817. Cell.Controls[0].Controls.Add(new LiteralControl(String.Format("<span class=\"UniGridSortLabel\">{0}</span>", ((LinkButton)(Cell.Controls[0])).Text)));
  818. // Add one space before image
  819. Cell.Controls[0].Controls.Add(new LiteralControl("&nbsp;"));
  820. Cell.Controls[0].Controls.Add(sortArrow);
  821. }
  822. else
  823. {
  824. // Add one space before image
  825. Cell.Controls.Add(new LiteralControl("&nbsp;"));
  826. Cell.Controls.Add(sortArrow);
  827. }
  828. }
  829. }
  830. }
  831. }
  832. }
  833. }
  834. else if (e.Row.RowType == DataControlRowType.DataRow)
  835. {
  836. e.Row.CssClass = (rowIndex % 2 == 0) ? "OddRow" : "EvenRow";
  837. rowIndex++;
  838. }
  839. else if (e.Row.RowType == DataControlRowType.Footer)
  840. {
  841. e.Row.CssClass = "UniGridFooter";
  842. }
  843. else if (e.Row.RowType == DataControlRowType.Pager)
  844. {
  845. e.Row.CssClass = "UniGridPager";
  846. }
  847. }
  848. /// <summary>
  849. /// Handles the action event.
  850. /// </summary>
  851. /// <param name="cmdName">Command name</param>
  852. /// <param name="cmdValue">Command value</param>
  853. public void HandleAction(string cmdName, string cmdValue)
  854. {
  855. string action = cmdName.ToLowerCSafe();
  856. // Check action security and redirect if user not authorized
  857. CheckActionAndRedirect(action);
  858. GeneralizedInfo infoObj = null;
  859. int objectId = 0;
  860. switch (action)
  861. {
  862. case "#delete":
  863. case "#destroyobject":
  864. {
  865. // Delete the object
  866. objectId = ValidationHelper.GetInteger(cmdValue, 0);
  867. if (objectId > 0)
  868. {
  869. infoObj = CMSObjectHelper.GetReadOnlyObject(ObjectType);
  870. string objectType = infoObj.TypeInfo.Inherited ? infoObj.TypeInfo.OriginalObjectType : infoObj.ObjectType;
  871. infoObj = BaseAbstractInfoProvider.GetInfoById(objectType, objectId);
  872. if (infoObj != null)
  873. {
  874. switch (action)
  875. {
  876. case "#delete":
  877. // Check the dependencies
  878. AbstractProvider providerObj = infoObj.TypeInfo.ProviderObject;
  879. List<string> names = new List<string>();
  880. if (providerObj.CheckObjectDependencies(objectId, ref names))
  881. {
  882. string description = null;
  883. if (names.Count > 0)
  884. {
  885. // Encode and localize names
  886. StringBuilder sb = new StringBuilder();
  887. names.ForEach(item => sb.Append("<br />", HTMLHelper.HTMLEncode(ResHelper.LocalizeString(item))));
  888. description = GetString(objectType.Replace(".", "_") + ".objectlist|unigrid.objectlist") + sb.ToString();
  889. }
  890. ShowError(GetString("ecommerce.deletedisabledwithoutenable"), description, null);
  891. return;
  892. }
  893. // Delete the object
  894. infoObj.DeleteObject();
  895. break;
  896. case "#destroyobject":
  897. if (CMSContext.CurrentUser.IsAuthorizedPerObject(PermissionsEnum.Destroy, infoObj.ObjectType, CMSContext.CurrentSiteName))
  898. {
  899. using (CMSActionContext context = new CMSActionContext())
  900. {
  901. context.CreateVersion = false;
  902. Action ac = GridActions.GetAction("#delete");
  903. if (ac != null)
  904. {
  905. HandleAction("#delete", cmdValue);
  906. }
  907. else
  908. {
  909. ac = GridActions.GetAction("delete");
  910. if (ac != null)
  911. {
  912. RaiseAction("delete", cmdValue);
  913. }
  914. else
  915. {
  916. ShowError(GetString("objectversioning.destroyobject.nodeleteaction"));
  917. return;
  918. }
  919. }
  920. }
  921. }
  922. break;
  923. }
  924. }
  925. }
  926. }
  927. break;
  928. default:
  929. RaiseAction(cmdName, cmdValue);
  930. break;
  931. }
  932. }
  933. #endregion
  934. #region "Private methods"
  935. /// <summary>
  936. /// Sets unigrid controls.
  937. /// </summary>
  938. private void SetUnigridControls()
  939. {
  940. filter.Visible = displayFilter;
  941. // Indicates whether unigrid datasource is empty or not
  942. isEmpty = DataHelper.DataSourceIsEmpty(UniGridView.DataSource);
  943. if (isEmpty)
  944. {
  945. // Try to reload data for previous page if action was used and no data loaded (mostly delete)
  946. if (onActionUsed && Pager.CurrentPage > 1)
  947. {
  948. Pager.UniPager.CurrentPage = Pager.CurrentPage - 1;
  949. ReloadData();
  950. }
  951. else if (HideControlForZeroRows && (WhereClause == ""))
  952. {
  953. // Hide filter
  954. filter.Visible = false;
  955. }
  956. }
  957. else
  958. {
  959. // Disable GridView paging because UniGridPager will provide paging
  960. UniGridView.AllowPaging = false;
  961. // Process paging if pager is displayed
  962. if (Pager.DisplayPager)
  963. {
  964. if (CurrentPageSize > 0)
  965. {
  966. if (!visiblePagesSet)
  967. {
  968. Pager.VisiblePages = (((CurrentOffset / CurrentPageSize) + 1)) > halfPageCountLimit ? 5 : 10;
  969. }
  970. Pager.DirectPageControlID = ((float)PagerForceNumberOfResults / Pager.CurrentPageSize > 20.0f) ? "txtPage" : "drpPage";
  971. // Save direct page control id in viewstate
  972. ViewState["DirectPageControlID"] = Pager.DirectPageControlID;
  973. }
  974. }
  975. }
  976. }
  977. /// <summary>
  978. /// Load options definition.
  979. /// </summary>
  980. /// <param name="options">Options configuration</param>
  981. /// <param name="filterTable">Table for filter</param>
  982. private void LoadOptionsDefinition(UniGridOptions options, Table filterTable)
  983. {
  984. // Create filter table according to the key value "DisplayFilter"
  985. displayFilter = options.DisplayFilter;
  986. if (displayFilter)
  987. {
  988. filter.Controls.Add(filterTable);
  989. }
  990. // Filter limit
  991. if (options.FilterLimit > -1)
  992. {
  993. FilterLimit = options.FilterLimit;
  994. }
  995. // Display sort direction images
  996. showSortDirection = options.ShowSortDirection;
  997. // Display selection column with checkboxes
  998. showSelection = options.ShowSelection;
  999. if (showSelection)
  1000. {
  1001. TemplateField chkColumn = new TemplateField();
  1002. using (CheckBox headerBox = new CheckBox { ID = "headerBox" })
  1003. {
  1004. using (CheckBox itemBox = new CheckBox { ID = "itemBox" })
  1005. {
  1006. // Set selection argument
  1007. itemBox.Attributes["selectioncolumn"] = options.SelectionColumn;
  1008. chkColumn.HeaderTemplate = new GridViewTemplate(ListItemType.Header, this, headerBox);
  1009. chkColumn.ItemTemplate = new GridViewTemplate(ListItemType.Item, this, itemBox);
  1010. }
  1011. }
  1012. UniGridView.Columns.Add(chkColumn);
  1013. }
  1014. // Get pagesize options
  1015. if (!String.IsNullOrEmpty(options.PageSize))
  1016. {
  1017. Pager.PageSizeOptions = options.PageSize;
  1018. }
  1019. // Set pagging acording to the key value "DisplayPageSizeDropdown"
  1020. if (options.DisplayPageSizeDropdown != null)
  1021. {
  1022. Pager.ShowPageSize = options.DisplayPageSizeDropdown.Value;
  1023. }
  1024. }
  1025. /// <summary>
  1026. /// Loads actions definition.
  1027. /// </summary>
  1028. /// <param name="actions">Configuration of the actions</param>
  1029. private void LoadActionsDefinition(UniGridActions actions)
  1030. {
  1031. // Custom template field of the grid view
  1032. TemplateField actionsColumn = new TemplateField();
  1033. // Ensure width of the column
  1034. if (!String.IsNullOrEmpty(actions.Width))
  1035. {
  1036. actionsColumn.ItemStyle.Width = new Unit(actions.Width);
  1037. }
  1038. // Add object menu if possible
  1039. if ((actions.Actions.Count > 0 && !(actions.Actions.FirstOrDefault() is EmptyAction)) && ShowObjectMenu && UniGridFunctions.ShowUniGridObjectContextMenu(CMSObjectHelper.GetReadOnlyObject(ObjectType)))
  1040. {
  1041. actions.Actions.RemoveAll(a => a is EmptyAction);
  1042. // Check if object menu already contained
  1043. var menus = from action in actions.Actions.OfType<Action>()
  1044. where (action.Name.ToLowerCSafe() == "#objectmenu") || (!String.IsNullOrEmpty(action.ContextMenu))
  1045. select action;
  1046. // Add object menu of necessary
  1047. if ((menus.Count() == 0) && !IsLiveSite)
  1048. {
  1049. Action action = new Action("#objectmenu");
  1050. action.ExternalSourceName = "#objectmenu";
  1051. actions.Actions.Add(action);
  1052. }
  1053. }
  1054. // Show header?
  1055. if (actions.ShowHeader)
  1056. {
  1057. if (ShowActionsMenu && string.IsNullOrEmpty(actions.ContextMenu))
  1058. {
  1059. actions.ContextMenu = DEFAULT_ACTIONS_MENU;
  1060. actions.Caption = "General.OtherActions";
  1061. }
  1062. // Fill in the custom template field
  1063. string label = (ShowActionsLabel ? GetString("unigrid.actions") : "");
  1064. GridViewTemplate headerTemplate = new GridViewTemplate(ListItemType.Header, this, actions, label, ImageDirectoryPath, DefaultImageDirectoryPath, Page);
  1065. headerTemplate.ContextMenuParent = plcContextMenu;
  1066. headerTemplate.CheckRelative = CheckRelative;
  1067. actionsColumn.HeaderTemplate = headerTemplate;
  1068. if (ShowActionsMenu)
  1069. {
  1070. if (actions.Actions.FirstOrDefault() is EmptyAction)
  1071. {
  1072. actionsColumn.HeaderStyle.CssClass = "EmptyAC";
  1073. }
  1074. else
  1075. {
  1076. actionsColumn.HeaderStyle.CssClass = "AC";
  1077. }
  1078. }
  1079. }
  1080. GridViewTemplate actionsTemplate = new GridViewTemplate(ListItemType.Item, this, actions, null, ImageDirectoryPath, DefaultImageDirectoryPath, Page);
  1081. actionsTemplate.OnExternalDataBound += RaiseExternalDataBound;
  1082. actionsTemplate.ContextMenuParent = plcContextMenu;
  1083. actionsTemplate.CheckRelative = CheckRelative;
  1084. actionsColumn.ItemTemplate = actionsTemplate;
  1085. if (!IsLiveSite)
  1086. {
  1087. actionsColumn.ItemStyle.CssClass = "NW UniGridActions";
  1088. }
  1089. else
  1090. {
  1091. actionsColumn.ItemStyle.CssClass = "UniGridActions";
  1092. actionsColumn.ItemStyle.Wrap = false;
  1093. }
  1094. // CSS class name
  1095. string cssClass = actions.CssClass;
  1096. if (cssClass != null)
  1097. {
  1098. actionsColumn.HeaderStyle.CssClass += " " + cssClass;
  1099. actionsColumn.ItemStyle.CssClass += " " + cssClass;
  1100. actionsColumn.FooterStyle.CssClass += " " + cssClass;
  1101. }
  1102. // Add custom column to grid view
  1103. UniGridView.Columns.Add(actionsColumn);
  1104. }
  1105. /// <summary>
  1106. /// Load unigrid pager configuration.
  1107. /// </summary>
  1108. /// <param name="config">Pager configuration</param>
  1109. private void LoadPagerDefinition(UniGridPagerConfig config)
  1110. {
  1111. if (config.DisplayPager != null)
  1112. {
  1113. Pager.DisplayPager = config.DisplayPager.Value;
  1114. }
  1115. // Load definition only if pager is displayed
  1116. if (Pager.DisplayPager)
  1117. {
  1118. if (config.PageSizeOptions != null)
  1119. {
  1120. Pager.PageSizeOptions = config.PageSizeOptions;
  1121. }
  1122. if (config.ShowDirectPageControl != null)
  1123. {
  1124. Pager.ShowDirectPageControl = config.ShowDirectPageControl.Value;
  1125. }
  1126. if (config.ShowFirstLastButtons != null)
  1127. {
  1128. Pager.ShowFirstLastButtons = config.ShowFirstLastButtons.Value;
  1129. }
  1130. if (config.ShowPageSize != null)
  1131. {
  1132. Pager.ShowPageSize = config.ShowPageSize.Value;
  1133. }
  1134. if (config.ShowPreviousNextButtons != null)
  1135. {
  1136. Pager.ShowPreviousNextButtons = config.ShowPreviousNextButtons.Value;
  1137. }
  1138. if (config.ShowPreviousNextPageGroup != null)
  1139. {
  1140. Pager.ShowPreviousNextPageGroup = config.ShowPreviousNextPageGroup.Value;
  1141. }
  1142. if (config.VisiblePages > 0)
  1143. {
  1144. Pager.VisiblePages = config.VisiblePages;
  1145. visiblePagesSet = true;
  1146. }
  1147. if (config.DefaultPageSize > 0)
  1148. {
  1149. Pager.DefaultPageSize = config.DefaultPageSize;
  1150. }
  1151. // Try to get page size from request
  1152. string selectedPageSize = Request.Form[Pager.PageSizeDropdown.UniqueID];
  1153. int pageSize = 0;
  1154. if (selectedPageSize != null)
  1155. {
  1156. pageSize = ValidationHelper.GetInteger(selectedPageSize, 0);
  1157. }
  1158. else if (config.DefaultPageSize > 0)
  1159. {
  1160. pageSize = config.DefaultPageSize;
  1161. }
  1162. if ((pageSize > 0) || (pageSize == -1))
  1163. {
  1164. Pager.CurrentPageSize = pageSize;
  1165. }
  1166. }
  1167. else
  1168. {
  1169. // Reset page size
  1170. Pager.CurrentPageSize = -1;
  1171. }
  1172. }
  1173. /// <summary>
  1174. /// Load single column definition.
  1175. /// </summary>
  1176. /// <param name="column">Column to use</param>
  1177. /// <param name="filterTable">Table for filter</param>
  1178. private void LoadColumnDefinition(Column column, Table filterTable)
  1179. {
  1180. DataControlField field = null;
  1181. string cssClass = column.CssClass;
  1182. string columnCaption = null;
  1183. // Process the column type Hyperlink or BoundColumn based on the parameters
  1184. if ((column.HRef != null) ||
  1185. (column.ExternalSourceName != null) ||
  1186. (column.Localize) ||
  1187. (column.Icon != null) ||
  1188. (column.Tooltip != null) ||
  1189. (column.Action != null) ||
  1190. (column.Style != null) ||
  1191. (column.MaxLength > 0))
  1192. {
  1193. ExtendedBoundField linkColumn = new ExtendedBoundField();
  1194. field = linkColumn;
  1195. // Attribute "source"
  1196. if (column.Source != null)
  1197. {
  1198. linkColumn.DataField = column.Source;
  1199. if (column.AllowSorting)
  1200. {
  1201. if (!String.IsNullOrEmpty(column.Sort))
  1202. {
  1203. linkColumn.SortExpression = column.Sort;
  1204. }
  1205. else if (column.Source.ToLowerCSafe() != ExtendedBoundField.ALL_DATA.ToLowerCSafe())
  1206. {
  1207. linkColumn.SortExpression = column.Source;
  1208. }
  1209. }
  1210. }
  1211. // Action parameters
  1212. if (column.Action != null)
  1213. {
  1214. linkColumn.Action = column.Action;
  1215. // Action parameters
  1216. if (column.CommandArgument != null)
  1217. {
  1218. linkColumn.CommandArgument = column.CommandArgument;
  1219. }
  1220. }
  1221. // Action parameters
  1222. if (column.Parameters != null)
  1223. {
  1224. linkColumn.ActionParameters = column.Parameters;
  1225. }
  1226. // Navigate URL
  1227. if (column.HRef != null)
  1228. {
  1229. linkColumn.NavigateUrl = column.HRef;
  1230. }
  1231. // External source
  1232. if (column.ExternalSourceName != null)
  1233. {
  1234. linkColumn.ExternalSourceName = column.ExternalSourceName;
  1235. linkColumn.OnExternalDataBound += RaiseExternalDataBound;
  1236. }
  1237. // Localize strings?
  1238. linkColumn.LocalizeStrings = column.Localize;
  1239. // Style
  1240. if (column.Style != null)
  1241. {
  1242. linkColumn.Style = column.Style;
  1243. }
  1244. // Class name
  1245. if (cssClass != null)
  1246. {
  1247. linkColumn.HeaderStyle.CssClass += " " + cssClass;
  1248. linkColumn.ItemStyle.CssClass += " " + cssClass;
  1249. linkColumn.FooterStyle.CssClass += " " + cssClass;
  1250. }
  1251. // Icon
  1252. if (column.Icon != null)
  1253. {
  1254. if (linkColumn.DataField == "")
  1255. {
  1256. linkColumn.DataField = ExtendedBoundField.ALL_DATA;
  1257. }
  1258. linkColumn.Icon = GetActionImage(column.Icon);
  1259. }
  1260. // Max length
  1261. if (column.MaxLength > 0)
  1262. {
  1263. linkColumn.MaxLength = column.MaxLength;
  1264. }
  1265. // Process "tooltip" node
  1266. ColumnTooltip tooltip = column.Tooltip;
  1267. if (tooltip != null)
  1268. {
  1269. // If there is some tooltip register TooltipScript
  1270. if ((tooltip.Source != null) || (tooltip.ExternalSourceName != null))
  1271. {
  1272. ScriptHelper.RegisterTooltip(Page);
  1273. }
  1274. // Tooltip source
  1275. if (tooltip.Source != null)
  1276. {
  1277. linkColumn.TooltipSourceName = tooltip.Source;
  1278. }
  1279. // Tooltip external source
  1280. if (tooltip.ExternalSourceName != null)
  1281. {
  1282. linkColumn.TooltipExternalSourceName = tooltip.ExternalSourceName;
  1283. // Ensure external data bound event handler
  1284. if (string.IsNullOrEmpty(column.ExternalSourceName))
  1285. {
  1286. linkColumn.OnExternalDataBound += RaiseExternalDataBound;
  1287. }
  1288. }
  1289. // Tooltip width
  1290. if (tooltip.Width != null)
  1291. {
  1292. linkColumn.TooltipWidth = tooltip.Width;
  1293. }
  1294. // Encode tooltip
  1295. linkColumn.TooltipEncode = tooltip.Encode;
  1296. }
  1297. }
  1298. else
  1299. {
  1300. BoundField userColumn = new BoundField(); // Custom column of the grid view
  1301. field = userColumn;
  1302. // Attribute "source"
  1303. if (column.Source != null)
  1304. {
  1305. userColumn.DataField = column.Source;
  1306. // Allow sorting
  1307. if (column.AllowSorting)
  1308. {
  1309. if (column.Source.ToLowerCSafe() != ExtendedBoundField.ALL_DATA.

Large files files are truncated, but you can click here to view the full file