using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using EnVisage; using EnVisage.App_Start; using EnVisage.Code; using EnVisage.Code.BLL; using EnVisage.Code.HtmlHelpers; using EnVisage.Models; using Microsoft.AspNet.Identity; using jQuery.DataTables.Mvc; using System.Collections.ObjectModel; namespace EnVisage.Controllers { [Authorize] public class StrategicGoalController : BaseController { /// /// GET: /Types/ /// /// Empty view [HttpGet] [AreaSecurityAttribute(area = Areas.StrategicGoals, level = AccessLevel.Read)] public ActionResult Index() { if (!SecurityManager.CheckSecurityObjectPermission(Areas.StrategicGoals, AccessLevel.Read)) return Redirect("/"); return View(); } /// /// Returns JSON Types list with filters and sort for jQuery DataTables /// [HttpPost] [AreaSecurityAttribute(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 GetGoals(int startIndex, int pageSize, IEnumerable sortedColumns, out int totalRecordCount, out int searchRecordCount, string searchString, ReadOnlyCollection filters) { //var query = from spg in DbContext.StrategicGoal2Project // group new { spg.StrategicGoal, spg } by new // { // Id =spg.StrategicGoal.Id, // spg.StrategicGoal.Name, // EndDate = (DateTime?)spg.StrategicGoal.EndDate, // StartDate = (DateTime?)spg.StrategicGoal.StartDate, // spg.StrategicGoal.Description, // spg.StrategicGoal.Color // } into g // select new StrategicGoalModel() // { // Id= g.Key.Id, // Name= g.Key.Name, // Description= g.Key.Description, // NbrProjects = g.Count(p => p.spg.Id != null), // StartDate = (DateTime?)g.Key.StartDate, // EndDate = (DateTime?)g.Key.EndDate, // Color = g.Key.Color // }; var query = from c in DbContext.StrategicGoals select new StrategicGoalModel() { Id = c.Id, Name = c.Name, NbrProjects = c.StrategicGoal2Project.Select(x => x.Id).Count(), Description = c.Description, StartDate = c.StartDate.Value, EndDate = c.EndDate.Value, Color = c.Color //, //Companies = c.StrategicGoal2Company.Select(x => x.Company).ToList() }; 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] [AreaSecurityAttribute(area = Areas.StrategicGoals, level = AccessLevel.Write)] public ActionResult Edit(Guid? id) { var model = new StrategicGoalModel(); try { if (id.HasValue && !id.Value.Equals(Guid.Empty)) { var manager = new StrategicGoalManager(DbContext); model = (StrategicGoalModel)manager.Load(id.Value); if (model == null) model = new StrategicGoalModel(); } model.CompanyId = model.Companies.Select(x => x.Id).ToList(); } catch (BLLException blEx) { if (blEx.DisplayError) SetErrorScript(message: blEx.Message); else { LogException(blEx); SetErrorScript(); } } catch (Exception exception) { LogException(exception); SetErrorScript(); } return PartialView("_editGoal", model); } // POST: /Type/Edit/5 // Чтобы защититься от атак чрезмерной передачи данных, включите определенные свойства, для которых следует установить привязку. Дополнительные // сведения см. в статье http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] [AreaSecurityAttribute(area = Areas.StrategicGoals, level = AccessLevel.Write)] public ActionResult Edit(StrategicGoalModel model) { if (ContentLocker.IsLock("StrategicGoal", model.Id.ToString(), User.Identity.Name)) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); model.TrimStringProperties(); if (ModelState.IsValid) { try { var manager = new StrategicGoalManager(DbContext); manager.Save(model); DbContext.SaveChanges(); ContentLocker.RemoveLock("StrategicGoal", model.Id.ToString(), User.Identity.Name); return PartialView("_editGoal", model); } 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 empty model with validation messages (if any) HttpContext.Response.StatusCode = 500; HttpContext.Response.Clear(); return PartialView("_editGoal", model); } // GET: /Type/Delete/5 [HttpGet] [AreaSecurityAttribute(area = Areas.StrategicGoals, level = AccessLevel.Write)] public ActionResult Delete(Guid? id) { if (id == null || id == Guid.Empty) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); var model = new StrategicGoalModel(); try { var manager = new StrategicGoalManager(DbContext); model = (StrategicGoalModel)manager.Load(id) ; if (model == null) return HttpNotFound(); } catch (BLLException blEx) { if (blEx.DisplayError) SetErrorScript(message: blEx.Message); else { LogException(blEx); SetErrorScript(); } } catch (Exception exception) { LogException(exception); SetErrorScript(); } return View(model); } // POST: /Type/Delete/5 [HttpPost] [ValidateAntiForgeryToken] [AreaSecurityAttribute(area = Areas.StrategicGoals, level = AccessLevel.Write)] public ActionResult Delete(StrategicGoalModel model, Guid deleteStrategicGoalId) { if (ContentLocker.IsLock("StrategicGoal", deleteStrategicGoalId.ToString(), User.Identity.Name)) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); var manager = new StrategicGoalManager(DbContext); var dbObj = DbContext.StrategicGoals.Where(x => x.Id == deleteStrategicGoalId).FirstOrDefault(); if (dbObj == null) return HttpNotFound(); 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.Name); return RedirectToAction("Index"); } } }