using System; using System.Collections.Generic; using System.Data; using System.Data.Entity.Validation; using System.Diagnostics; using System.Net; using System.Web.Mvc; using System.Xml.Linq; using System.Linq; using Pilotfish.Afx.ComponentModel; using Pilotfish.Afx.Mvc; using Pilotfish.Afx.Services.Integration; using Pilotfish.Afx.Services.Workflows; using Pilotfish.Afx.Services.Workflows.Entities; using Pilotfish.Afx.ViewModels; using Neo.Legitimate.NewRouteRequest.Models; using System.Text; using Neo.Legitimate.Data.Models; using Neo.Legitimate.Common; using Pilotfish.Afx.Services.Audits; namespace Neo.Legitimate.NewRouteRequest.Controllers { public class NewRouteRequestController : Controller { #region Constructor public NewRouteRequestController() : base(new NewRouteDatabase()) { } #endregion #region Console public ActionResult Console(long workflowid, long itemid) { var consoleUrl = "~/NewRouteRequest/Console?workflowid=" + workflowid + "&itemid=" + itemid + "&t=" + DateTime.Now.Ticks; //ensure t (ticks) parameter is present to prevent caching if (Request.QueryString["t"] == null) { return Redirect(consoleUrl); } var workflowDatabase = new WorkflowsDatabase(); if (!workflowDatabase.CheckWorkflowInstanceSecurity(workflowid, itemid, Profile.UserName)) { var returnUrl = Convert.ToBase64String(Encoding.ASCII.GetBytes(consoleUrl)); return Redirect(Url.Content("~/Error/ShowSecurityError?error=WORKFLOWACCESSSECURITY&workflowid=" + workflowid + "&itemid=" + itemid + "&returnUrl=" + returnUrl)); } return View("Console", GetViewModelInternal(workflowid, itemid)); } #endregion #region Save [HttpPost] public JsonResult Save(NewRouteRequestDetail value) { var changes = new List(); var auditDb = new AuditsDatabase(); if (value.NewRouteRequestDetailID == Database.NewID) { value.CreatedDate = DateTime.Now; value.CreatedByID = Profile.UserID; value.UpdatedDate = DateTime.Now; value.UpdatedByID = Profile.UserID; Database.Insert(value); } else { var routeDb = new NewRouteDatabase(); //don't use database as we need the values refreshed every time var existingModel = routeDb.GetNewRouteRequest(value.NewRouteRequestDetailID, Profile.UserID); if (existingModel != null && existingModel.UpdatedDate.ToLongTimeString() != value.UpdatedDate.ToLongTimeString()) { return Json(new { Result = "CONFLICT", Message = "The record has been modified by someone else. Please try again." }); } value.UpdatedDate = DateTime.Now; value.UpdatedByID = Profile.UserID; #region value.Nodes foreach (var node in value.Nodes) { if (node.NewRouteRouteNodeID > 0) { Database.Update(node); } else { Database.Insert(node); } } if (value.RemovedNodes != null) { foreach (var removedNode in value.RemovedNodes) { Database.Context.Entry(removedNode).State = System.Data.Entity.EntityState.Deleted; } } #endregion Database.Update(value); changes.AddRange(auditDb.GetEntityDifferences(existingModel, value, "NewRouteRequestDetailID")); } try { Database.Save(); Database.Context.Pr_NewRouteRequestPostSave(value.NewRouteRequestDetailID); if (changes.Count > 0) { auditDb.WriteEntries(2 /*Application*/, 2 /*Updated*/, changes, 1002 /*NewRouteRequestDetails*/, value.NewRouteRequestDetailID, Profile.UserID); } } catch (DbEntityValidationException dbEx) { foreach (var validationError in dbEx.EntityValidationErrors.SelectMany(validationErrors => validationErrors.ValidationErrors)) { return Json(new { Result = "ERROR", Message = string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) }); } } catch (Exception ex) { return Json(new { Result = "ERROR", Message = string.Format("Error: {0}", new LegitimateDatabase().GetInnermostMessage(ex)) }); } return Json(new WorkflowSaveResult { Id = value.NewRouteRequestDetailID, WorkflowInstanceID = (value.WorkflowInstanceID ?? 0) }); } #endregion #region GetViewModelInternal private WorkflowConsoleViewModelBase GetViewModelInternal(long workflowid, long itemid, bool includeLookups = true) { var projDb = new NewRouteDatabase(); //don't use database as we need the values refreshed every time var workflowDatabase = new WorkflowsDatabase(); var value = projDb.GetNewRouteRequest(itemid, Profile.UserID); if (value == null) { throw new Exception("Error initialising object data"); } if (Profile.Roles == null) { throw new Exception("Current user does not have any roles."); } //Re-assign the current task to the user if a) it is assigned to the system and b) the user is in the role linked to the task if (value.WorkflowInstanceID.HasValue) { workflowDatabase.ReAssignWorkflowInstanceGroupTask(value.WorkflowInstanceID.Value, Profile.UserID, "", Profile.UserID); } var vm = new WorkflowsDatabase().GetWorkflowConsoleViewModel(workflowid, (value.WorkflowInstanceID.HasValue ? value.WorkflowInstanceID.Value : -1), itemid, Profile.UserID, Profile.Roles, Profile.WorkflowBuddies); if (vm == null) { throw new Exception("Error initialising view model data"); } if (itemid < 0) { SetWorkflowTemplateDefaults(value, (IEnumerable)vm.WorkflowTemplateDefaults); } #region get defaults if new request if (itemid < 0) { //var integrationStore = new SqlIntegrationStore(); //try //{ // integrationStore.Open(); // var employee = integrationStore.GetData("Employees", "EmployeeNumber=" + Profile.UserID).FirstNode; // if (employee != null) // { // value.RequestedBy = employee.ToString(SaveOptions.DisableFormatting); // } //} //finally //{ // integrationStore.Close(); //} } #endregion #region load lookups var lookups = new List(); if (includeLookups) { var integrationStore = new SqlIntegrationStore(); try { integrationStore.Open(); lookups.Add(new LookupList("NodeWaypointTypes", integrationStore.GetDataEntities("WaypointTypes", string.Empty))); } finally { integrationStore.Close(); } } #endregion #if DEBUG foreach (var wp in ((WorkflowInstance)vm.WorkflowInstance).WorkflowInstanceParticipants) { wp.UserID = Profile.UserID; } #endif //if (itemid > 0) //{ //} value.RemovedNodes = new List(); vm.Lookups = lookups; vm.Value = value; return vm; } #endregion #region GetViewModel [HttpGet] public string GetViewModel(long workflowid, long itemid) { var workflowDatabase = new WorkflowsDatabase(); if (!workflowDatabase.CheckWorkflowInstanceSecurity(workflowid, itemid, Profile.UserName)) { throw new Exception("Security error trying to access GetViewModel"); } return GetViewModelInternal(workflowid, itemid, false).ToJson(JsonSerializerOptions.FormatDateTime); } #endregion #region SetWorkflowTemplateDefaults static void SetWorkflowTemplateDefaults(NewRouteRequestDetail value, IEnumerable defaults) { } #endregion #region JSON endpoints // All JSON endpoints require [HttpPost] to prevent JSON hijacking. // With [HttpPost], returning arrays is allowed. // See http://haacked.com/archive/2009/06/25/json-hijacking.aspx #endregion } }