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

/tags/1.31/src/RapidWeb/DynamicPages/Excel/ExcelUploadPanel.cs

#
C# | 344 lines | 251 code | 40 blank | 53 comment | 17 complexity | 395351d47fcf6afafac3f0bf9726d651 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1
  1. /***************************************************************************
  2. Copyright (C) 2010 RapidWebDev Organization (Author: Eunge, Legal Name: Jian Liu, Email: eunge.liu@gmail.com)
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ***************************************************************************/
  14. using System;
  15. using System.IO;
  16. using System.Data;
  17. using System.Data.OleDb;
  18. using System.Collections;
  19. using System.Collections.Generic;
  20. using System.Collections.ObjectModel;
  21. using System.Configuration;
  22. using System.Linq;
  23. using System.Data.Linq;
  24. using System.Threading;
  25. using System.Text.RegularExpressions;
  26. using System.Web;
  27. using System.Web.Security;
  28. using System.Web.UI;
  29. using System.Web.UI.HtmlControls;
  30. using System.Web.UI.WebControls;
  31. using System.Web.UI.WebControls.WebParts;
  32. using System.Xml.Linq;
  33. using BaoJianSoft.Web.Extensions.Controls;
  34. using BaoJianSoft.Common;
  35. using BaoJianSoft.Web.Extensions.Properties;
  36. namespace BaoJianSoft.Web.Extensions.DynamicPages
  37. {
  38. /// <summary>
  39. /// Excel upload panel.
  40. /// </summary>
  41. public sealed class ExcelUploadPanel : Panel
  42. {
  43. private GridViewPanel GridViewSuccess, GridViewFailure;
  44. private MessagePanel messagePanel;
  45. /// <summary>
  46. /// Construct Excel Upload Panel.
  47. /// </summary>
  48. public ExcelUploadPanel(IExcelParser parser)
  49. {
  50. this.Parser = parser;
  51. this.PageSize = 100;
  52. }
  53. /// <summary>
  54. /// Set/get excel parser.
  55. /// </summary>
  56. public IExcelParser Parser { get; private set; }
  57. /// <summary>
  58. /// Set/get page size for displaying success/failure upload records.
  59. /// The default value is 100.
  60. /// </summary>
  61. public int PageSize { get; set; }
  62. /// <summary>
  63. /// Get successful uploaded record count.
  64. /// </summary>
  65. public int SuccessCount
  66. {
  67. get
  68. {
  69. if (this.Uploaded == null) return 0;
  70. return this.Uploaded.Tables[ExcelParser.SUCCESS].Rows.Count;
  71. }
  72. }
  73. /// <summary>
  74. /// Get failure uploaded record count.
  75. /// </summary>
  76. public int FailureCount
  77. {
  78. get
  79. {
  80. if (this.Uploaded == null) return 0;
  81. return this.Uploaded.Tables[ExcelParser.FAILURE].Rows.Count;
  82. }
  83. }
  84. /// <summary>
  85. /// Set/get dataset for uploaded excel.
  86. /// </summary>
  87. private DataSet Uploaded
  88. {
  89. get { return HttpContext.Current.Session[string.Format("ExcelUpload::{0}", SessionManager.ObjectId)] as DataSet; }
  90. set { HttpContext.Current.Session[string.Format("ExcelUpload::{0}", SessionManager.ObjectId)] = value; }
  91. }
  92. /// <summary>
  93. /// Called when user uploads a excel file and web server has stored it into local disk.
  94. /// </summary>
  95. /// <param name="excelFilePath"></param>
  96. public void Upload(string excelFilePath)
  97. {
  98. try
  99. {
  100. this.Uploaded = this.Parser.Parse(excelFilePath);
  101. int successCount = this.Uploaded.Tables[ExcelParser.SUCCESS].Rows.Count;
  102. int failureCount = this.Uploaded.Tables[ExcelParser.FAILURE].Rows.Count;
  103. this.GridViewSuccess.DataBind(0);
  104. this.GridViewFailure.DataBind(0);
  105. string message = string.Format(Resources.ExcelHaveNotCommitToDatabase, successCount, failureCount);
  106. if (failureCount == 0)
  107. {
  108. this.messagePanel.ShowConfirm(message);
  109. }
  110. else
  111. {
  112. this.messagePanel.ShowWarning(message);
  113. }
  114. }
  115. catch (InvalidOperationException exp)
  116. {
  117. this.messagePanel.ShowWarning(exp.Message);
  118. }
  119. catch (Exception exp)
  120. {
  121. Logger.Instance(this).Error(exp);
  122. this.messagePanel.ShowError(Resources.OccurExceptionHaveLogTryLater);
  123. }
  124. }
  125. /// <summary>
  126. /// Clear all cached failure or successs upload records.
  127. /// </summary>
  128. public void Clear()
  129. {
  130. try
  131. {
  132. this.Uploaded = null;
  133. this.GridViewSuccess.DataBind(0);
  134. this.GridViewFailure.DataBind(0);
  135. }
  136. catch (InvalidOperationException exp)
  137. {
  138. this.messagePanel.ShowWarning(exp.Message);
  139. }
  140. catch (Exception exp)
  141. {
  142. Logger.Instance(this).Error(exp);
  143. this.messagePanel.ShowError(Resources.OccurExceptionHaveLogTryLater);
  144. }
  145. }
  146. /// <summary>
  147. /// Save the successful uploaded records.
  148. /// </summary>
  149. public void Save()
  150. {
  151. try
  152. {
  153. IList objects = this.Parser.Parse(this.Uploaded);
  154. ExcelParserObjectEventArgs e = new ExcelParserObjectEventArgs(objects, objects.Count);
  155. this.Parser.OnSaving(e);
  156. // clear caching
  157. this.Uploaded = null;
  158. this.GridViewSuccess.DataBind(0);
  159. this.GridViewFailure.DataBind(0);
  160. this.messagePanel.ShowConfirm(Resources.SaveUploadedDataSuccessfully);
  161. this.Parser.OnSaved(e);
  162. }
  163. catch (ThreadAbortException)
  164. {
  165. }
  166. catch (InvalidOperationException exp)
  167. {
  168. this.messagePanel.ShowWarning(exp.Message);
  169. }
  170. catch (Exception exp)
  171. {
  172. Logger.Instance(this).Error(exp);
  173. this.messagePanel.ShowError(Resources.OccurExceptionHaveLogTryLater);
  174. }
  175. }
  176. /// <summary>
  177. /// Raises the System.Web.UI.Control.Init event.
  178. /// </summary>
  179. /// <param name="e"></param>
  180. protected override void OnInit(EventArgs e)
  181. {
  182. base.OnInit(e);
  183. this.messagePanel = new MessagePanel { ID = "MessagePanelExcelUploadPanel" };
  184. this.Controls.Add(this.messagePanel);
  185. this.BuildGridViews();
  186. this.EnsureChildControls();
  187. }
  188. private void BuildGridViews()
  189. {
  190. this.BuildFailureGridView();
  191. this.BuildSuccessGridView();
  192. }
  193. private void BuildFailureGridView()
  194. {
  195. GridViewConfiguration configurationFailure = new GridViewConfiguration()
  196. {
  197. EntityName = this.Parser.Document.WorksheetName,
  198. PageSize = this.PageSize,
  199. PrimaryKeyFieldName = ExcelParser.ROW_INDEX,
  200. EnabledCheckBoxField = false,
  201. };
  202. List<GridViewFieldConfiguration> fields = new List<GridViewFieldConfiguration>()
  203. {
  204. new GridViewFieldConfiguration(ExcelParser.ROW_INDEX, "Excel"+ Resources.Line)
  205. {
  206. HeaderStyle = new TableItemStyle() { Width = new Unit("80px") },
  207. ItemStyle = new TableItemStyle() { HorizontalAlign = HorizontalAlign.Center, Width = new Unit("80px") },
  208. Sortable = false
  209. },
  210. new GridViewFieldConfiguration(ExcelParser.EXCEPTION, Resources.DetailedErrorInformation){ Sortable = false },
  211. };
  212. configurationFailure.Fields = fields;
  213. this.GridViewFailure = new GridViewPanel { ID = "GridViewFailure", Configuration = configurationFailure, Visible = false };
  214. this.GridViewFailure.DataSourceLoading += new EventHandler<DataSourceLoadEventArgs>(OnGridViewDataSourceLoading);
  215. HtmlGenericControl header = new HtmlGenericControl("h4") { InnerText = string.Format(Resources.InvalidUploadDataInWorksheet, this.Parser.Document.WorksheetName) };
  216. header.Style["color"] = "red";
  217. Container containerFailure = new Container() { Transparent = false };
  218. containerFailure.Controls.Add(header);
  219. containerFailure.Controls.Add(this.GridViewFailure);
  220. this.Controls.Add(containerFailure);
  221. }
  222. private void BuildSuccessGridView()
  223. {
  224. GridViewConfiguration configuration = new GridViewConfiguration()
  225. {
  226. EntityName = this.Parser.Document.WorksheetName,
  227. PageSize = this.PageSize,
  228. PrimaryKeyFieldName = this.Parser.Document.PrimaryKeyField.FieldName,
  229. EnabledCheckBoxField = false,
  230. DeleteButton = new ButtonConfiguration { Type = ButtonTypes.DeleteImage }
  231. };
  232. List<GridViewFieldConfiguration> fields = new List<GridViewFieldConfiguration>();
  233. foreach (ExcelField excelField in this.Parser.Document.Fields)
  234. {
  235. if (excelField.IsDisplayed)
  236. {
  237. GridViewFieldConfiguration field = new GridViewFieldConfiguration(excelField.FieldName, excelField.FieldName);
  238. switch (excelField.FieldType)
  239. {
  240. case ExcelFieldTypes.Double:
  241. case ExcelFieldTypes.Decimal:
  242. case ExcelFieldTypes.Int32:
  243. case ExcelFieldTypes.DateTime:
  244. field.ItemStyle = new TableItemStyle() { HorizontalAlign = HorizontalAlign.Center, Wrap = false };
  245. field.DisplayFormat = excelField.DisplayedFormat;
  246. break;
  247. }
  248. fields.Add(field);
  249. }
  250. }
  251. configuration.Fields = fields;
  252. this.GridViewSuccess = new GridViewPanel { ID = "GridViewSuccess", Configuration = configuration, Visible = false };
  253. this.GridViewSuccess.DataSourceLoading += new EventHandler<DataSourceLoadEventArgs>(OnGridViewDataSourceLoading);
  254. this.GridViewSuccess.Deleting += (sender, e) =>
  255. {
  256. if (this.Uploaded != null)
  257. {
  258. DataTable datatable = this.Uploaded.Tables[ExcelParser.SUCCESS];
  259. var rowsToDelete = datatable.AsEnumerable().Where(row => row[this.Parser.Document.PrimaryKeyField.FieldName].ToString() == e.PrimaryKey).ToList();
  260. foreach (DataRow rowToDelete in rowsToDelete)
  261. datatable.Rows.Remove(rowToDelete);
  262. datatable.AcceptChanges();
  263. this.GridViewSuccess.DataBind();
  264. }
  265. };
  266. HtmlGenericControl header = new HtmlGenericControl("h4") { InnerText = string.Format(Resources.SuccessfulWorksheetUploadInformation, this.Parser.Document.WorksheetName) };
  267. header.Style["color"] = "green";
  268. Container containerSuccess = new Container();
  269. containerSuccess.Controls.Add(header);
  270. containerSuccess.Controls.Add(this.GridViewSuccess);
  271. this.Controls.Add(containerSuccess);
  272. }
  273. void OnGridViewDataSourceLoading(object sender, DataSourceLoadEventArgs e)
  274. {
  275. GridViewPanel gridview = sender as GridViewPanel;
  276. DataTable datatable = null;
  277. if (this.Uploaded != null)
  278. {
  279. if (gridview == this.GridViewSuccess) datatable = this.Uploaded.Tables[ExcelParser.SUCCESS];
  280. else datatable = this.Uploaded.Tables[ExcelParser.FAILURE];
  281. DataTable clonedTable = datatable.Copy();
  282. var selectedRows = clonedTable.Select("", e.SortExpression).Skip(e.PageIndex * e.PageSize).Take(e.PageSize).ToList();
  283. foreach (DataRow row in clonedTable.Rows)
  284. {
  285. if (!selectedRows.Contains(row)) row.Delete();
  286. }
  287. clonedTable.AcceptChanges();
  288. var clonedDataView = clonedTable.AsDataView();
  289. clonedDataView.Sort = e.SortExpression;
  290. e.RecordCount = datatable.Rows.Count;
  291. e.DataSource = clonedDataView;
  292. }
  293. else
  294. {
  295. e.RecordCount = 0;
  296. e.DataSource = null;
  297. }
  298. gridview.Visible = e.RecordCount > 0;
  299. }
  300. }
  301. }