EnVisageOnline/Main/Source/EnVisage/Controllers/StrategicGoalController.cs

262 lines
11 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
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;
namespace EnVisage.Controllers
{
[Authorize]
public class StrategicGoalController : BaseController
{
/// <summary>
/// GET: /Types/
/// </summary>
/// <returns>Empty view</returns>
[HttpGet]
[AreaSecurity(area = Areas.StrategicGoals, level = AccessLevel.Read)]
public ActionResult Index()
{
if (!SecurityManager.CheckSecurityObjectPermission(Areas.StrategicGoals, AccessLevel.Read))
return Redirect("/");
return View();
}
/// <summary>
/// Returns JSON Types list with filters and sort for jQuery DataTables
/// </summary>
[HttpPost]
[AreaSecurity(area = Areas.StrategicGoals, level = AccessLevel.Read)]
public JsonResult Index(JQueryDataTablesModel jQueryDataTablesModel)
{
int totalRecordCount;
int searchRecordCount;
var goals = GetGoals(startIndex: jQueryDataTablesModel.iDisplayStart,
pageSize: jQueryDataTablesModel.iDisplayLength, sortedColumns: jQueryDataTablesModel.GetSortedColumns(),
totalRecordCount: out totalRecordCount, searchRecordCount: out searchRecordCount, searchString: jQueryDataTablesModel.sSearch,
filters: jQueryDataTablesModel.sSearch_);
return this.DataTablesJson(items: goals,
totalRecords: totalRecordCount,
totalDisplayRecords: searchRecordCount,
sEcho: jQueryDataTablesModel.sEcho);
}
private IEnumerable<StrategicGoalModel> GetGoals(int startIndex,
int pageSize,
IEnumerable<SortedColumn> sortedColumns,
out int totalRecordCount,
out int searchRecordCount,
string searchString,
ReadOnlyCollection<string> filters)
{
var manager = (new StrategicGoalManager(DbContext));
var query = manager.GetStrategicGoals();
var filteredQuery = query;
//filter
if (!string.IsNullOrWhiteSpace(searchString))
{
filteredQuery = filteredQuery.Where(c => c.Name.ToLower().Contains(searchString.ToLower()));
}
if (!string.IsNullOrWhiteSpace(filters[0]))
filteredQuery = filteredQuery.Where(c => c.Name.ToLower().Equals(filters[0].ToLower()));
//sort
foreach (var sortedColumn in sortedColumns)
{
switch (sortedColumn.PropertyName)
{
case "Id":
if (sortedColumn.Direction == SortingDirection.Ascending)
filteredQuery = filteredQuery.OrderBy(c => c.Id);
else
filteredQuery = filteredQuery.OrderByDescending(c => c.Id);
break;
case "StartDate":
if (sortedColumn.Direction == SortingDirection.Ascending)
filteredQuery = filteredQuery.OrderBy(c => c.StartDate);
else
filteredQuery = filteredQuery.OrderByDescending(c => c.StartDate);
break;
case "EndDate":
if (sortedColumn.Direction == SortingDirection.Ascending)
filteredQuery = filteredQuery.OrderBy(c => c.EndDate);
else
filteredQuery = filteredQuery.OrderByDescending(c => c.EndDate);
break;
case "NbrProjects":
if (sortedColumn.Direction == SortingDirection.Ascending)
filteredQuery = filteredQuery.OrderBy(c => c.NbrProjects);
else
filteredQuery = filteredQuery.OrderByDescending(c => c.NbrProjects);
break;
default:
if (sortedColumn.Direction == SortingDirection.Ascending)
filteredQuery = filteredQuery.OrderBy(c => c.Name);
else
filteredQuery = filteredQuery.OrderByDescending(c => c.Name);
break;
}
}
totalRecordCount = query.Count();
searchRecordCount = filteredQuery.Count();
return filteredQuery.Skip(startIndex).Take(pageSize).ToList();
}
// GET: /Type/Edit/5
[HttpGet]
[AreaSecurity(area = Areas.StrategicGoals, level = AccessLevel.Write)]
public ActionResult Edit(Guid? id)
{
try
{
var manager = new StrategicGoalManager(DbContext);
var model = manager.GetStrategicGoalById(id) ?? new StrategicGoalModel();
return PartialView("_editGoal", model);
}
catch (Exception exception)
{
LogException(exception);
}
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
// POST: /Type/Edit/5
// Чтобы защититься от атак чрезмерной передачи данных, включите определенные свойства, для которых следует установить привязку. Дополнительные
// сведения см. в статье http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAjax]
[ValidateAntiForgeryToken]
[AreaSecurity(area = Areas.StrategicGoals, level = AccessLevel.Write)]
public ActionResult Edit(StrategicGoalModel model)
{
if (model != null && model.Id != Guid.Empty && ContentLocker.IsLock("StrategicGoal", model.Id.ToString(), User.Identity.GetUserName()))
{
ModelState.AddModelError(string.Empty, "This goal is currently being updated by another user. Please attempt your edit again later.");
return new FailedJsonResult(ModelState);
}
try
{
if (model == null)
throw new ArgumentNullException("model");
model.TrimStringProperties();
var manager = new StrategicGoalManager(DbContext);
manager.Save(model);
DbContext.SaveChanges();
ContentLocker.RemoveLock("StrategicGoal", model.Id.ToString(), User.Identity.GetUserName());
return new SuccessJsonResult();
}
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);
ModelState.AddModelError(string.Empty, "Cannot save goal. Try again later.");
}
}
catch (Exception exception) // handle any unexpected error
{
LogException(exception);
ModelState.AddModelError(string.Empty, "Cannot save goal. Try again later.");
}
return new FailedJsonResult(ModelState);
}
// GET: /Type/Delete/5
[HttpGet]
[AreaSecurity(area = Areas.StrategicGoals, level = AccessLevel.Write)]
public ActionResult Delete(Guid? id)
{
if (!id.HasValue || id == Guid.Empty)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
try
{
var manager = new StrategicGoalManager(DbContext);
var model = manager.GetStrategicGoalById(id);
if (model == null)
return HttpNotFound();
return PartialView("_deleteGoal", model);
}
catch (Exception exception)
{
LogException(exception);
}
return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
}
// POST: /Type/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
[AreaSecurity(area = Areas.StrategicGoals, level = AccessLevel.Write)]
public ActionResult Delete(Guid id)
{
if (ContentLocker.IsLock("StrategicGoal", id.ToString(), User.Identity.GetUserName()))
{
ModelState.AddModelError(string.Empty, "This goal is currently being updated by another user. Please attempt your edit again later.");
return new FailedJsonResult(ModelState);
}
try
{
var manager = new StrategicGoalManager(DbContext);
var dbObj = DbContext.StrategicGoals.Where(x => x.Id == id).FirstOrDefault();
if (dbObj == null)
throw new InvalidOperationException(string.Format("System cannot delete goal {0} because it does not exist", id));
DbContext.StrategicGoal2Company.RemoveRange(DbContext.StrategicGoal2Company.Where(s2c => s2c.StrategicGoalId == dbObj.Id));
DbContext.StrategicGoal2Project.RemoveRange(DbContext.StrategicGoal2Project.Where(s2c => s2c.StrategicGoalId == dbObj.Id));
DbContext.StrategicGoals.Remove(dbObj);
DbContext.SaveChanges();
ContentLocker.RemoveLock("StrategicGoal", dbObj.Id.ToString(), User.Identity.GetUserName());
return new SuccessJsonResult();
}
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);
ModelState.AddModelError(string.Empty, "Cannot delete goal. Try again later.");
}
}
catch (Exception exception) // handle any unexpected error
{
LogException(exception);
ModelState.AddModelError(string.Empty, "Cannot delete goal. Try again later.");
}
return new FailedJsonResult(ModelState);
}
}
}