public ActionResult DeleteMetaReport(MetaReportDeleteModel model) { ViewBag.MenuItem = CurrentMenuItem; var metaReport = _unitOfWork.Repository <MetaReport>() .Queryable() .SingleOrDefault(r => r.Id == model.MetaReportId); if (metaReport != null) { if (ModelState.IsValid) { if (metaReport.IsSystem) { ModelState.AddModelError("ReportName", "SYSTEM REPORT. Unable to delete."); } if (ModelState.IsValid) { _unitOfWork.Repository <MetaReport>().Delete(metaReport); _unitOfWork.Complete(); HttpCookie cookie = new HttpCookie("PopUpMessage"); cookie.Value = "Report deleted successfully"; Response.Cookies.Add(cookie); return(Redirect("/Reports/Index")); } } } return(View(model)); }
public void CreateWorkFlowInstance(string workFlowName, Guid contextGuid, string patientIdentifier, string sourceIdentifier) { Check.IsEmpty(workFlowName, "workFlow may not be empty"); Check.IsNotNull(contextGuid, "contextGuid may not be null"); // Ensure instance does not exist for this context var workFlow = _unitOfWork.Repository <WorkFlow>().Queryable().SingleOrDefault(wf => wf.Description == workFlowName); Check.IsNotNull(workFlow, "contextGuid may not be null"); var currentUser = UserContext.CurrentUser != null?_unitOfWork.Repository <User>().Queryable().SingleOrDefault(u => u.Id == UserContext.CurrentUser.Id) : null; ReportInstance reportInstance = _unitOfWork.Repository <ReportInstance>().Queryable().SingleOrDefault(ri => ri.ContextGuid == contextGuid); if (reportInstance == null) { reportInstance = new ReportInstance(workFlow, currentUser) { ContextGuid = contextGuid, PatientIdentifier = patientIdentifier, SourceIdentifier = sourceIdentifier }; _unitOfWork.Repository <ReportInstance>().Save(reportInstance); reportInstance.SetIdentifier(); _unitOfWork.Repository <ReportInstance>().Update(reportInstance); _unitOfWork.Complete(); } }
public async Task <IHttpActionResult> Post([FromBody] PatientDTO value) { Patient patient = null; if (value.PatientUniqueIdentifier != null) { patient = await unitOfwork.Repository <Patient>() .Queryable() .SingleOrDefaultAsync(p => p.PatientGuid == value.PatientUniqueIdentifier); } if (patient == null) { patient = new Patient { PatientGuid = Guid.NewGuid(), FirstName = value.PatientFirstName, Surname = value.PatientLastName, DateOfBirth = value.PatientDateOfBirth, Notes = value.Notes }; setCustomAttributes(value.customAttributes, patient); unitOfwork.Repository <Patient>().Save(patient); } else { patient.FirstName = value.PatientFirstName; patient.Surname = value.PatientLastName; patient.DateOfBirth = value.PatientDateOfBirth; patient.Notes = value.Notes; setCustomAttributes(value.customAttributes, patient); unitOfwork.Repository <Patient>().Update(patient); } unitOfwork.Complete(); var patientDto = new PatientDTO { PatientId = patient.Id, PatientUniqueIdentifier = patient.PatientGuid, PatientFirstName = patient.FirstName, PatientLastName = patient.Surname, CreatedBy = patient.CreatedBy.FullName, PatientCreatedDate = patient.Created, UpdatedBy = patient.UpdatedBy != null? patient.UpdatedBy.FullName: "", PatientUpdatedDate = patient.LastUpdated.GetValueOrDefault(DateTime.MinValue), PatientDateOfBirth = patient.DateOfBirth.GetValueOrDefault(DateTime.MinValue), Notes = patient.Notes, customAttributes = getCustomAttributes(patient) }; return(Ok(patientDto)); }
public ActionResult EditCareEvent(CareEventEditModel model) { ViewBag.MenuItem = CurrentMenuItem; if (ModelState.IsValid) { if (unitOfWork.Repository <CareEvent>().Queryable().Any(ce => ce.Id != model.CareEventId && ce.Description == model.Description)) { ModelState.AddModelError("Description", "Another care event with the specified description already exists."); return(View(model)); } if (Regex.Matches(model.Description, @"[a-zA-Z ']").Count < model.Description.Length) { ModelState.AddModelError("Description", "Description contains invalid characters (Enter A-Z, a-z)"); return(View(model)); } var careEvent = unitOfWork.Repository <CareEvent>().Queryable().SingleOrDefault(ce => ce.Id == model.CareEventId); if (careEvent == null) { ModelState.AddModelError("", "Unable to update the care event. The care event could not be found in the data store."); return(View(model)); } try { var encodedDescription = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.Description, false); careEvent.Description = encodedDescription; unitOfWork.Repository <CareEvent>().Update(careEvent); unitOfWork.Complete(); return(Redirect("/Admin/ManageCareEvent.aspx")); } catch (Exception ex) { ModelState.AddModelError("", string.Format("Unable to update the care event: {0}", ex.Message)); } } return(View(model)); }
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { if (unitOfWork != null) { unitOfWork.Complete(); } base.OnActionExecuted(actionExecutedContext); }
public override void OnActionExecuted(ActionExecutedContext filterContext) { if (unitOfWork != null) { unitOfWork.Complete(); } base.OnActionExecuted(filterContext); }
public ActionResult DeleteMetaPage(MetaPageDeleteModel model) { ViewBag.MenuItem = CurrentMenuItem; var metaPage = _unitOfWork.Repository <MetaPage>() .Queryable() .SingleOrDefault(p => p.Id == model.MetaPageId); ViewBag.ReturnUrl = "/Publisher/PageViewer.aspx?guid=" + metaPage.metapage_guid; if (metaPage != null) { if (ModelState.IsValid) { var pageInUse = _unitOfWork.Repository <MetaWidget>().Queryable().Any(w => w.MetaPage.Id == model.MetaPageId); if (pageInUse) { ModelState.AddModelError("PageName", "Unable to delete the Page as it is currently in use."); } if (metaPage.IsSystem) { ModelState.AddModelError("PageName", "SYSTEM PAGE. Unable to delete."); } if (ModelState.IsValid) { _unitOfWork.Repository <MetaPage>().Delete(metaPage); _unitOfWork.Complete(); HttpCookie cookie = new HttpCookie("PopUpMessage"); cookie.Value = "Page deleted successfully"; Response.Cookies.Add(cookie); return(Redirect("/Publisher/PageViewer.aspx?guid=a63e9f29-a22f-43df-87a0-d0c8dec50548")); } } } return(View(model)); }
public ActionResult DeleteDatasetElement(DatasetElementDeleteModel model) { ViewBag.MenuItem = CurrentMenuItem; var cancelRedirectUrl = (TempData["cancelRedirectUrl"] ?? string.Empty).ToString(); ViewBag.cancelRedirectUrl = cancelRedirectUrl; ArrayList errors = new ArrayList(); if (ModelState.IsValid) { var element = _unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(ds => ds.Id == model.DatasetElementId); try { ArrayList delete = new ArrayList(); delete.AddRange(element.DatasetRules.ToArray()); foreach (DatasetRule rule in delete) { _unitOfWork.Repository <DatasetRule>().Delete(rule); } _unitOfWork.Repository <Field>().Delete(element.Field); _unitOfWork.Repository <DatasetElement>().Delete(element); _unitOfWork.Complete(); } catch (DbUpdateException ex) { errors.Add("Unable to delete element. " + ex.Message); } if (errors.Count == 0) { HttpCookie cookie = new HttpCookie("PopUpMessage"); cookie.Value = "Dataset element deleted successfully"; Response.Cookies.Add(cookie); return(Redirect("/Admin/ManageDatasetElement.aspx")); } else { AddErrors(errors); } } return(View(model)); }
public void UpdateCustomAttribute(CustomAttributeConfigDetail customAttribute) { var updateCustomAttribute = _unitOfWork.Repository <CustomAttributeConfiguration>().Queryable().Single(ca => ca.ExtendableTypeName == customAttribute.EntityName && ca.AttributeKey == customAttribute.AttributeName); updateCustomAttribute.Category = customAttribute.Category; updateCustomAttribute.AttributeDetail = customAttribute.AttributeDetail; updateCustomAttribute.IsRequired = customAttribute.Required; updateCustomAttribute.IsSearchable = customAttribute.Searchable; switch (updateCustomAttribute.CustomAttributeType) { case CustomAttributeType.Numeric: if (customAttribute.NumericMinValue.HasValue) { updateCustomAttribute.NumericMinValue = customAttribute.NumericMinValue.Value; } if (customAttribute.NumericMaxValue.HasValue) { updateCustomAttribute.NumericMaxValue = customAttribute.NumericMaxValue.Value; } break; case CustomAttributeType.String: if (customAttribute.StringMaxLength.HasValue) { updateCustomAttribute.StringMaxLength = customAttribute.StringMaxLength.Value; } break; case CustomAttributeType.DateTime: updateCustomAttribute.FutureDateOnly = customAttribute.FutureDateOnly; updateCustomAttribute.PastDateOnly = customAttribute.PastDateOnly; break; default: break; } customAttributeConfigRepository.Update(updateCustomAttribute); _unitOfWork.Complete(); }
public void SetConfigValue(ConfigType configType, string configValue) { var config = _unitOfWork.Repository <Config>().Queryable(). FirstOrDefault(c => c.ConfigType == configType); if (config == null) { config = new Config() { // Prepare new config ConfigType = configType, ConfigValue = configValue }; _unitOfWork.Repository <Config>().Save(config); } else { config.ConfigValue = configValue; _unitOfWork.Repository <Config>().Update(config); } _unitOfWork.Complete(); }
public void ExecuteScripts() { var scriptsFolder = Server.MapPath("~/PostDeploymentScripts/"); var postDeploymentRepository = _unitOfWork.Repository <PostDeployment>(); var pendingPostDeploymentScripts = postDeploymentRepository.Queryable() .Where(x => !x.RunDate.HasValue) .OrderBy(u => u.RunRank) .ToList(); foreach (var pendingPostDeploymentScript in pendingPostDeploymentScripts) { try { var fullPath = Path.Combine(scriptsFolder, pendingPostDeploymentScript.ScriptFileName); if (!System.IO.File.Exists(fullPath)) { pendingPostDeploymentScript.StatusCode = 404; pendingPostDeploymentScript.StatusMessage = "File not found"; } else { postDeploymentRepository.ExecuteSqlCommand(System.IO.File.ReadAllText(fullPath)); pendingPostDeploymentScript.StatusCode = 200; } } catch (Exception exception) { pendingPostDeploymentScript.StatusCode = 501; pendingPostDeploymentScript.StatusMessage = exception.Message; } finally { pendingPostDeploymentScript.RunDate = DateTime.Now; postDeploymentRepository.Update(pendingPostDeploymentScript); _unitOfWork.Complete(); } } }
public async Task <ActionResult> AddUser(AddUserModel model) { ViewBag.MenuItem = CurrentMenuItem; ArrayList errors = new ArrayList(); if (ModelState.IsValid) { // Validation if (String.IsNullOrEmpty(model.UserName.Trim())) { errors.Add("User Name is mandatory"); } if (model.SelectedRoles == null) { errors.Add("At least one role must be selected"); } if (model.SelectedFacilities == null) { errors.Add("At least one facility must be selected"); } if (unitOfWork.Repository <User>().Queryable().Any(u => u.UserName == model.UserName)) { errors.Add("A user with the specified username already exists."); } if (errors.Count == 0) { var user = new UserInfo() { FirstName = model.FirstName, LastName = model.LastName, UserName = model.UserName, Email = model.Email, Password = model.Password }; IdentityResult result = await userManager.CreateAsync(user, model.Password); if (result.Succeeded) { var roleIdsInt64 = model.SelectedRoles.ConvertAll <Int64>(Convert.ToInt64).ToArray(); var roles = unitOfWork.Repository <Role>().Queryable() .Where(r => roleIdsInt64.Contains(r.Id)) .Select(rk => rk.Key) .ToArray(); IdentityResult roleResult = await userManager.AddToRolesAsync(user.Id, roles); if (roleResult.Succeeded) { var utemp = unitOfWork.Repository <User>().Queryable().SingleOrDefault(u => u.Id == user.Id); var facilityIdsInt64 = model.SelectedFacilities.ConvertAll <Int64>(Convert.ToInt64).ToArray(); ArrayList deleteCollection = new ArrayList(); foreach (UserFacility uf in utemp.Facilities) { if (!facilityIdsInt64.Contains(uf.Facility.Id)) { // remove deleteCollection.Add(uf); } } ArrayList addCollection = new ArrayList(); foreach (Int64 id in facilityIdsInt64) { if (!utemp.Facilities.Any(uf => uf.Id == id)) { // add addCollection.Add(id); } } foreach (UserFacility uf in deleteCollection) { utemp.Facilities.Remove(uf); } foreach (Int64 id in addCollection) { var uf = new UserFacility() { Facility = unitOfWork.Repository <Facility>().Queryable().SingleOrDefault(f => f.Id == id), User = utemp }; utemp.Facilities.Add(uf); } utemp.Active = true; unitOfWork.Repository <User>().Update(utemp); unitOfWork.Complete(); HttpCookie cookie = new HttpCookie("PopUpMessage"); cookie.Value = "User record added successfully"; Response.Cookies.Add(cookie); return(RedirectToAction("Index")); } else { AddErrors(roleResult); } } else { AddErrors(result); } } else // if (errors.Count == 0) { AddErrors(errors); } } ViewBag.Roles = unitOfWork.Repository <Role>().Queryable().ToList().Select(r => new SelectListItem { Value = r.Id.ToString(), Text = r.Name }).ToList(); ViewBag.Facilities = unitOfWork.Repository <Facility>().Queryable().OrderBy(f => f.FacilityName).ToList().Select(f => new SelectListItem { Value = f.Id.ToString(), Text = f.FacilityName }).ToList(); return(View(model)); }
public ActionResult EditEncounterType(EncounterTypeEditModel model) { ViewBag.MenuItem = CurrentMenuItem; if (unitOfWork.Repository <EncounterType>().Queryable().Any(et => et.Id != model.EncounterTypeId && et.Description == model.Description)) { ModelState.AddModelError("Description", "Another encounter type with the specified description already exists."); } if (Regex.Matches(model.Description, @"[a-zA-Z ']").Count < model.Description.Length) { ModelState.AddModelError("Description", "Description contains invalid characters (Enter A-Z, a-z)"); } if (!String.IsNullOrWhiteSpace(model.Help)) { if (Regex.Matches(model.Help, @"[a-zA-Z ']").Count < model.Help.Length) { ModelState.AddModelError("Help", "Help contains invalid characters (Enter A-Z, a-z)"); } } if (ModelState.IsValid) { var encodedDescription = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.Description, false); var encodedHelp = !String.IsNullOrWhiteSpace(model.Help) ? System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.Help, false) : ""; var encounterType = unitOfWork.Repository <EncounterType>().Queryable().SingleOrDefault(et => et.Id == model.EncounterTypeId); if (encounterType == null) { ModelState.AddModelError("", "Unable to update the encounter type. The encounter type could not be found in the data store."); } try { encounterType.Description = encodedDescription; encounterType.Help = encodedHelp; unitOfWork.Repository <EncounterType>().Update(encounterType); var encounterTypeWorkPlan = unitOfWork.Repository <EncounterTypeWorkPlan>().Queryable().SingleOrDefault(etwp => etwp.EncounterType.Id == model.EncounterTypeId); var workPlan = unitOfWork.Repository <WorkPlan>().Queryable().SingleOrDefault(wp => wp.Id == model.WorkPlanId); if (workPlan == null) { if (encounterTypeWorkPlan != null) { unitOfWork.Repository <EncounterTypeWorkPlan>().Delete(encounterTypeWorkPlan); } } else { if (encounterTypeWorkPlan == null) { encounterTypeWorkPlan = new EncounterTypeWorkPlan { CohortGroup = null, EncounterType = encounterType, WorkPlan = workPlan }; unitOfWork.Repository <EncounterTypeWorkPlan>().Save(encounterTypeWorkPlan); } else { encounterTypeWorkPlan.WorkPlan = workPlan; unitOfWork.Repository <EncounterTypeWorkPlan>().Update(encounterTypeWorkPlan); } } unitOfWork.Complete(); return(Redirect("/Admin/ManageEncounterType.aspx")); } catch (Exception ex) { ModelState.AddModelError("", string.Format("Unable to update the encounter type: {0}", ex.Message)); } } var workPlans = unitOfWork.Repository <WorkPlan>() .Queryable() .ToList(); var wpList = new List <SelectListItem> { { new SelectListItem { Value = "", Text = "" } } }; wpList.AddRange(workPlans.Select(wp => new SelectListItem { Value = wp.Id.ToString(), Text = wp.Description })); ViewBag.WorkPlans = wpList; return(View(model)); }
public async Task <HttpResponseMessage> Post(JObject items) { if (items == null) { return(Request.CreateResponse(HttpStatusCode.NoContent, "No records to process ")); } dynamic json = items; List <PatientClinicalEvent> synchedPatientClinicalEvents = new List <PatientClinicalEvent>(); IList <PatientClinicalEventDTO> patientClinicalEvents = await Task.Run(() => ((JArray)json.items) .Select(t => new PatientClinicalEventDTO { PatientClinicalEventId = ((dynamic)t).PatientClinicalEventId, PatientClinicalEventIdentifier = ((dynamic)t).PatientClinicalEventIdentifier, PatientId = ((dynamic)t).PatientId, OnsetDate = ((dynamic)t).OnsetDate != null ? ((dynamic)t).OnsetDate : null, ReportedDate = ((dynamic)t).ReportedDate != null ? ((dynamic)t).ReportedDate : null, ResolutionDate = ((dynamic)t).ResolutionDate != null ? ((dynamic)t).ResolutionDate : null, Description = ((dynamic)t).Description, MedDraId = ((dynamic)t).MedDraId, customAttributes = ((dynamic)t).customAttributes == null ? null : ((JArray)(((dynamic)t).customAttributes)) .Select(x => new CustomAttributeDTO { CustomAttributeConfigId = ((dynamic)x).CustomAttributeConfigId, AttributeTypeName = ((dynamic)x).AttributeTypeName, AttributeName = ((dynamic)x).AttributeName, Category = ((dynamic)x).Category, EntityName = ((dynamic)x).EntityName, currentValue = ((dynamic)x).currentValue, lastUpdated = ((dynamic)x).lastUpdated != "" ? ((dynamic)x).lastUpdated : null, lastUpdatedUser = ((dynamic)x).lastUpdatedUser, Required = ((dynamic)x).Required, NumericMaxValue = ((dynamic)x).NumericMaxValue != "" ? ((dynamic)x).NumericMaxValue : null, NumericMinValue = ((dynamic)x).NumericMinValue != "" ? ((dynamic)x).NumericMinValue : null, StringMaxLength = ((dynamic)x).StringMaxLength != "" ? ((dynamic)x).StringMaxLength : null, FutureDateOnly = ((dynamic)x).FutureDateOnly != "" ? ((dynamic)x).FutureDateOnly : null, PastDateOnly = ((dynamic)x).PastDateOnly != "" ? ((dynamic)x).PastDateOnly : null }).ToList() }).ToList()); var termResults = await Task.Run(() => unitOfWork.Repository <TerminologyMedDra>() .Queryable().ToList()); foreach (PatientClinicalEventDTO patientEvent in patientClinicalEvents) { PatientClinicalEvent obj = await unitOfWork.Repository <PatientClinicalEvent>() .Queryable() .SingleOrDefaultAsync(e => e.PatientClinicalEventGuid == patientEvent.PatientClinicalEventIdentifier); if (obj == null) { obj = new PatientClinicalEvent { PatientClinicalEventGuid = patientEvent.PatientClinicalEventIdentifier, Patient = unitOfWork.Repository <Patient>().Queryable().SingleOrDefault(e => e.Id == patientEvent.PatientId), //Id = patientEvent.PatientClinicalEventId, OnsetDate = patientEvent.OnsetDate, ResolutionDate = patientEvent.ResolutionDate, SourceDescription = patientEvent.Description, SourceTerminologyMedDra = termResults.FirstOrDefault(e => e.Id == patientEvent.MedDraId) }; setCustomAttributes(patientEvent.customAttributes, obj); unitOfWork.Repository <PatientClinicalEvent>().Save(obj); synchedPatientClinicalEvents.Add(obj); } else { obj.OnsetDate = patientEvent.OnsetDate; obj.ResolutionDate = patientEvent.ResolutionDate; obj.SourceDescription = patientEvent.Description; obj.SourceTerminologyMedDra = termResults.FirstOrDefault(e => e.Id == patientEvent.MedDraId); setCustomAttributes(patientEvent.customAttributes, obj); unitOfWork.Repository <PatientClinicalEvent>().Update(obj); synchedPatientClinicalEvents.Add(obj); } } unitOfWork.Complete(); DateTime dttemp; var insertedObjs = synchedPatientClinicalEvents.Select(p => new PatientClinicalEventDTO { PatientId = p.Patient.Id, PatientClinicalEventIdentifier = p.PatientClinicalEventGuid, PatientClinicalEventId = p.Id, Description = p.SourceDescription, MedDraId = p.SourceTerminologyMedDra.Id, OnsetDate = p.OnsetDate, ResolutionDate = p.ResolutionDate, ReportedDate = DateTime.TryParse(GetCustomAttributeValue(unitOfWork.Repository <CustomAttributeConfiguration>().Queryable().SingleOrDefault(c => c.ExtendableTypeName == "PatientClinicalEvent" && c.AttributeKey == "Date of Report"), (IExtendable)p), out dttemp) ? dttemp : (DateTime?)null, customAttributes = getCustomAttributes(p) }).ToArray(); return(Request.CreateResponse(HttpStatusCode.OK, insertedObjs)); }
public ActionResult EditAppointment(AppointmentEditModel model) { ViewBag.MenuItem = CurrentMenuItem; var cancelRedirectUrl = (TempData["cancelRedirectUrl"] ?? string.Empty).ToString(); ViewBag.cancelRedirectUrl = cancelRedirectUrl; var appointmentRepository = unitOfWork.Repository <Appointment>(); var appointment = appointmentRepository.Queryable().Include("Patient").Single(a => a.Id == model.AppointmentId); if (appointment == null) { ViewBag.Entity = "Appointment"; return(View("NotFound")); } // If user has changed appointment date - then complete duplication check if (appointment.AppointmentDate != model.AppointmentDate) { var tempAppointment = unitOfWork.Repository <Appointment>() .Queryable() .Include(p => p.Patient) .SingleOrDefault(a => a.Patient.Id == appointment.Patient.Id && a.AppointmentDate == model.AppointmentDate); if (tempAppointment != null) { ModelState.AddModelError("AppointmentDate", "Patient already has an appointment for this date"); } } if (model.AppointmentDate > DateTime.Today.AddYears(2)) { ModelState.AddModelError("AppointmentDate", "Appointment Date should be within 2 years"); } if (model.AppointmentDate < DateTime.Today) { ModelState.AddModelError("AppointmentDate", "Appointment Date should be after current date"); } if (ModelState.IsValid) { appointment.AppointmentDate = model.AppointmentDate; appointment.Reason = model.Reason; appointment.Cancelled = model.Cancelled == "Yes" ? true : false; appointment.CancellationReason = model.CancellationReason; appointmentRepository.Update(appointment); unitOfWork.Complete(); HttpCookie cookie = new HttpCookie("PopUpMessage"); cookie.Value = "Appointment record updated successfully"; Response.Cookies.Add(cookie); return(Redirect("/Patient/PatientView.aspx?pid=" + appointment.Patient.Id.ToString())); } string patientName = appointment.Patient.FullName; ViewBag.Cancellations = new[] { new SelectListItem { Value = "No", Text = "No", Selected = true }, new SelectListItem { Value = "Yes", Text = "Yes" } }; ViewBag.PatientName = patientName; return(View(model)); }
public ActionResult EditContactDetail(ContactDetailEditModel model) { ViewBag.MenuItem = CurrentMenuItem; if (ModelState.IsValid) { if (!String.IsNullOrEmpty(model.OrganisationName)) { if (Regex.Matches(model.OrganisationName, @"[a-zA-Z0-9 ]").Count < model.OrganisationName.Length) { ModelState.AddModelError("OrganisationName", "Value contains invalid characters (Enter A-Z, a-z, 0-9, space)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.ContactFirstName)) { if (Regex.Matches(model.ContactFirstName, @"[a-zA-Z ]").Count < model.ContactFirstName.Length) { ModelState.AddModelError("ContactFirstName", "Value contains invalid characters (Enter A-Z, a-z, space)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.ContactSurname)) { if (Regex.Matches(model.ContactSurname, @"[a-zA-Z ]").Count < model.ContactSurname.Length) { ModelState.AddModelError("ContactSurname", "Value contains invalid characters (Enter A-Z, a-z, space)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.StreetAddress)) { if (Regex.Matches(model.StreetAddress, @"[a-zA-Z0-9 ']").Count < model.StreetAddress.Length) { ModelState.AddModelError("StreetAddress", "Value contains invalid characters (Enter A-Z, a-z, 0-9, space, comma)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.City)) { if (Regex.Matches(model.City, @"[a-zA-Z ]").Count < model.City.Length) { ModelState.AddModelError("City", "Value contains invalid characters (Enter A-Z, a-z, space)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.State)) { if (Regex.Matches(model.State, @"[a-zA-Z ]").Count < model.State.Length) { ModelState.AddModelError("State", "Value contains invalid characters (Enter A-Z, a-z, space)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.PostCode)) { if (Regex.Matches(model.PostCode, @"[a-zA-Z0-9]").Count < model.PostCode.Length) { ModelState.AddModelError("PostCode", "Value contains invalid characters (Enter A-Z, a-z, 0-9)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.ContactNumber)) { if (Regex.Matches(model.ContactNumber, @"[-0-9]").Count < model.ContactNumber.Length) { ModelState.AddModelError("ContactNumber", "Value contains invalid characters (Enter 0-9, hyphen)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.ContactEmail)) { if (Regex.Matches(model.ContactEmail, @"[-a-zA-Z@._]").Count < model.ContactEmail.Length) { ModelState.AddModelError("ContactEmail", "Value contains invalid characters (Enter A-Z, a-z, hyphen, @, period, underscore)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.CountryCode)) { if (Regex.Matches(model.CountryCode, @"[0-9]").Count < model.CountryCode.Length) { ModelState.AddModelError("CountryCode", "Value contains invalid characters (Enter 0-9)"); return(View(model)); } } var contact = unitOfWork.Repository <SiteContactDetail>().Queryable().SingleOrDefault(c => c.Id == model.ContactDetailId); if (contact == null) { ModelState.AddModelError("ContactType", "Unable to update the contact detail. The record could not be found in the data store."); return(View(model)); } try { string encodedValue = ""; encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.City, false);; contact.City = encodedValue; encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.ContactEmail, false);; contact.ContactEmail = encodedValue; encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.ContactFirstName, false);; contact.ContactFirstName = encodedValue; encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.ContactNumber, false);; contact.ContactNumber = encodedValue; encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.ContactSurname, false);; contact.ContactSurname = encodedValue; encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.CountryCode, false);; contact.CountryCode = encodedValue; encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.OrganisationName, false);; contact.OrganisationName = encodedValue; encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.PostCode, false);; contact.PostCode = encodedValue; encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.State, false);; contact.State = encodedValue; encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.StreetAddress, false);; contact.StreetAddress = encodedValue; unitOfWork.Repository <SiteContactDetail>().Update(contact); unitOfWork.Complete(); HttpCookie cookie = new HttpCookie("PopUpMessage"); cookie.Value = "Contact detail record updated successfully"; Response.Cookies.Add(cookie); return(Redirect("/Admin/ManageContactDetail.aspx")); } catch (Exception ex) { ModelState.AddModelError("", string.Format("Unable to update the configuration: {0}", ex.Message)); } } return(View(model)); }
public ActionResult EditFacility(FacilityEditModel model) { ViewBag.MenuItem = CurrentMenuItem; ViewBag.FacilityTypes = unitOfWork.Repository <FacilityType>() .Queryable() .Select(ft => new SelectListItem { Value = ft.Id.ToString(), Text = ft.Description }) .ToList(); ViewBag.OrgUnits = unitOfWork.Repository <OrgUnit>() .Queryable() .Where(ou => ou.OrgUnitType.Description == "Region") .Select(ou => new SelectListItem { Value = ou.Id.ToString(), Text = ou.Name }) .ToList(); if (ModelState.IsValid) { if (unitOfWork.Repository <Facility>().Queryable().Any(f => f.Id != model.FacilityId && f.FacilityName == model.FacilityName)) { ModelState.AddModelError("FacilityName", "Another facility with the specified name already exists."); return(View(model)); } if (Regex.Matches(model.FacilityName, @"[-a-zA-Z0-9. '()]").Count < model.FacilityName.Length) { ModelState.AddModelError("FacilityName", "Facility name contains invalid characters (Enter A-Z, a-z, 0-9, space, period, apostrophe, round brackets)"); return(View(model)); } if (unitOfWork.Repository <Facility>().Queryable().Any(f => f.Id != model.FacilityId && f.FacilityCode == model.FacilityCode)) { ModelState.AddModelError("FacilityCode", "Another facility with the specified code already exists."); return(View(model)); } if (Regex.Matches(model.FacilityCode, @"[-a-zA-Z0-9]").Count < model.FacilityCode.Length) { ModelState.AddModelError("FacilityCode", "Facility code contains invalid characters (Enter A-Z, a-z, 0-9)"); return(View(model)); } if (!String.IsNullOrEmpty(model.TelNumber)) { if (Regex.Matches(model.TelNumber, @"[-a-zA-Z0-9]").Count < model.TelNumber.Length) { ModelState.AddModelError("TelNumber", "Telephone number contains invalid characters (Enter A-Z, a-z, 0-9)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.MobileNumber)) { if (Regex.Matches(model.MobileNumber, @"[-a-zA-Z0-9]").Count < model.MobileNumber.Length) { ModelState.AddModelError("MobileNumber", "Mobile number contains invalid characters (Enter A-Z, a-z, 0-9)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.FaxNumber)) { if (Regex.Matches(model.FaxNumber, @"[a-zA-Z0-9]").Count < model.FaxNumber.Length) { ModelState.AddModelError("FaxNumber", "Fax number contains invalid characters (Enter A-Z, a-z, 0-9)"); return(View(model)); } } var encodedName = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.FacilityName, false); var encodedCode = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.FacilityCode, false); var encodedTelNumber = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.TelNumber, false); var encodedMobileNumber = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.MobileNumber, false); var encodedFaxNumber = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.FaxNumber, false); var facilityType = unitOfWork.Repository <FacilityType>().Queryable().SingleOrDefault(ft => ft.Id == model.FacilityTypeId); var orgUnit = unitOfWork.Repository <OrgUnit>().Queryable().SingleOrDefault(ou => ou.Id == model.OrgUnitId); var facility = unitOfWork.Repository <Facility>().Queryable().SingleOrDefault(f => f.Id == model.FacilityId); if (facility == null) { ModelState.AddModelError("", "Unable to update the facility. The facility could not be found in the data store."); return(View(model)); } try { facility.FacilityCode = encodedCode; facility.FacilityName = encodedName; facility.FacilityType = facilityType; facility.OrgUnit = orgUnit; facility.FaxNumber = encodedFaxNumber; facility.MobileNumber = encodedMobileNumber; facility.TelNumber = encodedTelNumber; unitOfWork.Repository <Facility>().Update(facility); unitOfWork.Complete(); return(RedirectToAction("Index")); } catch (Exception ex) { ModelState.AddModelError("", string.Format("Unable to update the facility: {0}", ex.Message)); } } return(View(model)); }
public IHttpActionResult SaveDatasetInstanceSubValues(DatasetInstanceSubValuesSaveModel model) { if (model.Values.All(v => v.Value == null) && model.SubValueContext == default(Guid)) { // Nothing to do return(Ok <string>("{ result: \"Ok\" }")); } var errors = new Dictionary <string, string>(); var datasetInstance = _unitOfWork.Repository <DatasetInstance>() .Queryable() .Include(i => i.Dataset) .Include(i => i.DatasetInstanceValues.Select(i2 => i2.DatasetInstanceSubValues)) .SingleOrDefault(di => di.Id == model.DatasetInstanceId); var datasetElement = _unitOfWork.Repository <DatasetElement>().Queryable().Single(u => u.Id == model.DatasetElementId); if (datasetInstance == null) { return(NotFound()); } var datasetElementSubIds = model.Values.Select(v => v.DatasetElementSubId).ToArray(); var datasetElementSubs = _unitOfWork.Repository <DatasetElementSub>() .Queryable() .Where(des => datasetElementSubIds.Contains(des.Id)) .ToList(); var context = model.SubValueContext; DatasetInstanceSubValue datasetInstanceSubValue = null; int fieldValueId = 0; foreach (var datasetElementSub in datasetElementSubs) { var instanceSubValueModel = model.Values.SingleOrDefault(v => v.DatasetElementSubId == datasetElementSub.Id); if (instanceSubValueModel != null) { switch ((FieldTypes)datasetElementSub.Field.FieldType.Id) { case FieldTypes.DropDownList: case FieldTypes.Listbox: if (int.TryParse(instanceSubValueModel.Value.ToString(), out fieldValueId)) { var instanceSubValue = datasetElementSub.Field.FieldValues.SingleOrDefault(fv => fv.Id == fieldValueId); if (instanceSubValue != null) { try { datasetInstanceSubValue = datasetInstance.SetInstanceSubValue(datasetElementSub, instanceSubValue.Value, context); } catch (DatasetFieldSetException ex) { errors.Add(ex.Key, ex.Message); continue; } } else { if (datasetElementSub.Field.Mandatory) { errors.Add(datasetElementSub.Id.ToString(), string.Format("{0} is required.", datasetElementSub.ElementName)); continue; } } } else { if (datasetElementSub.Field.Mandatory) { errors.Add(datasetElementSub.Id.ToString(), string.Format("{0} is required.", datasetElementSub.ElementName)); continue; } } break; case FieldTypes.YesNo: default: try { datasetInstanceSubValue = datasetInstance.SetInstanceSubValue(datasetElementSub, instanceSubValueModel.Value.ToString(), context); } catch (DatasetFieldSetException ex) { errors.Add(ex.Key, ex.Message); continue; } break; } if (datasetInstanceSubValue != null) { context = datasetInstanceSubValue.ContextValue; } } } if (errors.Any()) { return(new ValidationErrorsResult(errors.Select(e => new ValidationError(e.Key.ToString(), e.Value)).ToArray())); } _unitOfWork.Repository <DatasetInstance>().Update(datasetInstance); _unitOfWork.Complete(); // Prepare response StringBuilder sb = new StringBuilder(); sb.AppendFormat("<table class='table table-bordered table-striped table-responsive' style='width: 100 %;' id='{0}'>", model.DatasetElementId.ToString()); sb.Append("<tr>"); // Populate tablet headers foreach (DatasetElementSub elementSub in datasetElementSubs .Where(es1 => es1.System == false) .Take(6) .OrderBy(es2 => es2.FieldOrder)) { sb.AppendFormat("<th>{0}</th>", elementSub.ElementName); } sb.Append("<th></th>"); sb.Append("</tr>"); // Now populate data var instanceSubValueGroups = _unitOfWork.Repository <DatasetInstanceValue>().Queryable() .Single(div => div.DatasetInstance.Id == datasetInstance.Id && div.DatasetElement.Id == model.DatasetElementId) .DatasetInstanceSubValues.GroupBy(g => g.ContextValue) .Select(disv => new DatasetInstanceSubValueGroupingModel { Context = disv.Key, Values = disv.Select(v => new DatasetInstanceSubValueModel { DatasetElementSubId = v.DatasetElementSub.Id, InstanceSubValueId = v.Id, InstanceValue = v.InstanceValue, InstanceValueType = (FieldTypes)v.DatasetElementSub.Field.FieldType.Id, InstanceValueRequired = v.DatasetElementSub.Field.Mandatory }).ToArray() }).ToArray(); foreach (DatasetInstanceSubValueGroupingModel group in instanceSubValueGroups) { sb.Append("<tr>"); foreach (DatasetElementSub elementSub in datasetElementSubs .Where(es1 => es1.System == false) .Take(6) .OrderBy(es2 => es2.FieldOrder)) { var value = group.Values.SingleOrDefault(gv => gv.DatasetElementSubId == elementSub.Id); sb.AppendFormat("<td>{0}</td>", value != null ? value.InstanceValue : ""); } // Action button sb.Append("<td><div class='btn-group'><button data-toggle='dropdown' class='btn btn-default btn-sm dropdown-toggle'>Action<span class='caret'></span></button><ul class='dropdown-menu pull-right'>"); sb.AppendFormat("<li><a data-toggle='modal' data-target='#editDatasetElementSubModal' data-id='{0}' data-context='{1}' data-datasetinstance='{2}' data-original-title='Edit {3} item'> Edit {3} item </a></li>", model.DatasetElementId, group.Context.ToString(), model.DatasetInstanceId, datasetElement.ElementName); sb.AppendFormat("<li><a data-toggle='modal' data-target='#deleteDatasetElementSubModal' data-id='{0}' data-context='{1}' data-datasetinstance='{2}' data-original-title='Delete {3} item'> Delete {3} item </a></li>", model.DatasetElementId, group.Context.ToString(), model.DatasetInstanceId, datasetElement.ElementName); sb.Append("</ul></div></td>"); sb.Append("</tr>"); } sb.Append("</table>"); return(Ok <string>(sb.ToString())); }
public HttpResponseMessage Post(JObject items) { if (items == null) { return(Request.CreateResponse(HttpStatusCode.NoContent, "No records to process ")); } dynamic json = items; List <PatientMedication> synchedPatientMedications = new List <PatientMedication>(); IList <PatientMedicationDTO> patientMedications = ((JArray)json.items) .Select(t => new PatientMedicationDTO { PatientMedicationIdentifier = ((dynamic)t).PatientMedicationIdentifier, PatientId = ((dynamic)t).PatientId, PatientMedicationId = ((dynamic)t).PatientMedicationId, MedicationId = ((dynamic)t).MedicationId, StartDate = ((dynamic)t).StartDate, EndDate = ((dynamic)t).EndDate, Dose = ((dynamic)t).Dose, DoseFrequency = ((dynamic)t).DoseFrequency, DoseUnit = ((dynamic)t).DoseUnit, CustomAttributes = ((dynamic)t).CustomAttributes == null ? null : ((JArray)(((dynamic)t).CustomAttributes)) .Select(x => new CustomAttributeDTO { CustomAttributeConfigId = ((dynamic)x).CustomAttributeConfigId, AttributeTypeName = ((dynamic)x).AttributeTypeName, AttributeName = ((dynamic)x).AttributeName, Category = ((dynamic)x).Category, EntityName = ((dynamic)x).EntityName, currentValue = ((dynamic)x).currentValue, lastUpdated = ((dynamic)x).lastUpdated != "" ? ((dynamic)x).lastUpdated : null, lastUpdatedUser = ((dynamic)x).lastUpdatedUser, Required = ((dynamic)x).Required, NumericMaxValue = ((dynamic)x).NumericMaxValue != "" ? ((dynamic)x).NumericMaxValue : null, NumericMinValue = ((dynamic)x).NumericMinValue != "" ? ((dynamic)x).NumericMinValue : null, StringMaxLength = ((dynamic)x).StringMaxLength != "" ? ((dynamic)x).StringMaxLength : null, FutureDateOnly = ((dynamic)x).FutureDateOnly != "" ? ((dynamic)x).FutureDateOnly : null, PastDateOnly = ((dynamic)x).PastDateOnly != "" ? ((dynamic)x).PastDateOnly : null }).ToList() }).ToList(); // Load entities depedency List <Medication> medications = unitOfWork.Repository <Medication>().Queryable().ToList(); foreach (PatientMedicationDTO patientMedication in patientMedications) { PatientMedication obj = unitOfWork.Repository <PatientMedication>() .Queryable() .SingleOrDefault(e => e.PatientMedicationGuid == patientMedication.PatientMedicationIdentifier); if (obj == null) { obj = new PatientMedication { PatientMedicationGuid = patientMedication.PatientMedicationIdentifier, //Id = patientMedication.PatientMedicationId, Patient = unitOfWork.Repository <Patient>().Queryable().SingleOrDefault(e => e.Id == patientMedication.PatientId), DateStart = patientMedication.StartDate, DateEnd = patientMedication.EndDate, Dose = patientMedication.Dose, DoseFrequency = patientMedication.DoseFrequency, DoseUnit = patientMedication.DoseUnit, Medication = medications.Find(x => x.Id == patientMedication.MedicationId) }; setCustomAttributes(patientMedication.CustomAttributes, obj); if (obj.Patient == null) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Can't find the patient for patient Medication record " + obj.PatientMedicationGuid)); } unitOfWork.Repository <PatientMedication>().Save(obj); synchedPatientMedications.Add(obj); } else // update record { obj.DateStart = patientMedication.StartDate; obj.DateEnd = patientMedication.EndDate; obj.Dose = patientMedication.Dose; obj.DoseFrequency = patientMedication.DoseFrequency; obj.DoseUnit = patientMedication.DoseUnit; obj.Medication = medications.Find(x => x.Id == patientMedication.MedicationId); setCustomAttributes(patientMedication.CustomAttributes, obj); synchedPatientMedications.Add(obj); unitOfWork.Repository <PatientMedication>().Update(obj); } } unitOfWork.Complete(); var insertedObjs = synchedPatientMedications.Select(p => new PatientMedicationDTO { PatientMedicationIdentifier = p.PatientMedicationGuid, PatientMedicationId = p.Id, PatientId = p.Patient.Id, MedicationId = p.Medication != null? p.Medication.Id: default(int), StartDate = p.DateStart, EndDate = p.DateEnd, Dose = p.Dose, DoseFrequency = p.DoseFrequency, DoseUnit = p.DoseUnit, CustomAttributes = getCustomAttributes(p) }).ToArray(); return(Request.CreateResponse(HttpStatusCode.OK, insertedObjs)); }
public ActionResult EditConfig(ConfigEditModel model) { ViewBag.MenuItem = CurrentMenuItem; if (ModelState.IsValid) { if (!String.IsNullOrEmpty(model.ConfigValue2)) { if (Regex.Matches(model.ConfigValue2, @"[-a-zA-Z0-9, ']").Count < model.ConfigValue2.Length) { ModelState.AddModelError("ConfigValue2", "Value contains invalid characters (Enter A-Z, a-z, 0-9, comma, space, hyphen)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.ConfigValue4)) { if (Regex.Matches(model.ConfigValue4, @"[0-9]").Count < model.ConfigValue4.Length) { ModelState.AddModelError("ConfigValue4", "Value contains invalid characters (Enter 0-9)"); return(View(model)); } } if (!String.IsNullOrEmpty(model.ConfigValue5)) { if (Regex.Matches(model.ConfigValue5, @"[0-9]").Count < model.ConfigValue5.Length) { ModelState.AddModelError("ConfigValue5", "Value contains invalid characters (Enter 0-9)"); return(View(model)); } } var config = unitOfWork.Repository <Config>().Queryable().SingleOrDefault(c => c.Id == model.ConfigId); if (config == null) { ModelState.AddModelError("ConfigType", "Unable to update the configuration. The configuration could not be found in the data store."); return(View(model)); } try { string encodedValue = ""; switch (config.ConfigType) { case ConfigType.E2BVersion: encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.ConfigValue1, false);; break; case ConfigType.WebServiceSubscriberList: encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.ConfigValue2, false);; break; case ConfigType.AssessmentScale: encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.ConfigValue3, false);; break; case ConfigType.ReportInstanceNewAlertCount: encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.ConfigValue4, false);; break; case ConfigType.MedicationOnsetCheckPeriodWeeks: encodedValue = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.ConfigValue5, false);; break; default: break; } config.ConfigValue = encodedValue; unitOfWork.Repository <Config>().Update(config); unitOfWork.Complete(); return(Redirect("/Admin/ManageConfig.aspx")); } catch (Exception ex) { ModelState.AddModelError("", string.Format("Unable to update the configuration: {0}", ex.Message)); } } ViewBag.ConfigValue1Items = new[] { new SelectListItem { Value = "E2B(R2) ICH Report", Text = "E2B(R2) ICH Report", Selected = true }, new SelectListItem { Value = "E2B(R3) ICH Report", Text = "E2B(R3) ICH Report" } }; ViewBag.ConfigValue3Items = new[] { new SelectListItem { Value = "Both Scales", Text = "Both Scales", Selected = true }, new SelectListItem { Value = "WHO Scale", Text = "WHO Scale" }, new SelectListItem { Value = "Naranjo Scale", Text = "Naranjo Scale" } }; return(View(model)); }
public ActionResult AddSpontaneous(DatasetInstanceModel model) { DatasetInstance datasetInstance = null; var datasetInstanceRepository = _unitOfWork.Repository <DatasetInstance>(); datasetInstance = datasetInstanceRepository .Queryable() .Include(di => di.Dataset) .Include("DatasetInstanceValues.DatasetInstanceSubValues.DatasetElementSub") .Include("DatasetInstanceValues.DatasetElement") .SingleOrDefault(di => di.Id == model.DatasetInstanceId); if (ModelState.IsValid) { if (datasetInstance == null) { ViewBag.Entity = "DatasetInstance"; return(View("NotFound")); } datasetInstance.Status = DatasetInstanceStatus.COMPLETE; var datasetElementIds = model.DatasetCategories.SelectMany(dc => dc.DatasetElements.Select(dse => dse.DatasetElementId)).ToArray(); var datasetElements = _unitOfWork.Repository <DatasetElement>() .Queryable() .Where(de => datasetElementIds.Contains(de.Id)) .ToDictionary(e => e.Id); var datasetElementSubs = datasetElements .SelectMany(de => de.Value.DatasetElementSubs) .ToDictionary(des => des.Id); try { for (int i = 0; i < model.DatasetCategories.Length; i++) { for (int j = 0; j < model.DatasetCategories[i].DatasetElements.Length; j++) { try { if (model.DatasetCategories[i].DatasetElements[j].DatasetElementType != "Table") { datasetInstance.SetInstanceValue(datasetElements[model.DatasetCategories[i].DatasetElements[j].DatasetElementId], model.DatasetCategories[i].DatasetElements[j].DatasetElementValue); } } catch (DatasetFieldSetException ex) { // Need to rename the key in order for the message to be bound to the correct control. throw new DatasetFieldSetException(string.Format("DatasetCategories[{0}].DatasetElements[{1}].DatasetElementValue", i, j), ex.Message); } } } datasetInstanceRepository.Update(datasetInstance); // Instantiate new instance of work flow var patientIdentifier = datasetInstance.GetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Identification Number")); if (String.IsNullOrWhiteSpace(patientIdentifier)) { patientIdentifier = datasetInstance.GetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Initials")); } var sourceIdentifier = datasetInstance.GetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Description of reaction")); _workflowService.CreateWorkFlowInstance("New Spontaneous Surveilliance Report", datasetInstance.DatasetInstanceGuid, patientIdentifier, sourceIdentifier); // Prepare medications List <ReportInstanceMedicationListItem> medications = new List <ReportInstanceMedicationListItem>(); var sourceProductElement = _unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Product Information"); var destinationProductElement = _unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Medicinal Products"); var sourceContexts = datasetInstance.GetInstanceSubValuesContext(sourceProductElement); foreach (Guid sourceContext in sourceContexts) { var drugItemValues = datasetInstance.GetInstanceSubValues(sourceProductElement, sourceContext); var drugName = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Product").InstanceValue; if (drugName != string.Empty) { var item = new ReportInstanceMedicationListItem() { MedicationIdentifier = drugName, ReportInstanceMedicationGuid = sourceContext }; medications.Add(item); } } _workflowService.AddOrUpdateMedicationsForWorkFlowInstance(datasetInstance.DatasetInstanceGuid, medications); _unitOfWork.Complete(); return(RedirectToAction("FormAdded", "Public")); } catch (DatasetFieldSetException dse) { ModelState.AddModelError(dse.Key, dse.Message); } } bool[] validCat; bool[] validMan; var rule = datasetInstance.Dataset.GetRule(DatasetRuleType.MandatoryFieldsProminent); if (rule.RuleActive) { validCat = new[] { true, false }; validMan = new[] { true, false }; } else { validCat = new[] { false }; validMan = new[] { true, false }; } var groupedDatasetCategoryElements = datasetInstance.Dataset.DatasetCategories.Where(dc => validCat.Contains(dc.System)).OrderBy(dc => dc.CategoryOrder) .SelectMany(dc => dc.DatasetCategoryElements).Where(dce => (rule.RuleActive && (dce.DatasetCategory.System == true && dce.DatasetElement.Field.Mandatory == true) || (dce.DatasetCategory.System == false && dce.DatasetElement.Field.Mandatory == false)) || (!rule.RuleActive && validMan.Contains(dce.DatasetElement.Field.Mandatory))).OrderBy(dce => dce.FieldOrder) .GroupBy(dce => dce.DatasetCategory) .ToList(); model.DatasetCategories = groupedDatasetCategoryElements .Select(dsc => new DatasetCategoryEditModel { DatasetCategoryId = dsc.Key.Id, DatasetCategoryDisplayName = String.IsNullOrWhiteSpace(dsc.Key.FriendlyName) ? dsc.Key.DatasetCategoryName : dsc.Key.FriendlyName, DatasetCategoryHelp = dsc.Key.Help, DatasetElements = dsc.Select(e => new DatasetElementEditModel { DatasetElementId = e.DatasetElement.Id, DatasetElementName = e.DatasetElement.ElementName, DatasetElementDisplayName = String.IsNullOrWhiteSpace(e.FriendlyName) ? e.DatasetElement.ElementName : e.FriendlyName, DatasetElementHelp = e.Help, DatasetElementRequired = e.DatasetElement.Field.Mandatory, DatasetElementDisplayed = true, DatasetElementChronic = false, DatasetElementType = e.DatasetElement.Field.FieldType.Description, DatasetElementValue = datasetInstance.GetInstanceValue(e.DatasetElement), DatasetElementSubs = e.DatasetElement.DatasetElementSubs.Select(es => new DatasetElementSubEditModel { DatasetElementSubId = es.Id, DatasetElementSubName = es.ElementName, DatasetElementSubRequired = es.Field.Mandatory, DatasetElementSubType = es.Field.FieldType.Description //, //DatasetElementSubValue = datasetInstance.GetInstanceSubValue(es) }).ToArray() }) .ToArray() }) .ToArray(); var selectTypeDatasetElements = model.DatasetCategories .SelectMany(dc => dc.DatasetElements) .Where(de => de.DatasetElementType == FieldTypes.Listbox.ToString() || de.DatasetElementType == FieldTypes.DropDownList.ToString()) .ToArray(); var yesNoDatasetElements = model.DatasetCategories .SelectMany(dc => dc.DatasetElements) .Where(de => de.DatasetElementType == FieldTypes.YesNo.ToString()) .ToArray(); var datasetElementRepository = _unitOfWork.Repository <DatasetElement>(); var datasetElementSubRepository = _unitOfWork.Repository <DatasetElementSub>(); foreach (var element in selectTypeDatasetElements) { var elementFieldValues = datasetElementRepository.Queryable() .SingleOrDefault(de => de.Id == element.DatasetElementId) .Field.FieldValues .ToList(); var elementFieldValueList = new List <SelectListItem> { { new SelectListItem { Value = "", Text = "" } } }; elementFieldValueList.AddRange(elementFieldValues.Select(ev => new SelectListItem { Value = ev.Value, Text = ev.Value, Selected = element.DatasetElementValue == ev.Value })); ViewData.Add(element.DatasetElementName, elementFieldValueList.ToArray()); } foreach (var element in yesNoDatasetElements) { var yesNo = new[] { new SelectListItem { Value = "", Text = "" }, new SelectListItem { Value = "No", Text = "No" }, new SelectListItem { Value = "Yes", Text = "Yes" } }; var selectedYesNo = yesNo.SingleOrDefault(yn => yn.Value == element.DatasetElementValue); if (selectedYesNo != null) { selectedYesNo.Selected = true; } ViewData.Add(element.DatasetElementName, yesNo); } return(View(model)); }
public ActionResult AddPatientLabTest(PatientLabTestAddModel model) { ViewBag.MenuItem = CurrentMenuItem; var returnUrl = (TempData["returnUrl"] ?? string.Empty).ToString(); ViewBag.ReturnUrl = returnUrl; var patient = unitOfWork.Repository <Patient>().Get(model.PatientId); if (patient == null) { ViewBag.Entity = "Patient"; return(View("NotFound")); } if (model.TestDate < patient.DateOfBirth) { ModelState.AddModelError("TestDate", "Test Date should be after Date Of Birth"); } if (ModelState.IsValid) { var labTest = unitOfWork.Repository <LabTest>().Get(model.LabTestId); if (labTest == null) { ViewBag.Entity = "Lab Test"; return(View("NotFound")); } try { var labTestUnit = unitOfWork.Repository <LabTestUnit>().Queryable().SingleOrDefault(lu => lu.Id == model.LabTestUnitId); var patientLabTest = new PatientLabTest { Patient = patient, LabTest = labTest, TestDate = model.TestDate, TestResult = model.TestResult, LabValue = model.LabValue, TestUnit = labTestUnit, ReferenceLower = model.ReferenceLower, ReferenceUpper = model.ReferenceUpper }; if (model.CustomAttributes != null) { var patientLabTestExtended = (IExtendable)patientLabTest; var customAttributes = unitOfWork.Repository <CustomAttributeConfiguration>().Queryable().Where(ca => ca.ExtendableTypeName == typeof(PatientLabTest).Name).ToList(); for (int i = 0; i < model.CustomAttributes.Length; i++) { var attributeConfig = GetFrameworkCustomAttributeConfig(customAttributes, model.CustomAttributes[i].Name); // If there is not custom attribute configured with this name, ignore. if (attributeConfig == null) { continue; } try { if (attributeConfig.IsRequired && string.IsNullOrWhiteSpace(model.CustomAttributes[i].Value)) { ModelState.AddModelError(string.Format("CustomAttributes[{0}].Value", i), string.Format("{0} is required.", model.CustomAttributes[i].Name)); continue; } switch (model.CustomAttributes[i].Type) { case "Numeric": decimal number = 0M; if (decimal.TryParse(model.CustomAttributes[i].Value, out number)) { patientLabTestExtended.ValidateAndSetAttributeValue(attributeConfig, number, User.Identity.Name); } break; case "Selection": Int32 selection = 0; if (Int32.TryParse(model.CustomAttributes[i].Value, out selection)) { patientLabTestExtended.ValidateAndSetAttributeValue(attributeConfig, selection, User.Identity.Name); } break; case "DateTime": DateTime parsedDate = DateTime.MinValue; if (DateTime.TryParse(model.CustomAttributes[i].Value, out parsedDate)) { patientLabTestExtended.ValidateAndSetAttributeValue(attributeConfig, parsedDate, User.Identity.Name); } break; case "String": default: patientLabTestExtended.ValidateAndSetAttributeValue(attributeConfig, model.CustomAttributes[i].Value ?? string.Empty, User.Identity.Name); break; } } catch (CustomAttributeValidationException ve) { ModelState.AddModelError(string.Format("CustomAttributes[{0}].Value", i), ve.Message); continue; } } } if (ModelState.IsValid) { unitOfWork.Repository <PatientLabTest>().Save(patientLabTest); unitOfWork.Complete(); HttpCookie cookie = new HttpCookie("PopUpMessage"); cookie.Value = "Test and procedure added successfully"; Response.Cookies.Add(cookie); return(Redirect("/Patient/PatientView.aspx?pid=" + patientLabTest.Patient.Id.ToString())); } } catch (Exception ex) { ModelState.AddModelError("", string.Format("Unable to add the Patient Lab Test: {0}", ex.Message)); } } // Prepare custom attributes var cattributes = unitOfWork.Repository <CustomAttributeConfiguration>() .Queryable() .Where(ca => ca.ExtendableTypeName == typeof(PatientLabTest).Name) .ToList(); model.CustomAttributes = cattributes.Select(c => new CustomAttributeAddModel { Name = c.AttributeKey, Detail = c.AttributeDetail == null ? "" : "(" + c.AttributeDetail + ")", Type = c.CustomAttributeType.ToString(), IsRequired = c.IsRequired, StringMaxLength = c.StringMaxLength, NumericMinValue = c.NumericMinValue, NumericMaxValue = c.NumericMaxValue, PastDateOnly = c.PastDateOnly, FutureDateOnly = c.FutureDateOnly }) .ToArray(); var selectiondataRepository = unitOfWork.Repository <SelectionDataItem>(); if (model.CustomAttributes != null) { foreach (var selectCustomAttribute in model.CustomAttributes.Where(c => c.Type == VPS.CustomAttributes.CustomAttributeType.Selection.ToString())) { ViewData[selectCustomAttribute.Name] = selectiondataRepository .Queryable() .Where(sd => sd.AttributeKey == selectCustomAttribute.Name) .Select(s => new SelectListItem { Value = s.SelectionKey, Text = s.Value }) .ToArray(); } } var labTests = new List <SelectListItem> { { new SelectListItem { Value = "", Text = "" } } }; labTests.AddRange(unitOfWork.Repository <LabTest>() .Queryable() .Select(c => new SelectListItem { Value = c.Id.ToString(), Text = c.Description }) .OrderBy(c => c.Text) .ToArray()); ViewBag.LabTests = labTests; var labTestUnits = new List <SelectListItem> { { new SelectListItem { Value = "", Text = "" } } }; labTestUnits.AddRange(unitOfWork.Repository <LabTestUnit>() .Queryable() .OrderBy(c => c.Description) .Select(c => new SelectListItem { Value = c.Id.ToString(), Text = c.Description }) .ToArray()); ViewBag.LabTestUnits = labTestUnits; var labResults = new List <SelectListItem> { { new SelectListItem { Value = "", Text = "" } } }; labResults.AddRange(unitOfWork.Repository <LabResult>() .Queryable() .OrderBy(c => c.Description) .Select(c => new SelectListItem { Value = c.Description, Text = c.Description }) .ToArray()); ViewBag.TestResults = labResults; TempData["returnUrl"] = returnUrl; return(View(model)); }
public HttpResponseMessage Post(JObject data) { if (data == null) { return(Request.CreateResponse(HttpStatusCode.NoContent, "No records to process ")); } dynamic json = data; List <Encounter> synchedEncounters = new List <Encounter>(); IList <EncounterDTO> encounters = ((JArray)json.items) .Select(t => new EncounterDTO { EncounterIdentifier = ((dynamic)t).EncounterIdentifier, EncounterDate = ((dynamic)t).EncounterDate != "" ? ((dynamic)t).EncounterDate : null, EncounterId = ((dynamic)t).EncounterId, EncounterPriority = ((dynamic)t).EncounterPriority, EncounterType = ((dynamic)t).EncounterType, CreatedBy = ((dynamic)t).CreatedBy, UpdatedBy = ((dynamic)t).UpdatedBy, PatientId = ((dynamic)t).PatientId, Notes = ((dynamic)t).Notes, EncounterCreatedDate = ((dynamic)t).EncounterCreatedDate != "" ? ((dynamic)t).EncounterCreatedDate : null, EncounterUpdatedDate = ((dynamic)t).EncounterUpdatedDate != "" ? ((dynamic)t).EncounterUpdatedDate : null }).ToList(); foreach (EncounterDTO encounter in encounters) { var obj = unitOfWork.Repository <Encounter>() .Queryable() .SingleOrDefault(e => e.EncounterGuid == encounter.EncounterIdentifier); var encounterType = unitOfWork.Repository <EncounterType>().Queryable().SingleOrDefault(et => et.Id == encounter.EncounterType); var priority = unitOfWork.Repository <Priority>().Queryable().SingleOrDefault(p => p.Id == encounter.EncounterPriority); if (obj == null) { Patient patient = unitOfWork.Repository <Patient>().Queryable().SingleOrDefault(e => e.Id == encounter.PatientId); //var currentUser = unitOfWork.Repository<User>().Queryable().SingleOrDefault(u => u.UserName == encounter.CreatedBy); obj = new Encounter(patient) { EncounterGuid = encounter.EncounterIdentifier, // Id = encounter.EncounterId, EncounterDate = encounter.EncounterDate, EncounterType = encounterType, Priority = priority, ArchivedDate = null, //Created = encounter.EncounterCreatedDate, //CreatedBy = currentUser, Notes = encounter.Notes }; unitOfWork.Repository <Encounter>().Save(obj); synchedEncounters.Add(obj); } else { obj.EncounterDate = encounter.EncounterDate; obj.EncounterType = encounterType; obj.Priority = priority; obj.Notes = encounter.Notes; unitOfWork.Repository <Encounter>().Update(obj); synchedEncounters.Add(obj); } } unitOfWork.Complete(); var insertedObjs = synchedEncounters.Select(e => new EncounterDTO { EncounterIdentifier = e.EncounterGuid, PatientId = e.Patient.Id, EncounterId = e.Id, EncounterDate = e.EncounterDate, Notes = e.Notes, EncounterPriority = e.Priority.Id, EncounterType = e.EncounterType.Id, EncounterCreatedDate = e.Created, EncounterUpdatedDate = e.LastUpdated, CreatedBy = e.CreatedBy.FullName, UpdatedBy = e.UpdatedBy != null ? e.UpdatedBy.FullName : null }).ToArray(); return(Request.CreateResponse(HttpStatusCode.OK, insertedObjs)); }
public ActionResult DeletePatient(PatientDeleteModel model) { ViewBag.MenuItem = CurrentMenuItem; var cancelRedirectUrl = (TempData["cancelRedirectUrl"] ?? string.Empty).ToString(); ViewBag.cancelRedirectUrl = cancelRedirectUrl; ArrayList errors = new ArrayList(); if (ModelState.IsValid) { var patient = unitOfWork.Repository <Patient>().Queryable().SingleOrDefault(u => u.Id == model.PatientId); var currentUser = GetCurrentUser(); try { var reason = model.ArchiveReason.Trim() == "" ? "** NO REASON SPECIFIED ** " : model.ArchiveReason; var archivedDate = DateTime.Now; foreach (var appointment in patient.Appointments.Where(x => !x.Archived)) { appointment.Archived = true; appointment.ArchivedDate = archivedDate; appointment.ArchivedReason = reason; appointment.AuditUser = currentUser; unitOfWork.Repository <Appointment>().Update(appointment); } foreach (var attachment in patient.Attachments.Where(x => !x.Archived)) { attachment.Archived = true; attachment.ArchivedDate = archivedDate; attachment.ArchivedReason = reason; attachment.AuditUser = currentUser; unitOfWork.Repository <Attachment>().Update(attachment); } foreach (var enrolment in patient.CohortEnrolments.Where(x => !x.Archived)) { enrolment.Archived = true; enrolment.ArchivedDate = archivedDate; enrolment.ArchivedReason = reason; enrolment.AuditUser = currentUser; unitOfWork.Repository <CohortGroupEnrolment>().Update(enrolment); } foreach (var encounter in patient.Encounters.Where(x => !x.Archived)) { encounter.Archived = true; encounter.ArchivedDate = archivedDate; encounter.ArchivedReason = reason; encounter.AuditUser = currentUser; unitOfWork.Repository <Encounter>().Update(encounter); } foreach (var clinicalEvent in patient.PatientClinicalEvents.Where(x => !x.Archived)) { clinicalEvent.Archived = true; clinicalEvent.ArchivedDate = archivedDate; clinicalEvent.ArchivedReason = reason; clinicalEvent.AuditUser = currentUser; unitOfWork.Repository <PatientClinicalEvent>().Update(clinicalEvent); } foreach (var condition in patient.PatientConditions.Where(x => !x.Archived)) { condition.Archived = true; condition.ArchivedDate = archivedDate; condition.ArchivedReason = reason; condition.AuditUser = currentUser; unitOfWork.Repository <PatientCondition>().Update(condition); } foreach (var facility in patient.PatientFacilities.Where(x => !x.Archived)) { facility.Archived = true; facility.ArchivedDate = archivedDate; facility.ArchivedReason = reason; facility.AuditUser = currentUser; unitOfWork.Repository <PatientFacility>().Update(facility); } foreach (var labTest in unitOfWork.Repository <PatientLabTest>().Queryable().Include(plt => plt.Patient).Include(plt => plt.LabTest).Include(plt => plt.TestUnit).Where(x => x.Patient.Id == patient.Id && !x.Archived)) { labTest.Archived = true; labTest.ArchivedDate = archivedDate; labTest.ArchivedReason = reason; labTest.AuditUser = currentUser; unitOfWork.Repository <PatientLabTest>().Update(labTest); } foreach (var medication in patient.PatientMedications.Where(x => !x.Archived)) { medication.Archived = true; medication.ArchivedDate = archivedDate; medication.ArchivedReason = reason; medication.AuditUser = currentUser; unitOfWork.Repository <PatientMedication>().Update(medication); } foreach (var status in patient.PatientStatusHistories.Where(x => !x.Archived)) { status.Archived = true; status.ArchivedDate = archivedDate; status.ArchivedReason = reason; status.AuditUser = currentUser; unitOfWork.Repository <PatientStatusHistory>().Update(status); } patient.Archived = true; patient.ArchivedDate = archivedDate; patient.ArchivedReason = reason; patient.AuditUser = currentUser; unitOfWork.Repository <Patient>().Update(patient); unitOfWork.Complete(); } catch (DbUpdateException ex) { errors.Add("Unable to archive patient. " + ex.Message); } catch (DbEntityValidationException ex) { var err = string.Empty; foreach (var eve in ex.EntityValidationErrors) { foreach (var ve in eve.ValidationErrors) { err += String.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } errors.Add(err); } if (errors.Count == 0) { HttpCookie cookie = new HttpCookie("PopUpMessage"); cookie.Value = "Patient record deleted successfully"; Response.Cookies.Add(cookie); return(Redirect("/Patient/PatientSearch.aspx")); } else { AddErrors(errors); } } return(View(model)); }
public ActionResult EditCohort(CohortEditModel model) { ViewBag.MenuItem = CurrentMenuItem; if (ModelState.IsValid) { if (unitOfWork.Repository <CohortGroup>().Queryable().Any(cg => cg.Id != model.CohortId && cg.CohortName == model.CohortName)) { ModelState.AddModelError("CohortName", "A cohort with the specified name already exists."); } if (Regex.Matches(model.CohortName, @"[a-zA-Z0-9 ']").Count < model.CohortName.Length) { ModelState.AddModelError("CohortName", "Cohort name contains invalid characters (Enter A-Z, a-z, 0-9)"); } if (unitOfWork.Repository <CohortGroup>().Queryable().Any(cg => cg.Id != model.CohortId && cg.CohortCode == model.CohortCode)) { ModelState.AddModelError("CohortCode", "A cohort with the specified code already exists."); } if (Regex.Matches(model.CohortCode, @"[-a-zA-Z0-9 ']").Count < model.CohortCode.Length) { ModelState.AddModelError("CohortCode", "Cohort code contains invalid characters (Enter -, A-Z, a-z, 0-9)"); } if (model.FinishDate != null) { if (model.FinishDate > DateTime.Today.AddYears(20)) { ModelState.AddModelError("FinishDate", "End Date should be within 20 years"); } if (model.FinishDate < model.StartDate) { ModelState.AddModelError("FinishDate", "End Date should be after Start Date"); } } var encodedName = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.CohortName, false); var encodedCode = System.Web.Security.AntiXss.AntiXssEncoder.HtmlEncode(model.CohortCode, false); var condition = unitOfWork.Repository <Condition>().Queryable().SingleOrDefault(cg => cg.Id == model.ConditionId); var cohortGroup = unitOfWork.Repository <CohortGroup>().Queryable().SingleOrDefault(cg => cg.Id == model.CohortId); if (cohortGroup == null) { ModelState.AddModelError("CohortName", "Unable to update the cohort. The cohort could not be found in the data store."); } try { cohortGroup.CohortName = encodedName; cohortGroup.CohortCode = encodedCode; cohortGroup.StartDate = model.StartDate; cohortGroup.FinishDate = model.FinishDate; cohortGroup.Condition = condition; if (ModelState.IsValid) { unitOfWork.Repository <CohortGroup>().Update(cohortGroup); unitOfWork.Complete(); return(Redirect("/Cohort/CohortSearch.aspx")); } } catch (Exception ex) { ModelState.AddModelError("CohortName", string.Format("Unable to update the cohort: {0}", ex.Message)); } } var conditions = unitOfWork.Repository <Condition>() .Queryable() .ToList(); var cgList = new List <SelectListItem> { { new SelectListItem { Value = "", Text = "" } } }; cgList.AddRange(conditions.Select(cg => new SelectListItem { Value = cg.Id.ToString(), Text = cg.Description })); ViewBag.Conditions = cgList; return(View(model)); }
public HttpResponseMessage Post(JObject items) { if (items == null) { return(Request.CreateResponse(HttpStatusCode.NoContent, "No records to process ")); } dynamic json = items; List <PatientLabTest> synchedPatientLabTest = new List <PatientLabTest>(); IList <PatientLabTestDTO> patientLabTests = ((JArray)json.items) .Select(t => new PatientLabTestDTO { PatientId = ((dynamic)t).PatientId, PatientLabTestId = ((dynamic)t).PatientLabTestId, PatientLabTestIdentifier = ((dynamic)t).PatientLabTestIdentifier, TestDate = ((dynamic)t).TestDate != null ? ((dynamic)t).TestDate : null, TestName = ((dynamic)t).TestName, TestResult = (((dynamic)t).TestResult != null && ((dynamic)t).TestResult != "") ? ((dynamic)t).TestResult : null, TestUnit = (((dynamic)t).TestUnit != null && ((dynamic)t).TestUnit != "") ? ((dynamic)t).TestUnit : default(decimal?), LabValue = (((dynamic)t).LabValue != null && ((dynamic)t).LabValue != "") ? ((dynamic)t).LabValue : default(int?), customAttributes = ((dynamic)t).customAttributes == null ? null : ((JArray)(((dynamic)t).customAttributes)) .Select(x => new CustomAttributeDTO { CustomAttributeConfigId = ((dynamic)x).CustomAttributeConfigId, AttributeTypeName = ((dynamic)x).AttributeTypeName, AttributeName = ((dynamic)x).AttributeName, Category = ((dynamic)x).Category, EntityName = ((dynamic)x).EntityName, currentValue = ((dynamic)x).currentValue, lastUpdated = ((dynamic)x).lastUpdated != "" ? ((dynamic)x).lastUpdated : null, lastUpdatedUser = ((dynamic)x).lastUpdatedUser, Required = ((dynamic)x).Required, NumericMaxValue = ((dynamic)x).NumericMaxValue != "" ? ((dynamic)x).NumericMaxValue : null, NumericMinValue = ((dynamic)x).NumericMinValue != "" ? ((dynamic)x).NumericMinValue : null, StringMaxLength = ((dynamic)x).StringMaxLength != "" ? ((dynamic)x).StringMaxLength : null, FutureDateOnly = ((dynamic)x).FutureDateOnly != "" ? ((dynamic)x).FutureDateOnly : null, PastDateOnly = ((dynamic)x).PastDateOnly != "" ? ((dynamic)x).PastDateOnly : null }).ToList() }).ToList(); var labTestUnits = unitOfWork.Repository <LabTestUnit>().Queryable().ToList(); var labTests = unitOfWork.Repository <LabTest>().Queryable().ToList(); foreach (PatientLabTestDTO labTest in patientLabTests) { PatientLabTest obj = unitOfWork.Repository <PatientLabTest>() .Queryable() .SingleOrDefault(e => e.PatientLabTestGuid == labTest.PatientLabTestIdentifier); if (obj == null) { obj = new PatientLabTest { PatientLabTestGuid = labTest.PatientLabTestIdentifier, Patient = unitOfWork.Repository <Patient>().Queryable().SingleOrDefault(e => e.Id == labTest.PatientId), //Id = labTest.PatientLabTestId, TestDate = labTest.TestDate, TestResult = labTest.TestResult, LabValue = labTest.LabValue, LabTest = labTests.SingleOrDefault(e => e.Description == labTest.TestName), TestUnit = labTestUnits.SingleOrDefault(e => e.Id == labTest.TestUnit) }; setCustomAttributes(labTest.customAttributes, obj); unitOfWork.Repository <PatientLabTest>().Save(obj); synchedPatientLabTest.Add(obj); } else { obj.TestDate = labTest.TestDate; obj.TestResult = labTest.TestResult; obj.LabValue = labTest.LabValue; obj.LabTest = labTests.SingleOrDefault(e => e.Description == labTest.TestName); obj.TestUnit = labTestUnits.SingleOrDefault(e => e.Id == labTest.TestUnit); setCustomAttributes(labTest.customAttributes, obj); synchedPatientLabTest.Add(obj); unitOfWork.Repository <PatientLabTest>().Update(obj); } } unitOfWork.Complete(); var insertedObjs = synchedPatientLabTest.Select(p => new PatientLabTestDTO { PatientId = p.Patient.Id, PatientLabTestId = p.Id, PatientLabTestIdentifier = p.PatientLabTestGuid, TestName = p.LabTest != null ? p.LabTest.Description : "", TestDate = p.TestDate, TestResult = p.TestResult, LabValue = p.LabValue, TestUnit = p.TestUnit != null ? p.TestUnit.Id : 0, customAttributes = getCustomAttributes(p) }).ToArray(); return(Request.CreateResponse(HttpStatusCode.OK, insertedObjs)); }
public IHttpActionResult SaveDatasetInstanceSubValues(DatasetInstanceSubValuesSaveModel model) { if (model.Values.All(v => v.Value == null) && model.SubValueContext == default(Guid)) { // Nothing to do return(Ok <string>("{ result: \"Ok\" }")); } var errors = new Dictionary <string, string>(); var datasetInstance = unitOfWork.Repository <DatasetInstance>() .Queryable() .Include(i => i.Dataset) .Include(i => i.DatasetInstanceValues.Select(i2 => i2.DatasetInstanceSubValues)) .SingleOrDefault(di => di.Id == model.DatasetInstanceId); if (datasetInstance == null) { return(NotFound()); } var datasetElementSubIds = model.Values.Select(v => v.DatasetElementSubId).ToArray(); var datasetElementSubs = unitOfWork.Repository <DatasetElementSub>() .Queryable() .Where(des => datasetElementSubIds.Contains(des.Id)) .ToList(); var context = model.SubValueContext; DatasetInstanceSubValue datasetInstanceSubValue = null; int fieldValueId = 0; foreach (var datasetElementSub in datasetElementSubs) { var instanceSubValueModel = model.Values.SingleOrDefault(v => v.DatasetElementSubId == datasetElementSub.Id); if (instanceSubValueModel != null) { switch ((FieldTypes)datasetElementSub.Field.FieldType.Id) { case FieldTypes.DropDownList: case FieldTypes.Listbox: if (int.TryParse(instanceSubValueModel.Value.ToString(), out fieldValueId)) { var instanceSubValue = datasetElementSub.Field.FieldValues.SingleOrDefault(fv => fv.Id == fieldValueId); if (instanceSubValue != null) { try { datasetInstanceSubValue = datasetInstance.SetInstanceSubValue(datasetElementSub, instanceSubValue.Value, context); } catch (DatasetFieldSetException ex) { errors.Add(ex.Key, ex.Message); continue; } } else { if (datasetElementSub.Field.Mandatory) { errors.Add(datasetElementSub.Id.ToString(), string.Format("{0} is required.", datasetElementSub.ElementName)); continue; } } } else { if (datasetElementSub.Field.Mandatory) { errors.Add(datasetElementSub.Id.ToString(), string.Format("{0} is required.", datasetElementSub.ElementName)); continue; } } break; case FieldTypes.YesNo: default: try { datasetInstanceSubValue = datasetInstance.SetInstanceSubValue(datasetElementSub, instanceSubValueModel.Value.ToString(), context); } catch (DatasetFieldSetException ex) { errors.Add(ex.Key, ex.Message); continue; } break; } if (datasetInstanceSubValue != null) { context = datasetInstanceSubValue.ContextValue; } } } if (errors.Any()) { return(new ValidationErrorsResult(errors.Select(e => new ValidationError(e.Key.ToString(), e.Value)).ToArray())); } unitOfWork.Repository <DatasetInstance>().Update(datasetInstance); unitOfWork.Complete(); return(Ok <string>("{ result: \"Ok\" }")); }