/// <summary> /// Lists folders from the Imap connection. /// </summary> /// <param name="folderPath"></param> /// <param name="dtRequestModel"></param> /// <returns></returns> public ActionResult Folders(string folderPath = "", [ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel = null) { using (var imap = EnsureConnection()) { List <Mailbox> folders; folders = imap.ListMailboxes(folderPath, "*").Where(x => FOLDERS.Contains(x.Name)).Select(x => imap.Examine(x.Name)).ToList(); var subscribes = imap.ListSuscribesMailboxes("", "*"); var result = View("Index", new SupportModel { Mailboxes = folders.AsQueryable(), Messages = new List <MailMessage>().AsQueryable(), AccountSetup = true }); if (dtRequestModel != null) { return(Query(result, dtRequestModel, ControllerContext)); } return(result); } }
public async Task <IActionResult> TableData([FromBody] DataTablesRequestModel req) { return(Json(await _dataTables.PopulateTable(req, _context.Users, x => { x.Password = ""; return x; }))); }
public ActionResult Query([ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { var result = View(this, GetAlerts()); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetNoStore(); return(Query(result, dtRequestModel)); }
public ActionResult List([ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { ViewResult result = View(new LinqMetaData().Device.WithPermissions()); if (dtRequestModel == null) { return(result); } return(Query(result, dtRequestModel)); }
public ActionResult List([ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { ViewResult result = View(GetModel()); if (dtRequestModel == null) { return(result); } return(Query(result, dtRequestModel)); }
public ActionResult List([ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { ViewResult result = View(new LinqMetaData().ExceptionLog); if (dtRequestModel == null) { return(result); } return(Query(result, dtRequestModel)); }
public ActionResult Index([ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { var result = View(); if (dtRequestModel != null) { return(Query(result, dtRequestModel)); } return(View()); }
public ActionResult List(int?locationId, int?organizationId, [ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { var result = (Request.IsAjaxRequest() || ControllerContext.IsChildAction) ? (ViewResultBase)PartialView(GetListModel(locationId, organizationId)) : View(GetListModel(locationId, organizationId)); if (dtRequestModel == null) { return(result); } return(Query(result, dtRequestModel)); }
public ActionResult Index(int?locationId, int?patientId, [ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { IQueryable <TreatmentEntity> treatments; if (locationId.HasValue) { var location = new LocationEntity(locationId.Value); if (location.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_Location); } if (!Permissions.UserHasPermission("View", location)) { throw new HttpException(401, SharedRes.Error.Unauthorized_Location); } treatments = new LinqMetaData().Treatment.Where(x => x.Patient.LocationId == locationId.Value); } else if (patientId.HasValue) { var patient = new PatientEntity(patientId.Value); if (patient.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_Patient); } if (!Permissions.UserHasPermission("View", patient)) { throw new HttpException(401, SharedRes.Error.Unauthorized_Patient); } treatments = new LinqMetaData().Treatment.Where(x => x.PatientId == patientId.Value); } else { treatments = new LinqMetaData().Treatment.WithPermissions(); } ViewResult result = View(treatments); if (dtRequestModel == null) { return(result); } return(Query(result, dtRequestModel)); }
public virtual JsonResult GetCvCompetenceListAjax(DataTablesRequestModel model) { int sortColumnId = 0; string sortDirection = String.Empty; if (model.Order.Count() > 0) { sortColumnId = model.Order.FirstOrDefault().Column; sortDirection = model.Order.FirstOrDefault().Dir; } var result = CvCompetencesManager.GetCvCompetenceDataTable(model.Length, model.Start, model.Search.Value, sortColumnId, sortDirection); return(Json(result, JsonRequestBehavior.AllowGet)); }
public ActionResult Messages(string folderPath = "INBOX", [ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel = null) { using (var imap = EnsureConnection()) { var messages = new List <MailMessage>(); var msgCount = imap.SelectMailbox(folderPath).NumMsg; if (msgCount > 0) { var msgs = imap.Search(SearchCondition.Deleted().Not()).Select( x => imap.GetMessage(x, true, true, new[] { "date", "subject", "from", "content-type", "to", "cc", "message-id" })); if (folderPath == "INBOX") { UpdateInboxCount( msgs.Count(x => (x.Flags & Flags.Recent) == Flags.Recent || (x.Flags & Flags.Seen) == 0), Membership.GetUser().GetUserEntity()); } messages.AddRange(msgs); } var result = View("Index", new SupportModel { Mailboxes = new List <Mailbox>().AsQueryable(), Messages = messages.AsQueryable(), CurrentFolder = folderPath, AccountSetup = true }); if (dtRequestModel != null) { return(Query(result, dtRequestModel, ControllerContext)); } return(result); } }
public ActionResult New(NewPurchaseModel model, [ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { var user = Membership.GetUser().GetUserEntity(); if (Session["cart"] as List <Models.Purchase> == null) { Session["cart"] = new List <Models.Purchase>(); } model.Cart = ((List <Models.Purchase>)Session["cart"]); model.Cards = user.UserCreditCards.AsQueryable(); var result = View(model); if (dtRequestModel == null) { return(result); } return(Query(result, dtRequestModel)); }
/// <summary> /// Main Query logic just used in a static context so some controllers could inherit other types and still use the Datatables functionality. /// </summary> /// <param name="viewResult"></param> /// <param name="model"></param> /// <param name="controllerContext"></param> /// <returns></returns> public static JsonResult Query(ViewResultBase viewResult, DataTablesRequestModel model, ControllerContext controllerContext) { // Render the view so the DataTables initialization model is rebuilt. StringWriter bitbucket = new StringWriter(); IView view = viewResult.View ?? ViewEngines.Engines.FindView(controllerContext, string.IsNullOrEmpty(viewResult.ViewName) ? controllerContext.RouteData.Values["action"].ToString() : viewResult.ViewName, null).View; view.Render(new ViewContext(controllerContext, view, viewResult.ViewData, viewResult.TempData, bitbucket), bitbucket); // Get set of table models from the ViewData. var dataTableInitModels = controllerContext.Controller.ViewData["DataTablesModels"] as Dictionary <string, object>; if (dataTableInitModels == null) { throw new HttpException(500, ControllerRes.DataTables.InitializationModelNotFound); } // Get the model for the table making the request. var dataTableInit = dataTableInitModels[model.epicTableId]; // If the object isn't defined in the cache, we don't know what columns to return. if (dataTableInit == null) { throw new HttpException(500, ControllerRes.DataTables.ColumnDefinitionNotFound); } var objectType = dataTableInit.GetType().GetGenericArguments()[0]; var method = typeof(DataTablesController).GetMethods(BindingFlags.NonPublic | BindingFlags.Static).First( x => x.Name == "Query" && x.IsGenericMethod); // call Query<TEntity>() return((JsonResult)method.MakeGenericMethod(new[] { objectType }).Invoke(null, new[] { dataTableInit, model })); }
public ActionResult List(int?locationId, int?organizationId, PurchaseHistoryModel model, [ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { if (Request.HttpMethod == "POST" && ModelState.IsValid) { var user = Membership.GetUser().GetUserEntity(); var transaction = new Transaction(IsolationLevel.ReadCommitted, "purchase transfer"); try { var fromDevice = model.FromDevice; var toDevice = model.ToDevice; var from = new PurchaseHistoryEntity { DeviceId = model.FromDeviceId, LocationId = fromDevice.LocationId, UserId = user.UserId, PurchaseTime = DateTime.UtcNow, ScansPurchased = -model.Quantity, AmountPaid = 0, TransactionId = string.Empty, PurchaseNotes = String.Format(Purchase.TransferFrom, SharedRes.Formats.Device.FormatWith(fromDevice), SharedRes.Formats.Device.FormatWith(toDevice)) }; transaction.Add(from); from.Save(); var to = new PurchaseHistoryEntity { DeviceId = model.ToDeviceId, LocationId = toDevice.LocationId, UserId = user.UserId, PurchaseTime = DateTime.UtcNow, ScansPurchased = model.Quantity, AmountPaid = 0, TransactionId = string.Empty, PurchaseNotes = String.Format(Purchase.TransferFrom, SharedRes.Formats.Device.FormatWith(fromDevice), SharedRes.Formats.Device.FormatWith(toDevice)) }; transaction.Add(to); to.Save(); transaction.Add(fromDevice); fromDevice.ScansAvailable -= model.Quantity; fromDevice.Save(); transaction.Add(toDevice); toDevice.ScansAvailable += model.Quantity; toDevice.Save(); transaction.Commit(); } catch (Exception ex) { transaction.Rollback(); ModelState.AddModelError("", Purchase.TransferFailed); Log.Error(Purchase.TransferFailed, ex); } finally { transaction.Dispose(); } } if (!organizationId.HasValue) { if (!locationId.HasValue) { model.Puchases = new LinqMetaData().PurchaseHistory.WithPermissions(); } else { var location = new LocationEntity(locationId.Value); if (location.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_Location); } if (!Permissions.UserHasPermission("View", location)) { throw new HttpException(401, SharedRes.Error.Unauthorized_Location); } model.Puchases = new LinqMetaData().PurchaseHistory.Where(x => x.LocationId == locationId.Value); } } else { var organization = new OrganizationEntity(organizationId.Value); if (organization.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_Organization); } if (!locationId.HasValue) { if (!Permissions.UserHasPermission("View", organization)) { throw new HttpException(401, SharedRes.Error.Unauthorized_Organization); } model.Puchases = new LinqMetaData().PurchaseHistory.Where(x => x.Location.OrganizationId == organizationId); } else { // do the same thing as above but check if the location is assigned to the organization var location = new LocationEntity(locationId.Value); if (location.IsNew && location.OrganizationId == organizationId) { throw new HttpException(404, SharedRes.Error.NotFound_Location); } if (!Permissions.UserHasPermission("View", location)) { throw new HttpException(401, SharedRes.Error.Unauthorized_Location); } model.Puchases = new LinqMetaData().PurchaseHistory.Where(x => x.LocationId == locationId.Value); } } var result = View(model); if (dtRequestModel == null) { return(result); } return(Query(result, dtRequestModel)); }
public async Task <IActionResult> TableData([FromBody] DataTablesRequestModel req) { return(Json(await _dataTables.PopulateTable(req, _context.Sensors))); }
public ActionResult View(long treatmentId, Treatment model, [ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { var treatment = new TreatmentEntity(treatmentId); if (treatment.IsNew) { throw new HttpException(404, SharedRes.Error.NotFound_Treatment); } // make sure the user has access to this treatment if (!Permissions.UserHasPermission("View", treatment)) { throw new HttpException(401, SharedRes.Error.Unauthorized_Treatment); } // make sure user has access to this page if (!RoleUtils.IsUserServiceAdmin() && model.Page != TreatmentPage.Summary && model.Page != TreatmentPage.System && model.Page != TreatmentPage.Definitions) { throw new HttpException(401, SharedRes.Error.Unauthorized); } // make sure treatment can be accessed by this user model.License = LicenseMode.Full; model.Name = treatment.Patient.FirstName + " " + treatment.Patient.MiddleInitial + " " + treatment.Patient.LastName; model.DateOfBirth = treatment.Patient.BirthDate; model.Gender = treatment.Patient.Gender; var age = treatment.TreatmentTime.Year - treatment.Patient.BirthDate.Year; if (treatment.TreatmentTime < treatment.Patient.BirthDate.AddYears(age)) { age--; } model.Age = age; model.VisitDate = treatment.TreatmentTime; // only load data used for each page // severities is used on the summary and the raw report page if (model.Page == TreatmentPage.Summary || model.Page == TreatmentPage.RawReport) { model.Severities = new LinqMetaData().OrganSystemOrgan .Where(x => x.LicenseOrganSystem.LicenseMode == model.License) .OrderBy(x => x.ReportOrder) .OrderBy(x => x.LicenseOrganSystem.ReportOrder) .SelectMany(x => x.Organ.Severities.Where(y => y.TreatmentId == treatmentId)) .DistinctBy(x => x.Organ.Description.Replace(" - Left", "").Replace(" - Right", "")); } // organ systems is only used on the summary page if (model.Page == TreatmentPage.Summary) { model.OrganSystems = new LinqMetaData().LicenseOrganSystem.Where(x => x.LicenseMode == model.License).OrderBy( x => x.ReportOrder).Select(x => x.OrganSystem); model.PatientPrescanQuestion = treatment.PatientPrescanQuestion; } // load all analysis results for the raw data page if (model.Page == TreatmentPage.Raw || model.Page == TreatmentPage.Summary) { model.Raw = new LinqMetaData().AnalysisResult.Where(x => x.TreatmentId == model.TreatmentId); } // load the debug data for the raw report page if (model.Page == TreatmentPage.RawReport) { model.Debug = GetDebugData(new LinqMetaData().CalculationDebugData.Where(x => x.TreatmentId == model.TreatmentId), model.Severities, model.License); model.NBScores = new LinqMetaData().NBAnalysisResult.Where(x => x.TreatmentId == model.TreatmentId); } // only load images for the images page if (!Request.IsAjaxRequest() && !ControllerContext.IsChildAction) { // get database images var energizedImages = Utilities.Treatment.ImageRetrievalHelper.GetPatientImages(treatment.EnergizedImageSetId); var calibrationImages = Utilities.Treatment.ImageRetrievalHelper.GetCalibrationImageSet(treatment.CalibrationId); // save in cache for a few minutes var caches = new LinqMetaData().ImageCache.Where( x => x.LookupKey == treatmentId && (x.Description.StartsWith("Finger-") || x.Description.StartsWith("Calibration-"))).Select(x => x.Description).ToList(); // save extracted images to database for (var i = 0; i < energizedImages.Count; i++) { if (caches.All(x => x != "Finger-" + i)) { using (var mem = new MemoryStream()) { energizedImages[i].Image.Save(mem, ImageFormat.Png); new ImageCacheEntity { LookupKey = treatmentId, Description = "Finger-" + i, Image = mem.ToArray() }.Save(); energizedImages[i].Image.Dispose(); } } } for (var i = 0; i < calibrationImages.Count; i++) { if (caches.All(x => x != "Calibration-" + i)) { using (var mem = new MemoryStream()) { calibrationImages[i].Image.Save(mem, ImageFormat.Png); new ImageCacheEntity { LookupKey = treatmentId, Description = "Calibration-" + i, Image = mem.ToArray() }.Save(); calibrationImages[i].Image.Dispose(); } } } } ViewResult result = View(model); if (dtRequestModel == null) { return(result); } return(Query(result, dtRequestModel)); }
public ActionResult Checkout(NewPurchaseModel model, [ModelBinder(typeof(DataTablesRequestModelBinder))] DataTablesRequestModel dtRequestModel) { var user = Membership.GetUser().GetUserEntity(); if (Session["cart"] as List <Models.Purchase> == null) { Session["cart"] = new List <Models.Purchase>(); } model.Cart = ((List <Models.Purchase>)Session["cart"]); if (Request.HttpMethod == "POST") { if (ModelState.IsValid) { if (model.Cart.Count > 0) { var transaction = new Transaction(IsolationLevel.ReadCommitted, "purchase transfer"); try { // authorize and capture purchase CustomerGateway cg; var customer = EnsureProfile(out cg); var order = new Order(customer.ProfileID, model.CreditCard.AuthorizeId, "") { Amount = model.Cart.Sum(x => x.Price), Description = model.PurchaseNotes, InvoiceNumber = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture) }; var response = (GatewayResponse)cg.AuthorizeAndCapture(order); if (!response.Approved) { throw new Exception(response.Message); } // set up all the transactions foreach (var purchase in model.Cart) { var toDevice = purchase.Device; var newPurchase = new PurchaseHistoryEntity { DeviceId = purchase.DeviceId, LocationId = toDevice.LocationId, UserId = user.UserId, PurchaseTime = DateTime.UtcNow, ScansPurchased = purchase.Quantity, AmountPaid = purchase.Price, PurchaseNotes = model.PurchaseNotes, TransactionId = response.TransactionID }; transaction.Add(newPurchase); newPurchase.Save(); toDevice.ScansAvailable += purchase.Quantity; transaction.Add(toDevice); toDevice.Save(); } transaction.Commit(); model.Cart.Clear(); OperationController.Update(); return(RedirectToAction("List")); } catch (Exception ex) { transaction.Rollback(); ModelState.AddModelError("", Purchase.CheckoutError); Log.Error(Purchase.CheckoutError, ex); } finally { transaction.Dispose(); } } } else { ModelState.AddModelError("", Purchase.NoItems); } Response.StatusCode = 417; Response.TrySkipIisCustomErrors = true; } model.Cards = user.UserCreditCards.AsQueryable(); var result = View(model); if (dtRequestModel == null) { return(result); } return(Query(result, dtRequestModel)); }
/// <summary> /// This is the primary query function called by all inheritors of DataTablesController. /// </summary> /// <param name="viewResult">The view result from the function that displays the datatable and sets up the datatable for the page. The configuration is stored in the ViewData.</param> /// <param name="model">The model created by the dataTables script making an AJAX callback to the server.</param> /// <returns></returns> protected JsonResult Query(ViewResultBase viewResult, DataTablesRequestModel model) { return(Query(viewResult, model, ControllerContext)); }
/// <summary> /// The call for this function is generated in order to simplify the filtering below. This is not usually necessary for IQueryable<object> /// However, LLBLGen has problems with IQuerable when the type is casted to object, so the proper typed call is generated above and this generic is called. /// </summary> /// <typeparam name="TEntity"></typeparam> /// <param name="dataTableInit"></param> /// <param name="model"></param> /// <returns></returns> private static JsonResult Query <TEntity>(DataTablesInitializationModel <TEntity> dataTableInit, DataTablesRequestModel model) { // Get source model used to create the view. var source = dataTableInit.Source; // get IQueryable type of object passed in, this makes the work below generalized for any type /*var source2 = source as IQueryable<PatientEntity>; * if(source2 != null) * { * source2 = source2.Where(x => Convert.ToString(x.BirthDate, new DateTimeFormatInfo(){ShortDatePattern = }).Contains("fe")); * * var result = source2.ToList(); * } */ // start with the source, then add on each filter var count = source.Count(); var displayCount = count; if (!String.IsNullOrEmpty(model.sSearch)) { var llblGenProProvider = source.Provider as LLBLGenProProvider; if (llblGenProProvider != null) { var dateConverter = new FunctionMapping(typeof(DateTime), "ToString", 0, @"CONVERT(nvarchar(2), CONVERT(int, SUBSTRING(CONVERT(nvarchar(23), {0}, 121), 6, 2))) + '/' + CONVERT(nvarchar(2), CONVERT(int, SUBSTRING(CONVERT(nvarchar(23), {0}, 121), 9, 2))) + '/' + CONVERT(nvarchar(4), CONVERT(int, SUBSTRING(CONVERT(nvarchar(23), {0}, 121), 1, 4))) + ' ' + CASE WHEN CONVERT(int, SUBSTRING(CONVERT(nvarchar(23), {0}, 121), 12, 2)) > 12 THEN CONVERT(nvarchar(4), CONVERT(int, SUBSTRING(CONVERT(nvarchar(23), {0}, 121), 12, 2)) - 12) ELSE CONVERT(nvarchar(4), CONVERT(int, SUBSTRING(CONVERT(nvarchar(23), {0}, 121), 12, 2))) END +':' +SUBSTRING(CONVERT(nvarchar(23), {0}, 121), 15, 2) + ':' + SUBSTRING(CONVERT(nvarchar(23), {0}, 121), 18, 2) + CASE WHEN CONVERT(int, SUBSTRING(CONVERT(nvarchar(23), {0}, 121), 12, 2)) > 11 THEN ' PM' ELSE ' AM' END"); //var indexOf = new FunctionMapping(typeof(string), "IndexOf", 1, "PATINDEX('%{1}%', {0}) - 1"); //var indexOf2 = new FunctionMapping(typeof(string), "IndexOf", 2, "PATINDEX('%{1}%', {0}) - 1"); if ((llblGenProProvider).CustomFunctionMappings == null) { (llblGenProProvider).CustomFunctionMappings = new FunctionMappingStore(); } (llblGenProProvider).CustomFunctionMappings.Add(dateConverter); //(llblGenProProvider).CustomFunctionMappings.Add(indexOf); //(llblGenProProvider).CustomFunctionMappings.Add(indexOf2); // ^--- Doesn't work for no apparent reason but would make the Search() function a lot simpler. } // search all specified columns for the specified string source = source.Search(dataTableInit.Columns, model.sSearch, !(source.Provider is LLBLGenProProvider)); displayCount = source.Count(); } // sort the result based on the model, this calls OrderBy on multiple columns sequentially if (model.Sorts.Any()) { source = source.Sort(dataTableInit.Columns, model.Sorts); } // filter page based on start and length, this is like the SQL LIMIT directive if (model.iDisplayLength > 0) { source = source.Skip(model.iDisplayStart).Take(model.iDisplayLength); } // now build the response var response = new DataTablesResponseModel { sEcho = model.sEcho.Value, iTotalRecords = count, iTotalDisplayRecords = displayCount }; // loop through each item and output JSON foreach (TEntity entity in source.ToList()) { var row = response.NewRow(); row.SetRowId(string.Empty + entity.GetHashCode()); foreach (var column in dataTableInit.Columns) { // if the column specifies a formatting function if (column.Format != null) { var method = column.Format.Compile(); row.PushColumn(method.Invoke(entity).ToString()); } else { var value = DataBinder.Eval(entity, column.ColumnName); row.PushColumn(value != null ? value.ToString() : ""); } } } return(new JsonResult { Data = response, ContentType = null, ContentEncoding = null, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }