PageRenderTime 34ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/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
  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.ToLowerCSafe())
  1310. {
  1311. userColumn.SortExpression = column.Source;
  1312. }
  1313. else if (column.Sort != null)
  1314. {
  1315. userColumn.SortExpression = column.Sort;
  1316. }
  1317. }
  1318. }
  1319. }
  1320. if (!IsLiveSite)
  1321. {
  1322. field.HeaderStyle.CssClass = "NW";
  1323. }
  1324. else
  1325. {
  1326. field.HeaderStyle.Wrap = false;
  1327. }
  1328. // Column name
  1329. if (column.Name != null)
  1330. {
  1331. NamedColumns[column.Name] = field;
  1332. }
  1333. // Caption
  1334. if (column.Caption != null)
  1335. {
  1336. columnCaption = GetString(ResHelper.GetResourceName(column.Caption));
  1337. field.HeaderText = columnCaption;
  1338. }
  1339. // Width
  1340. if (column.Width != null)
  1341. {
  1342. if (GridView.ShowHeader)
  1343. {
  1344. field.HeaderStyle.Width = new Unit(column.Width);
  1345. }
  1346. else
  1347. {
  1348. field.ItemStyle.Width = new Unit(column.Width);
  1349. }
  1350. }
  1351. // Visible
  1352. field.Visible = column.Visible;
  1353. // Is text?
  1354. if (column.IsText && (column.Source != null))
  1355. {
  1356. TextColumns.Add(column.Source);
  1357. }
  1358. // Wrap?
  1359. if (!column.Wrap)
  1360. {
  1361. if (!IsLiveSite)
  1362. {
  1363. field.ItemStyle.CssClass = "NW";
  1364. }
  1365. else
  1366. {
  1367. field.ItemStyle.Wrap = false;
  1368. }
  1369. }
  1370. // Class name
  1371. if (cssClass != null)
  1372. {
  1373. field.HeaderStyle.CssClass += " " + cssClass;
  1374. field.ItemStyle.CssClass += " " + cssClass;
  1375. field.FooterStyle.CssClass += " " + cssClass;
  1376. }
  1377. // Process "filter" node
  1378. if (displayFilter)
  1379. {
  1380. // Filter
  1381. ColumnFilter filter = column.Filter;
  1382. if (filter != null)
  1383. {
  1384. object option = null;
  1385. object value = null;
  1386. // Filter via query string
  1387. if (FilterByQueryString)
  1388. {
  1389. if (String.IsNullOrEmpty(filter.Path))
  1390. {
  1391. string values = QueryHelper.GetString(column.Source, null);
  1392. if (!string.IsNullOrEmpty(values))
  1393. {
  1394. string[] pair = values.Split(';');
  1395. option = pair[0];
  1396. value = pair[1];
  1397. }
  1398. }
  1399. else
  1400. {
  1401. value = QueryHelper.GetString(column.Source, null);
  1402. }
  1403. }
  1404. // Add the filter field
  1405. AddFilterField(filter, column.Source, columnCaption, filterTable, option, value);
  1406. }
  1407. }
  1408. // Add custom column to gridview
  1409. UniGridView.Columns.Add(field);
  1410. // Store corresponding field
  1411. column.Field = field;
  1412. }
  1413. /// <summary>
  1414. /// Load query definition from XML.
  1415. /// </summary>
  1416. /// <param name="objectTypeNode">XML query definition node</param>
  1417. private void LoadObjectTypeDefinition(XmlNode objectTypeNode)
  1418. {
  1419. if (objectTypeNode != null)
  1420. {
  1421. ObjectType = objectTypeNode.Attributes["name"].Value;
  1422. // Set the columns property if columns are defined
  1423. LoadColumns(objectTypeNode);
  1424. }
  1425. }
  1426. /// <summary>
  1427. /// Load query definition from XML.
  1428. /// </summary>
  1429. /// <param name="queryNode">XML query definition node</param>
  1430. private void LoadQueryDefinition(XmlNode queryNode)
  1431. {
  1432. if (queryNode != null)
  1433. {
  1434. Query = queryNode.Attributes["name"].Value;
  1435. // Set the columns property if columns are defined
  1436. LoadColumns(queryNode);
  1437. LoadAllColumns(queryNode);
  1438. // Load the query parameters
  1439. XmlNodeList parameters = queryNode.SelectNodes("parameter");
  1440. if ((parameters != null) && (parameters.Count > 0))
  1441. {
  1442. QueryDataParameters newParams = new QueryDataParameters();
  1443. // Process all parameters
  1444. foreach (XmlNode param in parameters)
  1445. {
  1446. object value = null;
  1447. string name = param.Attributes["name"].Value;
  1448. switch (param.Attributes["type"].Value.ToLowerCSafe())
  1449. {
  1450. case "string":
  1451. value = param.Attributes["value"].Value;
  1452. break;
  1453. case "int":
  1454. value = ValidationHelper.GetInteger(param.Attributes["value"].Value, 0);
  1455. break;
  1456. case "double":
  1457. value = Convert.ToDouble(param.Attributes["value"].Value);
  1458. break;
  1459. case "bool":
  1460. value = Convert.ToBoolean(param.Attributes["value"].Value);
  1461. break;
  1462. }
  1463. newParams.Add(name, value);
  1464. }
  1465. QueryParameters = newParams;
  1466. }
  1467. }
  1468. }
  1469. /// <summary>
  1470. /// Sets the columns property if columns are defined.
  1471. /// </summary>
  1472. /// <param name="queryNode">Node from which to load columns</param>
  1473. private void LoadAllColumns(XmlNode queryNode)
  1474. {
  1475. XmlAttribute allColumns = queryNode.Attributes["allcolumns"];
  1476. if (allColumns != null)
  1477. {
  1478. AllColumns = DataHelper.GetNotEmpty(allColumns.Value, AllColumns);
  1479. }
  1480. }
  1481. /// <summary>
  1482. /// Sets the columns property if columns are defined.
  1483. /// </summary>
  1484. /// <param name="queryNode">Node from which to load columns</param>
  1485. private void LoadColumns(XmlNode queryNode)
  1486. {
  1487. XmlAttribute columns = queryNode.Attributes["columns"];
  1488. if (columns != null)
  1489. {
  1490. Columns = DataHelper.GetNotEmpty(columns.Value, Columns);
  1491. }
  1492. }
  1493. /// <summary>
  1494. /// Add filter field to the filter table.
  1495. /// </summary>
  1496. /// <param name="filter">Filter definition</param>
  1497. /// <param name="columnSourceName">Column source field name</param>
  1498. /// <param name="fieldDisplayName">Field display name</param>
  1499. /// <param name="filterTable">Filter table</param>
  1500. /// <param name="filterOption">Filter option</param>
  1501. /// <param name="filterValue">Filter value</param>
  1502. private void AddFilterField(ColumnFilter filter, string columnSourceName, string fieldDisplayName, Table filterTable, object filterOption, object filterValue)
  1503. {
  1504. string fieldType = filter.Type;
  1505. string fieldPath = filter.Path;
  1506. string filterFormat = filter.Format;
  1507. string fieldSourceName = filter.Source ?? columnSourceName;
  1508. int filterSize = filter.Size;
  1509. Unit filterWidth = filter.Width;
  1510. TableRow tRow = new TableRow();
  1511. TableCell tCellName = new TableCell();
  1512. TableCell tCellOption = new TableCell();
  1513. TableCell tCellValue = new TableCell();
  1514. // Ensure fieldSourceName is JavaScript valid
  1515. fieldSourceName = fieldSourceName.Replace(ALL, "__ALL__");
  1516. // Label
  1517. Label textName = new Label
  1518. {
  1519. Text = String.IsNullOrEmpty(fieldDisplayName) ? "" : fieldDisplayName + ":",
  1520. ID = fieldSourceName + "Name",
  1521. EnableViewState = false
  1522. };
  1523. tCellName.Controls.Add(textName);
  1524. tRow.Cells.Add(tCellName);
  1525. // Filter option
  1526. string option = null;
  1527. if (filterOption != null)
  1528. {
  1529. option = ValidationHelper.GetString(filterOption, null);
  1530. }
  1531. // Filter value
  1532. string value = null;
  1533. if (filterValue != null)
  1534. {
  1535. value = ValidationHelper.GetString(filterValue, null);
  1536. }
  1537. // Filter definition
  1538. UniGridFilterField filterDefinition = new UniGridFilterField();
  1539. filterDefinition.Type = (fieldType != null) ? fieldType.ToLowerCSafe() : "custom";
  1540. filterDefinition.Label = textName;
  1541. filterDefinition.Format = filterFormat;
  1542. filterDefinition.FilterRow = tRow;
  1543. string customPath = null;
  1544. // Set the filter default value
  1545. string defaultValue = filter.DefaultValue;
  1546. // Remember default values of filter field controls for potential UniGrid reset
  1547. string optionFilterFieldValue = null;
  1548. string valueFilterFieldValue = null;
  1549. switch (filterDefinition.Type)
  1550. {
  1551. // Text filter
  1552. case "text":
  1553. {
  1554. DropDownList textOptionFilterField = new DropDownList();
  1555. textOptionFilterField.Items.Add(new ListItem("LIKE", "LIKE"));
  1556. textOptionFilterField.Items.Add(new ListItem("NOT LIKE", "NOT LIKE"));
  1557. textOptionFilterField.Items.Add(new ListItem("=", "="));
  1558. textOptionFilterField.Items.Add(new ListItem("<>", "<>"));
  1559. textOptionFilterField.CssClass = "ContentDropdown";
  1560. textOptionFilterField.ID = fieldSourceName;
  1561. // Set the value
  1562. SetDropdownValue(value, null, textOptionFilterField);
  1563. optionFilterFieldValue = textOptionFilterField.SelectedValue;
  1564. LocalizedLabel lblSelect = new LocalizedLabel
  1565. {
  1566. EnableViewState = false,
  1567. Display = false,
  1568. AssociatedControlID = textOptionFilterField.ID,
  1569. ResourceString = "general.select"
  1570. };
  1571. tCellOption.Controls.Add(lblSelect);
  1572. tCellOption.Controls.Add(textOptionFilterField);
  1573. tRow.Cells.Add(tCellOption);
  1574. // Add text field
  1575. TextBox textValueFilterField = new TextBox
  1576. {
  1577. ID = fieldSourceName + "TextValue",
  1578. CssClass = "FilterTextBox",
  1579. };
  1580. // Set value
  1581. SetTextboxValue(value, defaultValue, textValueFilterField);
  1582. valueFilterFieldValue = textValueFilterField.Text;
  1583. if (filterSize > 0)
  1584. {
  1585. textValueFilterField.MaxLength = filterSize;
  1586. }
  1587. if (!filterWidth.IsEmpty)
  1588. {
  1589. textValueFilterField.Width = filterWidth;
  1590. }
  1591. tCellValue.Controls.Add(textValueFilterField);
  1592. tRow.Cells.Add(tCellValue);
  1593. textName.AssociatedControlID = textValueFilterField.ID;
  1594. filterDefinition.OptionsControl = textOptionFilterField;
  1595. filterDefinition.ValueControl = textValueFilterField;
  1596. }
  1597. break;
  1598. // Boolean filter
  1599. case "bool":
  1600. {
  1601. DropDownList booleanOptionFilterField = new DropDownList();
  1602. booleanOptionFilterField.Items.Add(new ListItem(GetString("general.selectall"), ""));
  1603. booleanOptionFilterField.Items.Add(new ListItem(GetString("general.yes"), "1"));
  1604. booleanOptionFilterField.Items.Add(new ListItem(GetString("general.no"), "0"));
  1605. booleanOptionFilterField.CssClass = "ContentDropdown";
  1606. booleanOptionFilterField.ID = fieldSourceName;
  1607. textName.AssociatedControlID = booleanOptionFilterField.ID;
  1608. // Set the value
  1609. SetDropdownValue(value, defaultValue, booleanOptionFilterField);
  1610. valueFilterFieldValue = booleanOptionFilterField.SelectedValue;
  1611. tCellValue.Controls.Add(booleanOptionFilterField);
  1612. tRow.Cells.Add(tCellValue);
  1613. filterDefinition.ValueControl = booleanOptionFilterField;
  1614. }
  1615. break;
  1616. // Integer filter
  1617. case "integer":
  1618. case "double":
  1619. {
  1620. DropDownList numberOptionFilterField = new DropDownList();
  1621. numberOptionFilterField.Items.Add(new ListItem("=", "="));
  1622. numberOptionFilterField.Items.Add(new ListItem("<>", "<>"));
  1623. numberOptionFilterField.Items.Add(new ListItem("<", "<"));
  1624. numberOptionFilterField.Items.Add(new ListItem(">", ">"));
  1625. numberOptionFilterField.CssClass = "ContentDropdown";
  1626. numberOptionFilterField.ID = fieldSourceName;
  1627. // Set the value
  1628. SetDropdownValue(value, null, numberOptionFilterField);
  1629. optionFilterFieldValue = numberOptionFilterField.SelectedValue;
  1630. LocalizedLabel lblSelect = new LocalizedLabel
  1631. {
  1632. EnableViewState = false,
  1633. Display = false,
  1634. AssociatedControlID = numberOptionFilterField.ID,
  1635. ResourceString = "general.select"
  1636. };
  1637. // Add filter field
  1638. tCellOption.Controls.Add(lblSelect);
  1639. tCellOption.Controls.Add(numberOptionFilterField);
  1640. tRow.Cells.Add(tCellOption);
  1641. TextBox numberValueFilterField = new TextBox
  1642. {
  1643. ID = fieldSourceName + "NumberValue",
  1644. };
  1645. // Set value
  1646. SetTextboxValue(value, defaultValue, numberValueFilterField);
  1647. valueFilterFieldValue = numberValueFilterField.Text;
  1648. if (filterSize > 0)
  1649. {
  1650. numberValueFilterField.MaxLength = filterSize;
  1651. }
  1652. if (!filterWidth.IsEmpty)
  1653. {
  1654. numberValueFilterField.Width = filterWidth;
  1655. }
  1656. numberValueFilterField.EnableViewState = false;
  1657. tCellValue.Controls.Add(numberValueFilterField);
  1658. tRow.Cells.Add(tCellValue);
  1659. filterDefinition.OptionsControl = numberOptionFilterField;
  1660. filterDefinition.ValueControl = numberValueFilterField;
  1661. }
  1662. break;
  1663. case "site":
  1664. {
  1665. // Site selector
  1666. customPath = "~/CMSFormControls/Filters/SiteFilter.ascx";
  1667. }
  1668. break;
  1669. case "custom":
  1670. // Load custom path
  1671. {
  1672. if (String.IsNullOrEmpty(fieldPath))
  1673. {
  1674. throw new Exception("[UniGrid.AddFilterField]: Filter field path is not set");
  1675. }
  1676. customPath = fieldPath;
  1677. }
  1678. break;
  1679. default:
  1680. // Not supported filter type
  1681. throw new Exception("[UniGrid.AddFilterField]: Filter type '" + filterDefinition.Type + "' is not supported. Supported filter types: integer, double, bool, text, site, custom.");
  1682. }
  1683. // Else if filter path is defined use custom filter
  1684. if (customPath != null)
  1685. {
  1686. customPath = (customPath.StartsWithCSafe("~/") ? customPath : FilterDirectoryPath + customPath.TrimStart('/'));
  1687. // Add to the controls collection
  1688. CMSAbstractBaseFilterControl filterControl = LoadFilterControl(fieldPath, fieldSourceName, value, filterDefinition, customPath);
  1689. if (filterControl != null)
  1690. {
  1691. // Set default value
  1692. if (!String.IsNullOrEmpty(defaultValue))
  1693. {
  1694. filterControl.SelectedValue = defaultValue;
  1695. }
  1696. tCellValue.Controls.Add(filterControl);
  1697. }
  1698. tCellValue.Attributes["colspan"] = "2";
  1699. tRow.Cells.Add(tCellValue);
  1700. }
  1701. RaiseOnFilterFieldCreated(fieldSourceName, filterDefinition);
  1702. FilterFields[fieldSourceName] = filterDefinition;
  1703. filterTable.Rows.Add(tRow);
  1704. // Store initial filter state for potential UniGrid reset
  1705. if (filterDefinition.OptionsControl != null)
  1706. {
  1707. InitialFilterStateControls.Add(new KeyValuePair<Control, object>(filterDefinition.OptionsControl, optionFilterFieldValue));
  1708. }
  1709. if (filterDefinition.ValueControl != null)
  1710. {
  1711. if (!(filterDefinition.ValueControl is CMSAbstractBaseFilterControl))
  1712. {
  1713. InitialFilterStateControls.Add(new KeyValuePair<Control, object>(filterDefinition.ValueControl, valueFilterFieldValue));
  1714. }
  1715. }
  1716. }
  1717. /// <summary>
  1718. /// Sets the textbox value to the given value or default value if available
  1719. /// </summary>
  1720. /// <param name="value">Value to set</param>
  1721. /// <param name="defaultValue">Default value</param>
  1722. /// <param name="textBox">TextBox to set</param>
  1723. private static void SetTextboxValue(string value, string defaultValue, TextBox textBox)
  1724. {
  1725. // Set default value
  1726. if (!String.IsNullOrEmpty(defaultValue))
  1727. {
  1728. textBox.Text = defaultValue;
  1729. }
  1730. else
  1731. {
  1732. textBox.Text = value;
  1733. }
  1734. }
  1735. /// <summary>
  1736. /// Sets the DropDown value to the given value or default value if available
  1737. /// </summary>
  1738. /// <param name="value">Value to set</param>
  1739. /// <param name="defaultValue">Default value</param>
  1740. /// <param name="dropDown">DropDown to set</param>
  1741. private static void SetDropdownValue(string value, string defaultValue, DropDownList dropDown)
  1742. {
  1743. // Select filter option
  1744. try
  1745. {
  1746. if (!String.IsNullOrEmpty(defaultValue))
  1747. {
  1748. dropDown.SelectedValue = defaultValue;
  1749. }
  1750. else
  1751. {
  1752. dropDown.SelectedValue = value;
  1753. }
  1754. }
  1755. catch
  1756. {
  1757. }
  1758. }
  1759. /// <summary>
  1760. /// Loads the filter control
  1761. /// </summary>
  1762. /// <param name="fieldPath">Field path</param>
  1763. /// <param name="fieldSourceName">Field source name</param>
  1764. /// <param name="value">Field value</param>
  1765. /// <param name="filterDefinition">Filter definition</param>
  1766. /// <param name="path">Control path</param>
  1767. private CMSAbstractBaseFilterControl LoadFilterControl(string fieldPath, string fieldSourceName, string value, UniGridFilterField filterDefinition, string path)
  1768. {
  1769. // Load the filter control
  1770. CMSAbstractBaseFilterControl filterControl = this.LoadUserControl(path) as CMSAbstractBaseFilterControl;
  1771. if (filterControl != null)
  1772. {
  1773. // Setup the filter control
  1774. filterControl.ID = fieldSourceName;
  1775. filterControl.FilteredControl = this;
  1776. if (!RequestHelper.IsPostBack())
  1777. {
  1778. filterControl.Value = value;
  1779. }
  1780. filterDefinition.ValueControl = filterControl;
  1781. filterDefinition.ControlPath = fieldPath;
  1782. }
  1783. return filterControl;
  1784. }
  1785. /// <summary>
  1786. /// Creates filter show button.
  1787. /// </summary>
  1788. private void CreateFilterButton(Table filterTable)
  1789. {
  1790. if (!HideFilterButton && String.IsNullOrEmpty(FilterFormName))
  1791. {
  1792. // Add button to the bottom of the filter table
  1793. showButton = new CMSButton();
  1794. Literal ltlBreak = new Literal();
  1795. TableRow tRow = new TableRow();
  1796. TableCell tCell = new TableCell();
  1797. showButton.ID = "btnShow";
  1798. showButton.Text = GetString("general.show");
  1799. showButton.CssClass = "ContentButton";
  1800. showButton.Click += ShowButton_Click;
  1801. showButton.EnableViewState = false;
  1802. tCell.Controls.Add(showButton);
  1803. // If we remember the grid state we need to add the reset button to allow the user to restore the initial state
  1804. if (RememberState)
  1805. {
  1806. LinkButton resetButton = new LinkButton
  1807. {
  1808. ID = "btnReset",
  1809. Text = GetString("general.reset"),
  1810. EnableViewState = false,
  1811. };
  1812. resetButton.Style.Add("line-height", "2em");
  1813. resetButton.Style.Add("margin", "1em");
  1814. resetButton.Click += ResetButton_Click;
  1815. tCell.Controls.Add(resetButton);
  1816. }
  1817. ltlBreak.EnableViewState = false;
  1818. ltlBreak.Text = "<br /><br />";
  1819. tCell.Controls.Add(ltlBreak);
  1820. tCell.ColumnSpan = 2;
  1821. tCell.EnableViewState = false;
  1822. TableCell indentCell = new TableCell
  1823. {
  1824. EnableViewState = false,
  1825. Text = "&nbsp;"
  1826. };
  1827. tRow.Cells.Add(indentCell); // Indent 'Show' button
  1828. tRow.Cells.Add(tCell);
  1829. filterTable.Rows.Add(tRow);
  1830. pnlHeader.DefaultButton = showButton.ID;
  1831. }
  1832. }
  1833. /// <summary>
  1834. /// Sets filter to the grid view and save it to the view state.
  1835. /// </summary>
  1836. /// <param name="reloadData">Reload data</param>
  1837. protected override void SetFilter(bool reloadData, string where)
  1838. {
  1839. // Where can be empty string - it means that filter condition was added to WhereCondition property
  1840. if (where == null)
  1841. {
  1842. where = GetFilter();
  1843. }
  1844. // Filter by query string
  1845. if (FilterByQueryString && !reloadData)
  1846. {
  1847. string url = URLRewriter.CurrentURL;
  1848. foreach (string name in queryStringHashTable.Keys)
  1849. {
  1850. if (queryStringHashTable[name] != null)
  1851. {
  1852. string value = HttpContext.Current.Server.UrlEncode(queryStringHashTable[name].ToString());
  1853. url = URLHelper.AddParameterToUrl(url, name, value);
  1854. }
  1855. }
  1856. URLHelper.Redirect(url);
  1857. }
  1858. else
  1859. {
  1860. WhereClause = where;
  1861. if (!String.IsNullOrEmpty(where))
  1862. {
  1863. FilterIsSet = true;
  1864. }
  1865. if ((!DelayedReload) && (reloadData))
  1866. {
  1867. // Get data from database and set them to the grid view
  1868. ReloadData();
  1869. }
  1870. }
  1871. }
  1872. /// <summary>
  1873. /// Sets filter visibility depending on the UniGrid's configuration and number of objects.
  1874. /// </summary>
  1875. private void CheckFilterVisibility()
  1876. {
  1877. if (displayFilter)
  1878. {
  1879. if (FilterLimit > 0)
  1880. {
  1881. if (!String.IsNullOrEmpty(FilterFormName))
  1882. {
  1883. plcFilterForm.Visible = FilterIsSet || ShowFilter;
  1884. }
  1885. else
  1886. {
  1887. filter.Visible = FilterIsSet || ShowFilter;
  1888. }
  1889. }
  1890. }
  1891. else
  1892. {
  1893. filter.Visible = false;
  1894. plcFilterForm.Visible = false;
  1895. }
  1896. }
  1897. /// <summary>
  1898. /// Sorts UniGrid data source according to sort directive saved in viewstate.
  1899. /// </summary>
  1900. private void SortUniGridDataSource(object ds)
  1901. {
  1902. if (SortDirect != "")
  1903. {
  1904. // If source isn't empty
  1905. if (!DataHelper.DataSourceIsEmpty(ds))
  1906. {
  1907. // Set sort directive from viewstate
  1908. if (ds is DataTable)
  1909. {
  1910. // Data table
  1911. try
  1912. {
  1913. ((DataTable)(ds)).DefaultView.Sort = SortDirect;
  1914. }
  1915. catch
  1916. {
  1917. }
  1918. }
  1919. else if (ds is DataSet)
  1920. {
  1921. // DataSet
  1922. try
  1923. {
  1924. ((DataSet)(ds)).Tables[0].DefaultView.Sort = SortDirect;
  1925. ds = ((DataSet)(ds)).Tables[0].DefaultView;
  1926. }
  1927. catch
  1928. {
  1929. }
  1930. }
  1931. else if (ds is DataView)
  1932. {
  1933. // Data view
  1934. try
  1935. {
  1936. ((DataView)(ds)).Sort = SortDirect;
  1937. }
  1938. catch
  1939. {
  1940. }
  1941. }
  1942. }
  1943. }
  1944. }
  1945. /// <summary>
  1946. /// Changes sorting direction by specified column.
  1947. /// </summary>
  1948. /// <param name="orderByColumn">Column name to order by</param>
  1949. /// <param name="orderByString">Old order by string</param>
  1950. private void ChangeSortDirection(string orderByColumn, string orderByString)
  1951. {
  1952. orderByColumn = orderByColumn.Trim().TrimStart('[').TrimEnd(']').Trim();
  1953. orderByString = orderByString.Trim().TrimStart('[');
  1954. // If order by column is long text use CAST in ORDER BY part of query
  1955. if (TextColumns.Contains(orderByColumn))
  1956. {
  1957. if (orderByString.EndsWithCSafe("desc"))
  1958. {
  1959. SortDirect = String.Format("CAST([{0}] AS nvarchar(32)) asc", orderByColumn);
  1960. }
  1961. else
  1962. {
  1963. SortDirect = String.Format("CAST([{0}] AS nvarchar(32)) desc", orderByColumn);
  1964. }
  1965. }
  1966. else
  1967. {
  1968. string orderByDirection = "asc";
  1969. Match orderByMatch = OrderByRegex.Match(orderByString);
  1970. if (orderByMatch.Success)
  1971. {
  1972. if (orderByMatch.Groups[2].Success)
  1973. {
  1974. orderByDirection = orderByMatch.Groups[2].Value;
  1975. }
  1976. }
  1977. // Sort by the same column -> the other directon
  1978. if (orderByString.StartsWithCSafe(orderByColumn))
  1979. {
  1980. SortDirect = (orderByDirection == "desc") ? String.Format("[{0}] asc", orderByColumn) : String.Format("[{0}] desc", orderByColumn);
  1981. }
  1982. // Sort by a new column -> implicitly direction is ASC
  1983. else
  1984. {
  1985. SortDirect = String.Format("[{0}] asc", orderByColumn);
  1986. }
  1987. }
  1988. }
  1989. /// <summary>
  1990. /// Returns List of selected Items.
  1991. /// </summary>
  1992. private List<string> GetSelectedItems()
  1993. {
  1994. return GetHiddenValues(SelectionHiddenField);
  1995. }
  1996. /// <summary>
  1997. /// Sets selection values for UniGrid.
  1998. /// </summary>
  1999. /// <param name="values">Values to set</param>
  2000. private void SetSectedItems(IEnumerable<string> values)
  2001. {
  2002. SetHiddenValues(values, SelectionHiddenField, null);
  2003. }
  2004. /// <summary>
  2005. /// Returns List of deselected Items.
  2006. /// </summary>
  2007. private List<string> GetDeselectedItems()
  2008. {
  2009. return GetHiddenValues(hidDeSelection);
  2010. }
  2011. /// <summary>
  2012. /// Returns List of newly selected Items.
  2013. /// </summary>
  2014. private List<string> GetNewlySelectedItems()
  2015. {
  2016. return GetHiddenValues(hidNewSelection);
  2017. }
  2018. /// <summary>
  2019. /// Returns array list from hidden field.
  2020. /// </summary>
  2021. /// <param name="field">Hidden field with values separated with |</param>
  2022. private static List<string> GetHiddenValues(HiddenField field)
  2023. {
  2024. string hiddenValue = field.Value.Trim('|');
  2025. var list = new List<string>();
  2026. string[] values = hiddenValue.Split('|');
  2027. foreach (string value in values)
  2028. {
  2029. if (!list.Contains(value))
  2030. {
  2031. list.Add(value);
  2032. }
  2033. }
  2034. list.Remove("");
  2035. return list;
  2036. }
  2037. /// <summary>
  2038. /// Sets values into hidden field.
  2039. /// </summary>
  2040. /// <param name="values">Values to set</param>
  2041. /// <param name="actionsField">Hidden field</param>
  2042. private static void SetHiddenValues(IEnumerable<string> values, HiddenField actionsField, HiddenField hashField)
  2043. {
  2044. if (values != null)
  2045. {
  2046. if (actionsField != null)
  2047. {
  2048. // Build the list of actions
  2049. StringBuilder sb = new StringBuilder();
  2050. sb.Append("|");
  2051. foreach (string value in values)
  2052. {
  2053. sb.Append(value);
  2054. sb.Append("|");
  2055. }
  2056. // Action IDs
  2057. string actions = sb.ToString();
  2058. actionsField.Value = actions;
  2059. // Actions hash
  2060. if (hashField != null)
  2061. {
  2062. hashField.Value = ValidationHelper.GetHashString(actions);
  2063. }
  2064. }
  2065. }
  2066. }
  2067. /// <summary>
  2068. /// Clears all selected items from hidden values.
  2069. /// </summary>
  2070. /// <param name="field">Hidden field</param>
  2071. private static void ClearHiddenValues(HiddenField field)
  2072. {
  2073. if (field != null)
  2074. {
  2075. field.Value = "";
  2076. }
  2077. }
  2078. /// <summary>
  2079. /// Sets hidden field with actions hashes.
  2080. /// </summary>
  2081. private void SetActionsHash()
  2082. {
  2083. if (ActionsID.Count > 0)
  2084. {
  2085. SetHiddenValues(ActionsID, hidActions, hidActionsHash);
  2086. }
  2087. }
  2088. /// <summary>
  2089. /// Sets pager control.
  2090. /// </summary>
  2091. private void SetPager()
  2092. {
  2093. Pager.PagedControl = this;
  2094. }
  2095. /// <summary>
  2096. /// Sets the sort direction if current request is sorting.
  2097. /// </summary>
  2098. private void ProcessSorting()
  2099. {
  2100. // Get current event target
  2101. string uniqieId = ValidationHelper.GetString(Request.Params["__EVENTTARGET"], String.Empty);
  2102. // Get current argument
  2103. string eventargument = ValidationHelper.GetString(Request.Params["__EVENTARGUMENT"], String.Empty);
  2104. if ((uniqieId == GridView.UniqueID) && (eventargument.StartsWithCSafe("Sort")))
  2105. {
  2106. string orderByColumn = Convert.ToString(eventargument.Split('$')[1]);
  2107. if (SortColumns.Contains(orderByColumn.ToLowerCSafe()))
  2108. {
  2109. // If sorting is called for the first time and default sorting (OrderBy property) is set
  2110. if ((SortDirect == "") && !string.IsNullOrEmpty(OrderBy))
  2111. {
  2112. ChangeSortDirection(orderByColumn, OrderBy);
  2113. }
  2114. else
  2115. {
  2116. ChangeSortDirection(orderByColumn, SortDirect);
  2117. }
  2118. }
  2119. }
  2120. }
  2121. /// <summary>
  2122. /// Returns true if current request was fired by page change or filter show button.
  2123. /// </summary>
  2124. private bool EventRequest()
  2125. {
  2126. if (URLHelper.IsPostback())
  2127. {
  2128. // Get current event target
  2129. string uniqieId = ValidationHelper.GetString(Request.Params["__EVENTTARGET"], String.Empty);
  2130. // Get current argument
  2131. string eventargument = ValidationHelper.GetString(Request.Params["__EVENTARGUMENT"], String.Empty).ToLowerCSafe();
  2132. // Check whether current request is paging
  2133. if (!String.IsNullOrEmpty(uniqieId) && (uniqieId == GridView.UniqueID) && eventargument.StartsWithCSafe("page"))
  2134. {
  2135. return true;
  2136. }
  2137. // Check whether show button is defined
  2138. if (showButton != null)
  2139. {
  2140. // If button name is not empty => button fire postback
  2141. if (!string.IsNullOrEmpty(Request.Params[showButton.UniqueID]))
  2142. {
  2143. return true;
  2144. }
  2145. }
  2146. // Check whether show button in basic form is defined
  2147. if (FilterForm.SubmitButton != null)
  2148. {
  2149. // If submit button name is not empty => button fire postback
  2150. if (!string.IsNullOrEmpty(Request.Params[FilterForm.SubmitButton.UniqueID]))
  2151. {
  2152. return true;
  2153. }
  2154. }
  2155. }
  2156. // Non-paging request by default
  2157. return false;
  2158. }
  2159. /// <summary>
  2160. /// Returns icon file for current theme or from default if current doesn't exist.
  2161. /// </summary>
  2162. /// <param name="iconfile">Icon file name</param>
  2163. private string GetActionImage(string iconfile)
  2164. {
  2165. if (File.Exists(MapPath(ImageDirectoryPath + iconfile)))
  2166. {
  2167. return (ImageDirectoryPath + iconfile);
  2168. }
  2169. // Short path to the icon
  2170. if (ControlsExtensions.RenderShortIDs)
  2171. {
  2172. return UIHelper.GetShortImageUrl(UIHelper.UNIGRID_ICONS, iconfile);
  2173. }
  2174. return GetImageUrl("Design/Controls/UniGrid/Actions/" + iconfile);
  2175. }
  2176. /// <summary>
  2177. /// Register unigrid commands scripts.
  2178. /// </summary>
  2179. private void RegisterCmdScripts()
  2180. {
  2181. StringBuilder builder = new StringBuilder();
  2182. // Redir function
  2183. if (EditActionUrl != null)
  2184. {
  2185. builder.Append("function UG_Redir(url) { document.location.replace(url); return false; }\n");
  2186. }
  2187. builder.Append("function ", RELOAD_PREFIX, ClientID, "() { ", Page.ClientScript.GetPostBackEventReference(this, "Reload"), " }\n");
  2188. builder.Append("function UG_Reload() { ", RELOAD_PREFIX, ClientID, "(); }\n");
  2189. // Actions
  2190. builder.Append(
  2191. @"
  2192. function Get(id) {
  2193. return document.getElementById(id);
  2194. }
  2195. function ", CMD_PREFIX, ClientID, @"(name, arg) {
  2196. var nameObj = Get('", hidCmdName.ClientID, @"');
  2197. var argObj = Get('", hidCmdArg.ClientID, @"');
  2198. if ((nameObj != null) && (argObj != null)) {
  2199. nameObj.value = name;
  2200. argObj.value = arg;
  2201. ", Page.ClientScript.GetPostBackEventReference(this, "UniGridAction"), @"
  2202. }
  2203. return false;
  2204. }
  2205. function ", DESTROY_OBJECT_PREFIX, ClientID, @"(arg) {"
  2206. , CMD_PREFIX, ClientID, @"('#destroyobject',arg);
  2207. }");
  2208. if (showSelection)
  2209. {
  2210. // Selection - click
  2211. builder.Append(
  2212. "function ", SELECT_PREFIX, ClientID, @"(checkBox, arg) {
  2213. if (checkBox == null) return;
  2214. var sel = Get('", GetSelectionFieldClientID(), @"');
  2215. var newSel = Get('", hidNewSelection.ClientID, @"');
  2216. var deSel = Get('", hidDeSelection.ClientID, @"');
  2217. if ((sel == null) || (newSel == null) || (deSel == null)) return;
  2218. if (newSel.value == '') {
  2219. newSel.value = '|';
  2220. }
  2221. if (deSel.value == '') {
  2222. deSel.value = '|'
  2223. }
  2224. if (sel.value == '') {
  2225. sel.value = '|'
  2226. }
  2227. if (checkBox.checked) {
  2228. sel.value += arg + '|'
  2229. if (deSel.value.indexOf('|' + arg + '|') >= 0) {
  2230. deSel.value = deSel.value.replace('|' + arg + '|', '|')
  2231. }
  2232. else {
  2233. newSel.value += arg + '|'
  2234. }
  2235. }
  2236. else {
  2237. sel.value = sel.value.replace('|' + arg + '|', '|')
  2238. if (newSel.value.indexOf('|' + arg + '|') >= 0) {
  2239. newSel.value = newSel.value.replace('|' + arg + '|', '|')
  2240. }
  2241. else {
  2242. deSel.value += arg + '|'
  2243. }
  2244. }
  2245. }
  2246. ");
  2247. // Selection - select all
  2248. builder.Append(
  2249. "function ", SELECT_ALL_PREFIX, ClientID, @"(chkBox) {
  2250. var elems = document.getElementsByTagName('INPUT');
  2251. var re = new RegExp('", ClientID, @"');
  2252. for(i=0; i<elems.length; i++) {
  2253. if(elems[i].type == 'checkbox') {
  2254. if(elems[i].id.match(re)) {
  2255. if((!elems[i].id != chkBox.id) && (chkBox.checked != elems[i].checked)) {
  2256. elems[i].click();
  2257. }
  2258. }
  2259. }
  2260. }
  2261. }
  2262. ");
  2263. // Selection - clear
  2264. builder.Append(
  2265. "function ", CLEAR_SELECTION_PREFIX, ClientID, @"() {
  2266. var inp = document.getElementsByTagName('input');
  2267. if (inp != null) {
  2268. for (var i = 0; i< inp.length; i++) {
  2269. if ((inp[i].type.toLowerCase() == 'checkbox') && (inp[i].id.match(/^", ClientID, @"/i))) {
  2270. inp[i].checked = false;
  2271. }
  2272. }
  2273. }
  2274. var sel = Get('", GetSelectionFieldClientID(), @"');
  2275. var newSel = Get('", hidNewSelection.ClientID, @"');
  2276. var deSel = Get('", hidDeSelection.ClientID, @"');
  2277. if (sel != null) {
  2278. sel.value = '';
  2279. }
  2280. if (newSel != null) {
  2281. newSel.value = '';
  2282. }
  2283. if (deSel != null) {
  2284. deSel.value = '';
  2285. }
  2286. }
  2287. ");
  2288. // Selection - IsSelectionEmpty
  2289. builder.Append(
  2290. "function ", CHECK_SELECTION_PREFIX, ClientID, @"() {
  2291. var sel = Get('", GetSelectionFieldClientID(), @"');
  2292. var items = sel.value;
  2293. return !(items != '' && items != '|');
  2294. }
  2295. ");
  2296. if (resetSelection)
  2297. {
  2298. builder.Append("if (", CLEAR_SELECTION_PREFIX, ClientID, ") { ", CLEAR_SELECTION_PREFIX, ClientID, "(); }");
  2299. }
  2300. }
  2301. ScriptHelper.RegisterStartupScript(this, typeof(string), "UniGrid_" + ClientID, ScriptHelper.GetScript(builder.ToString()));
  2302. }
  2303. /// <summary>
  2304. /// Sets basic form filter.
  2305. /// </summary>
  2306. private void SetBasicFormFilter()
  2307. {
  2308. // Get alternative form layout if defined
  2309. AlternativeFormInfo afi = AlternativeFormInfoProvider.GetAlternativeFormInfo(FilterFormName);
  2310. if (afi != null)
  2311. {
  2312. // Get form info
  2313. FormInfo fi = FormHelper.GetFormInfo(FilterFormName, true);
  2314. if (fi != null)
  2315. {
  2316. FilterForm.OnAfterSave += BasicForm_OnAfterSave;
  2317. // Set form info
  2318. FilterForm.FormInformation = fi;
  2319. // Set filter button
  2320. FilterForm.SubmitButton.ID = "btnShow";
  2321. FilterForm.SubmitButton.Text = GetString("general.show");
  2322. FilterForm.SubmitButton.CssClass = "ContentButton";
  2323. FilterForm.SubmitButton.RegisterHeaderAction = false;
  2324. // Set layout
  2325. if (!string.IsNullOrEmpty(afi.FormLayout))
  2326. {
  2327. FilterForm.FormLayout = afi.FormLayout;
  2328. }
  2329. else
  2330. {
  2331. // Indent filter
  2332. Literal ltlBreak = new Literal();
  2333. ltlBreak.EnableViewState = false;
  2334. ltlBreak.Text = "<br />";
  2335. plcFilterForm.Controls.Add(ltlBreak);
  2336. }
  2337. FilterForm.CheckFieldEmptiness = false;
  2338. FilterForm.LoadData(FilterFormData);
  2339. }
  2340. }
  2341. }
  2342. /// <summary>
  2343. /// Handles OnAfterSave event of basic form.
  2344. /// </summary>
  2345. /// <param name="sender">Sender</param>
  2346. /// <param name="e">Event argument</param>
  2347. private void BasicForm_OnAfterSave(object sender, EventArgs e)
  2348. {
  2349. // Set where clause
  2350. WhereClause = FilterForm.GetWhereCondition();
  2351. FilterIsSet = !string.IsNullOrEmpty(WhereClause);
  2352. Pager.UniPager.CurrentPage = 1;
  2353. ReloadData();
  2354. }
  2355. /// <summary>
  2356. /// Checks whether user is authorized for specified action.
  2357. /// </summary>
  2358. /// <param name="actionName">Action name</param>
  2359. private void CheckActionAndRedirect(string actionName)
  2360. {
  2361. // Get the action
  2362. Action action = GridActions.GetAction(actionName);
  2363. if ((action != null) && (!string.IsNullOrEmpty(action.ModuleName)))
  2364. {
  2365. CurrentUserInfo user = CMSContext.CurrentUser;
  2366. string siteName = CMSContext.CurrentSiteName;
  2367. // Check module permissions
  2368. if (!string.IsNullOrEmpty(action.Permissions) && !user.IsAuthorizedPerResource(action.ModuleName, action.Permissions, siteName))
  2369. {
  2370. RedirectToAccessDenied(action.ModuleName, action.Permissions);
  2371. }
  2372. // Check module UI elements
  2373. if (!string.IsNullOrEmpty(action.UIElements) && !user.IsAuthorizedPerUIElement(action.ModuleName, action.UIElements.Split(';'), siteName))
  2374. {
  2375. RedirectToUIElementAccessDenied(action.ModuleName, action.UIElements);
  2376. }
  2377. }
  2378. }
  2379. #endregion
  2380. #region "IUniPageable Members"
  2381. /// <summary>
  2382. /// Pager data item.
  2383. /// </summary>
  2384. public object PagerDataItem
  2385. {
  2386. get
  2387. {
  2388. return UniGridView.DataSource;
  2389. }
  2390. set
  2391. {
  2392. UniGridView.DataSource = value;
  2393. }
  2394. }
  2395. /// <summary>
  2396. /// Pager control.
  2397. /// </summary>
  2398. public UniPager UniPagerControl
  2399. {
  2400. get;
  2401. set;
  2402. }
  2403. /// <summary>
  2404. /// Occurs when the control bind data.
  2405. /// </summary>
  2406. public event EventHandler<EventArgs> OnPageBinding;
  2407. /// <summary>
  2408. /// Occurs when the pager change the page and current mode is postback => reload data
  2409. /// </summary>
  2410. public event EventHandler<EventArgs> OnPageChanged;
  2411. /// <summary>
  2412. /// Evokes control databind.
  2413. /// </summary>
  2414. public virtual void ReBind()
  2415. {
  2416. if (OnPageChanged != null)
  2417. {
  2418. OnPageChanged(this, null);
  2419. }
  2420. ReloadData();
  2421. }
  2422. #endregion
  2423. }