using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; using EnVisage; using EnVisage.Code; using EnVisage.Code.BLL; using EnVisage.Code.HtmlHelpers; using EnVisage.Models; using Microsoft.AspNet.Identity; using jQuery.DataTables.Mvc; using EnVisage.App_Start; namespace EnVisage.Controllers { [Authorize] public class ClientsController : BaseController { /// /// GET: /Clients/ /// /// Empty view [HttpGet] [AreaSecurityAttribute(area = Areas.Clients, level = AccessLevel.Read)] public ActionResult Index() { return View(); } /// /// Returns JSON client list with filters and sort for jQuery DataTables /// [HttpPost] [AreaSecurityAttribute(area = Areas.Clients, level = AccessLevel.Read)] public JsonResult Index(JQueryDataTablesModel jQueryDataTablesModel) { int totalRecordCount; int searchRecordCount; var clients = GetClients(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: clients, totalRecords: totalRecordCount, totalDisplayRecords: searchRecordCount, sEcho: jQueryDataTablesModel.sEcho); } private IList GetClients(int startIndex, int pageSize, ReadOnlyCollection sortedColumns, out int totalRecordCount, out int searchRecordCount, string searchString, ReadOnlyCollection filters) { ClientManager mngr = new ClientManager(this.DbContext); var query = mngr.GetListReadOnly(); //filter if (!string.IsNullOrWhiteSpace(searchString)) { query = query.Where(c => c.Name.ToLower().Contains(searchString.ToLower())); } if(!string.IsNullOrWhiteSpace(filters[0])) query = query.Where(c => c.Name.ToLower().Contains(filters[0].ToLower())); if (!string.IsNullOrWhiteSpace(filters[1])) query = query.Where(c => c.ProjectsCount.ToString().Contains(filters[1])); if (!string.IsNullOrWhiteSpace(filters[2]) && filters[2] != "All companies") { var q = new List(); foreach(var companies in query.Select(x => x.Companies)) { foreach (var company in companies) { if (company.ToLower().Contains(filters[2].ToLower())) { foreach (var c in query.Where(c => c.Companies.Contains(company))) { if (!q.Any(x => x.Id == c.Id) && c.Companies.Any(x => x == filters[2])) q.Add(c); } } } } query = q.AsEnumerable(); } //sort foreach (var sortedColumn in sortedColumns) { switch (sortedColumn.PropertyName) { case "Id": if(sortedColumn.Direction == SortingDirection.Ascending) query = query.OrderBy(c => c.Id); else query = query.OrderByDescending(c => c.Id); break; case "ProjectsCount": if (sortedColumn.Direction == SortingDirection.Ascending) query = query.OrderBy(c => c.ProjectsCount); else query = query.OrderByDescending(c => c.ProjectsCount); break; case "ClientNumber": if (sortedColumn.Direction == SortingDirection.Ascending) query = query.OrderBy(c => c.ClientNumber); else query = query.OrderByDescending(c => c.ClientNumber); break; default: if(sortedColumn.Direction == SortingDirection.Ascending) query = query.OrderBy(c => c.Name); else query = query.OrderByDescending(c => c.Name); break; } } totalRecordCount = DbContext.Clients.Count(); searchRecordCount = query.Count(); return query.Skip(startIndex).Take(pageSize).ToList(); } // GET: /Clients/Edit/5 [HttpGet] [AreaSecurityAttribute(area = Areas.Clients, level = AccessLevel.Write)] public ActionResult Edit(Guid? id) { var model = new ClientModel(); try { var manager = new ClientManager(DbContext); model = (ClientModel)manager.LoadWithChildCollections(id) ?? new ClientModel(); } catch (BLLException blEx) { if (blEx.DisplayError) SetErrorScript(message: blEx.Message); else { LogException(blEx); SetErrorScript(); } } catch (Exception exception) { LogException(exception); SetErrorScript(); } return View(model); } // POST: /Clients/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] [AreaSecurityAttribute(area = Areas.Clients, level = AccessLevel.Write)] public ActionResult Edit(ClientModel model) { if (ContentLocker.IsLock("Clients", model.Id.ToString(), User.Identity.Name)) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); model.TrimStringProperties(); if (ModelState.IsValid) { try { var manager = new ClientManager(DbContext); manager.Save(model); DbContext.SaveChanges(); ContentLocker.RemoveLock("Clients", model.Id.ToString(), User.Identity.Name); 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); } [HttpGet] [AreaSecurityAttribute(area = Areas.Clients, level = AccessLevel.Write)] public ActionResult Delete(Guid? id) { if (id == null || id == Guid.Empty) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); var model = new ClientModel(); try { var manager = new ClientManager(DbContext); model = (ClientModel) manager.Load(id); if (model == null) return HttpNotFound(); if (model.ProjectsCount > 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Client has projects assigned and could not be deleted"); } catch (BLLException blEx) { if (blEx.DisplayError) SetErrorScript(message: blEx.Message); else { LogException(blEx); SetErrorScript(); } } catch (Exception exception) { LogException(exception); SetErrorScript(); } return View(model); } [HttpGet] [AreaSecurityAttribute(area = Areas.Clients, level = AccessLevel.Write)] public ActionResult AddContact(Guid Id) { if (Id == null || Id == new Guid()) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } return PartialView("_addContact", new ContactModel(Id)); } [HttpPost] [AreaSecurityAttribute(area = Areas.Clients, level = AccessLevel.Write)] public ActionResult AddContact(ContactModel model) { //if (model.ScenarioId != Guid.Empty && ContentLocker.IsLock("Scenarios", model.ScenarioId.ToString(), User.Identity.Name)) // return new HttpStatusCodeResult(HttpStatusCode.BadRequest); model.TrimStringProperties(); if (ModelState.IsValid) { try { model.Type = ContactType.ClientContact; var newcontact = new Contact(); model.CopyTo(newcontact); if (newcontact.Id == Guid.Empty) newcontact.Id = Guid.NewGuid(); DbContext.Contacts.Add(newcontact); DbContext.SaveChanges(); } 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 Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri); } // POST: /Clients/Delete/5 [HttpPost] [ValidateAntiForgeryToken] [AreaSecurityAttribute(area = Areas.Clients, level = AccessLevel.Write)] public ActionResult Delete(ClientModel model) { if (ContentLocker.IsLock("Clients", model.Id.ToString(), User.Identity.Name)) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); var manager = new ClientManager(DbContext); var dbObj = manager.Load(model.Id, false); if (dbObj == null) return HttpNotFound(); if (dbObj.Projects.Count > 0) return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Client has projects assigned and could not be deleted"); DbContext.Company2Client.RemoveRange(DbContext.Company2Client.Where(c2s => c2s.ClientId == dbObj.Id)); DbContext.Contact2Project.RemoveRange(DbContext.Contact2Project.Where(c2s => c2s.Contact.ParentId == dbObj.Id)); DbContext.Contacts.RemoveRange(DbContext.Contacts.Where(c => c.ParentId == dbObj.Id)); DbContext.Clients.Remove(dbObj); DbContext.SaveChanges(); ContentLocker.RemoveLock("Clients", dbObj.Id.ToString(), User.Identity.Name); return RedirectToAction("Index"); } // GET: /User/Edit/5 [AreaSecurityAttribute(area = Areas.Clients, level = AccessLevel.Write)] public ActionResult EditContact(string Id) { if (string.IsNullOrEmpty(Id) || Id == "JSVar") { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var ContactId = new Guid(Id); var contact = (from c in DbContext.Contacts where c.Id == ContactId select c).FirstOrDefault(); if (contact == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); else { return PartialView("_addContact", (ContactModel)contact); } } [HttpPost] [ValidateAntiForgeryToken] [AreaSecurityAttribute(area = Areas.Clients, level = AccessLevel.Write)] public ActionResult EditContact(ContactModel model) { model.TrimStringProperties(); //if (model.Id == new Guid()) model.Id = Guid.NewGuid(); if (ModelState.IsValid) { try { var manager = new ContactManager(DbContext); manager.Save(model); DbContext.SaveChanges(); ContentLocker.RemoveLock("Contact", model.Id.ToString(), User.Identity.Name); return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri); } 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 Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri); } [AreaSecurityAttribute(area = Areas.Clients, level = AccessLevel.Write)] public ActionResult DeleteContact(string Id) { if (string.IsNullOrEmpty(Id) || Id == "JSVar") { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var ContactId = new Guid(Id); var contact = (from c in DbContext.Contacts where c.Id == ContactId select c).FirstOrDefault(); if (ContactId == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); else { DbContext.Contacts.Remove(contact); DbContext.SaveChanges(); } return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri); } } }