using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Mvc; using EnVisage.App_Start; using EnVisage.Code; using EnVisage.Code.BLL; using EnVisage.Models; using jQuery.DataTables.Mvc; using System.Collections.ObjectModel; using EnVisage.Code.Validation; using Resources; namespace EnVisage.Controllers { [Authorize] public class ExpenditureController : BaseController { #region Models /// /// An UI representation of expenditures to be displayed as list items /// public class ListExpenditure { public Guid Id { get; set; } public string Name { get; set; } public int ExpenditureCount { get; set; } } #endregion #region Actions /// /// GET: /Expenditures/ /// /// Empty view [HttpGet] [AreaSecurity(area = Areas.Expenditures, level = AccessLevel.Read)] public ActionResult Index() { return View(); } /// /// Returns JSON expenditure list with filters and sort for jQuery DataTables /// [HttpPost] [AreaSecurity(area = Areas.Expenditures, level = AccessLevel.Read)] public JsonResult Index(JQueryDataTablesModel jQueryDataTablesModel) { int totalRecordCount; int searchRecordCount; var expenditures = GetExpenditures(startIndex: jQueryDataTablesModel.iDisplayStart, pageSize: jQueryDataTablesModel.iDisplayLength, sortedColumns: jQueryDataTablesModel.GetSortedColumns(), totalRecordCount: out totalRecordCount, searchRecordCount: out searchRecordCount, searchString: jQueryDataTablesModel.sSearch); return this.DataTablesJson(items: expenditures, totalRecords: totalRecordCount, totalDisplayRecords: searchRecordCount, sEcho: jQueryDataTablesModel.sEcho); } // GET: /Expenditure/Edit/5 [AreaSecurity(area = Areas.Expenditures, level = AccessLevel.Write)] public ActionResult Edit(Guid? id) { ExpenditureModel model; try { var manager = new ExpenditureManager(DbContext); model = (ExpenditureModel)manager.Load(id) ?? new ExpenditureModel(); } catch (BLLException blEx) { if (blEx.DisplayError) { //SetErrorScript(message: blEx.Message); ModelState.AddModelError(string.Empty, blEx.Message); return new FailedJsonResult(ModelState); } LogException(blEx); return new FailedJsonResult(); } catch (Exception exception) { LogException(exception); return new FailedJsonResult(); } return View(model); } // POST: /Expenditure/Edit/5 // Чтобы защититься от атак чрезмерной передачи данных, включите определенные свойства, для которых следует установить привязку. Дополнительные // сведения см. в статье http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] [AreaSecurity(area = Areas.Expenditures, level = AccessLevel.Write)] public ActionResult Edit(ExpenditureModel model) { if (ContentLocker.IsLock("Expenditure", model.Id.ToString(), User.Identity.GetUserName())) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); model.TrimStringProperties(); if (ModelState.IsValid) { try { var manager = new ExpenditureManager(DbContext); manager.Save(model); DbContext.SaveChanges(); ContentLocker.RemoveLock("Expenditure", model.Id.ToString(), User.Identity.GetUserName()); return RedirectToAction("Index"); } catch (BLLException blEx) // handle any system specific error { // display error message if required if (blEx.DisplayError) ModelState.AddModelError(string.Empty, blEx.Message); else // if display not requried then display modal form with general error message { LogException(blEx); SetErrorScript(); } } catch (Exception exception) // handle any unexpected error { LogException(exception); SetErrorScript(); } } // return empty model with validation messages (if any) return View(model); } // GET: /Expenditure/Delete/5 [AreaSecurity(area = Areas.Expenditures, level = AccessLevel.Write)] public ActionResult Delete(Guid? id) { if (id == null || id == Guid.Empty) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); var model = new ExpenditureModel(); try { var manager = new ExpenditureManager(DbContext); model = (ExpenditureModel)manager.Load(id); if (model == null) return HttpNotFound(); if (model.CategoriesCount > 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest, Messages.Expenditure_Delete_HasCategoriesAssigned_Error); } catch (BLLException blEx) { if (blEx.DisplayError) SetErrorScript(message: blEx.Message); else { LogException(blEx); SetErrorScript(); } } catch (Exception exception) { LogException(exception); SetErrorScript(); } return View(model); } // POST: /Expenditure/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] [AreaSecurity(area = Areas.Expenditures, level = AccessLevel.Write)] public ActionResult DeleteConfirmed(ExpenditureModel model) { if (ContentLocker.IsLock("Expenditure", model.Id.ToString(), User.Identity.GetUserName())) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); var manager = new ExpenditureManager(DbContext); var dbObj = manager.Load(model.Id, false); if (dbObj == null) return HttpNotFound(); if (dbObj.ExpenditureCategory.Count > 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest, Messages.Expenditure_Delete_HasCategoriesAssigned_Error); DbContext.Expenditures.Remove(dbObj); DbContext.SaveChanges(); ContentLocker.RemoveLock("Expenditure", dbObj.Id.ToString(), User.Identity.GetUserName()); return RedirectToAction("Index"); } #endregion #region Private Methods private IList GetExpenditures(int startIndex, int pageSize, ReadOnlyCollection sortedColumns, out int totalRecordCount, out int searchRecordCount, string searchString) { var query = DbContext.Expenditures.Select( c => new ListExpenditure {Id = c.Id, Name = c.Name, ExpenditureCount = c.ExpenditureCategory.Count}); //filter if (!string.IsNullOrWhiteSpace(searchString)) { query = query.Where(c => c.Name.ToLower().Contains(searchString.ToLower())); } //sort foreach (var sortedColumn in sortedColumns) { switch (sortedColumn.PropertyName) { case "Id": query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Id) : query.OrderByDescending(c => c.Id); break; case "ExpenditureCount": query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.ExpenditureCount) : query.OrderByDescending(c => c.ExpenditureCount); break; default: query = sortedColumn.Direction == SortingDirection.Ascending ? query.OrderBy(c => c.Name) : query.OrderByDescending(c => c.Name); break; } } totalRecordCount = DbContext.Expenditures.Count(); searchRecordCount = query.Count(); var list = query.Skip(startIndex).Take(pageSize).ToList(); return list; } #endregion } }