Beispiel #1
0
        public async Task <IHttpActionResult> PutDoctor(long id, Doctor doctor)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != doctor.doctorID)
            {
                return(BadRequest());
            }

            db.Entry(doctor).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DoctorExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Beispiel #2
0
        public async Task <HttpResponseMessage> RemovePatientAlert(DeleteAlertModel model)
        {
            try
            {
                Alert alert = db.Alerts.Where(all => all.alertID == model.alertID && all.active == true).FirstOrDefault();

                if (alert == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Alert not found."
                    });
                    response.ReasonPhrase = "Alert not found.";
                    return(response);
                }
                alert.active          = false;//Delete Operation changed
                alert.mb              = model.userID;
                alert.md              = System.DateTime.Now;
                db.Entry(alert).State = EntityState.Modified;
                await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                return(ThrowError(ex, "DeletePatientAlert in AlertsController."));
            }

            response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                ID = model.alertID, message = ""
            });
            return(response);
        }
Beispiel #3
0
        public async Task <HttpResponseMessage> addPatientFamilyHX(PatientFamilyHX_Custom model)
        {
            PatientFamilyHX phx = new PatientFamilyHX();

            try
            {
                if (model.name == null || model.name == "")
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid familyHX."
                    });
                    return(response);
                }
                if (model.patientID == null || model.patientID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid patient id."
                    });
                    return(response);
                }

                phx = db.PatientFamilyHXes.Where(p => p.name.Trim() == model.name.Trim() && p.patientID == model.patientID).FirstOrDefault();
                if (phx != null)
                {
                    phx.relationship    = model.relationship;
                    phx.md              = System.DateTime.Now;
                    phx.mb              = phx.patientID.ToString();
                    phx.active          = true;
                    db.Entry(phx).State = EntityState.Modified;
                    await db.SaveChangesAsync();

                    response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                        ID = phx.fhxid, message = ""
                    });
                    return(response);
                }
                if (phx == null)
                {
                    phx              = new PatientFamilyHX();
                    phx.active       = true;
                    phx.name         = model.name;
                    phx.relationship = model.relationship;
                    phx.patientID    = model.patientID;
                    phx.cd           = System.DateTime.Now;
                    phx.cb           = model.patientID.ToString();
                    db.PatientFamilyHXes.Add(phx);
                    await db.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                return(ThrowError(ex, "AddPatientFamilyHX in PatientFamilyHXController."));
            }

            response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                ID = phx.fhxid, message = ""
            });
            return(response);
        }
        public async Task <HttpResponseMessage> EditPatientSugery(long surgeryID, PatientSurgery_Custom model)
        {
            PatientSurgery psurgery = new PatientSurgery();

            try
            {
                if (model.bodyPart == null || model.bodyPart == "" || !Regex.IsMatch(model.bodyPart.Trim(), "^[0-9a-zA-Z ]+$"))
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid surgery. Only letters and numbers are allowed."
                    });
                    return(response);
                }
                if (model.patientID == null || model.patientID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid patient id."
                    });
                    return(response);
                }
                psurgery = db.PatientSurgeries.Where(all => all.bodyPart.Trim() == model.bodyPart.Trim() && all.surgeryID != surgeryID && all.active == true).FirstOrDefault();
                if (psurgery != null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Surgery already exists."
                    });
                    response.ReasonPhrase = "Surgery already exists.";
                    return(response);
                }
                psurgery = db.PatientSurgeries.Where(m => m.surgeryID == surgeryID).FirstOrDefault();
                if (psurgery == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Surgery not found."
                    });
                    return(response);
                }

                psurgery.bodyPart        = model.bodyPart;
                psurgery.md              = System.DateTime.Now;
                psurgery.mb              = psurgery.patientID.ToString();
                db.Entry(psurgery).State = EntityState.Modified;
                await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                return(ThrowError(ex, "EditPatientSurgery in PatientSurgeriesController."));
            }

            response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                ID = surgeryID, message = ""
            });
            return(response);
        }
        public async Task <HttpResponseMessage> AddFavourite(FavouriteDoctorModel model)
        {
            FavouriteDoctor favdoc = new FavouriteDoctor();

            try
            {
                if (model.docID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid doctor ID."
                    });
                    return(response);
                }
                if (model.patID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid patient ID."
                    });
                    return(response);
                }
                favdoc = db.FavouriteDoctors.Where(fav => fav.doctorID == model.docID && fav.patientID == model.patID && fav.active == false).FirstOrDefault();
                if (favdoc != null)
                {
                    favdoc.active          = true;
                    favdoc.doctorID        = model.docID;
                    favdoc.patientID       = model.patID;
                    favdoc.mb              = model.patID.ToString();
                    favdoc.md              = System.DateTime.Now;
                    db.Entry(favdoc).State = EntityState.Modified;
                    await db.SaveChangesAsync();
                }
                else
                {
                    favdoc           = new FavouriteDoctor();
                    favdoc.active    = true;
                    favdoc.doctorID  = model.docID;
                    favdoc.patientID = model.patID;
                    favdoc.mb        = model.patID.ToString();
                    favdoc.md        = System.DateTime.Now;
                    db.FavouriteDoctors.Add(favdoc);
                    await db.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                ThrowError(ex, "AddFavourite in SearchDoctorController.");
            }

            response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                ID = favdoc.favID, message = ""
            });
            return(response);
        }
        public async Task <IHttpActionResult> PutSpeciallity(long id, Speciallity speciallity)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != speciallity.speciallityID)
            {
                return(BadRequest());
            }

            db.Entry(speciallity).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SpeciallityExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Beispiel #7
0
        public async Task <IHttpActionResult> PutAspNetUser(string id, AspNetUser aspNetUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != aspNetUser.Id)
            {
                return(BadRequest());
            }

            db.Entry(aspNetUser).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!AspNetUserExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
 public ActionResult Edit([Bind(Include = "allergyID,allergyName,active,cb,cd,mb,md")] Allergy allergy)
 {
     if (ModelState.IsValid)
     {
         db.Entry(allergy).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(allergy));
 }
        public async Task <HttpResponseMessage> EditPatientLifeStyle(PatientLifeStyleModel model)
        {
            PatientLifeStyle pls = new PatientLifeStyle();

            try
            {
                if (model.answer == null || model.answer == "")
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid answer."
                    });
                    return(response);
                }
                if (model.patientlifestyleID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid patient life style ID."
                    });
                    return(response);
                }
                if (model.patientID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid patient ID."
                    });
                    return(response);
                }
                pls = db.PatientLifeStyles.Where(all => all.patientlifestyleID == model.patientlifestyleID && all.patientID == model.patientID).FirstOrDefault();
                if (pls != null)
                {
                    pls.answer          = model.answer;
                    pls.md              = System.DateTime.Now;
                    pls.mb              = model.patientID.ToString();
                    db.Entry(pls).State = EntityState.Modified;
                    await db.SaveChangesAsync();
                }
                else
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "PatientLifeStyle not found."
                    });
                    return(response);
                }
            }
            catch (Exception ex)
            {
                return(ThrowError(ex, "EditPatientLifeStyle in PatientLifeStyleController."));
            }

            response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                ID = model.patientlifestyleID, message = ""
            });
            return(response);
        }
Beispiel #10
0
        public async Task <HttpResponseMessage> AddPharmacy(PatientPharmacy_Custom model)
        {
            Patient patient = new Patient();

            try
            {
                if (model.pharmacy == "" || model.pharmacy == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid pharmacy name. Only letters and numbers are allowed."
                    });
                    return(response);
                }
                if (model.patientID == 0 || model.patientID == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid patient ID"
                    });
                    return(response);
                }
                patient = db.Patients.Where(m => m.patientID == model.patientID).FirstOrDefault();
                if (patient == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Patient record not found."
                    });
                    return(response);
                }

                patient.pharmacy             = model.pharmacy;
                patient.pharmacyaddress      = model.pharmacyaddress;
                patient.pharmacycitystatezip = model.pharmacycitystatezip;
                patient.pharmacyid           = model.pharmacyid;
                patient.md = System.DateTime.Now;
                patient.mb = model.patientID.ToString();
                db.Entry(patient).State = EntityState.Modified;


                await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                return(ThrowError(ex, "AddPharmacy in PharmacyController."));
            }

            response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                ID = Convert.ToInt64(model.pharmacyid), message = ""
            });
            return(response);
        }
Beispiel #11
0
        public async Task <HttpResponseMessage> ReadMessage(long msgID)
        {
            try
            {
                Message email = new Message();
                if (msgID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid message ID."
                    });
                    return(response);
                }
                email = db.Messages.Where(msg => msg.msgID == msgID).FirstOrDefault();

                if (email == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Message not found."
                    });
                    return(response);
                }
                email.isRead          = true;
                email.md              = System.DateTime.Now;
                db.Entry(email).State = EntityState.Modified;
                await db.SaveChangesAsync();

                response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                    ID = msgID, message = ""
                });
                return(response);
            }
            catch (Exception ex)
            {
                return(ThrowError(ex, "ReadMessage in MessagesController."));
            }
        }
Beispiel #12
0
        public ActionResult Create(FormCollection collection)
        {
            var newsid     = "";
            var newstitle  = "";
            var newsdetail = "";

            byte[] thumbBytes   = null;
            byte[] detailBytes  = null;
            string thumbBase64  = "";
            string detailBase64 = "";

            ViewBag.successMessage = "";
            ViewBag.errorMessage   = "";
            if (Session["LogedUserID"] != null)
            {
                try
                {
                    var action = Request.Form["action"].ToString();
                    if (action == "create")
                    {
                        HttpPostedFileBase thumbnail   = Request.Files["thumbnailimage"];
                        HttpPostedFileBase detailimage = Request.Files["detailimage"];
                        newstitle    = Request.Form["newstitle"].ToString();
                        newsdetail   = Request.Form["newsdetail"].ToString();
                        thumbBytes   = util.ConvertToBytes(thumbnail);
                        detailBytes  = util.ConvertToBytes(detailimage);
                        thumbBase64  = "data:image/png;base64," + Convert.ToBase64String(thumbBytes);
                        detailBase64 = "data:image/png;base64," + Convert.ToBase64String(detailBytes);
                        var news = (
                            from p in db.News
                            where (p.newsTitle == newstitle || p.newsDetail == newsdetail && p.active == true)
                            select p
                            ).FirstOrDefault();
                        if (news != null)
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "News already exists";
                        }
                        if (news == null)
                        {
                            News newsObj = new News();
                            newsObj.active              = true;
                            newsObj.newsTitle           = newstitle;
                            newsObj.newsDetail          = newsdetail;
                            newsObj.newsThumbnailBase64 = thumbBase64;
                            newsObj.newsImageBase64     = detailBase64;
                            newsObj.cb = Session["LogedUserID"].ToString();
                            newsObj.cd = System.DateTime.UtcNow;
                            db.News.Add(newsObj);
                            db.SaveChanges();
                            //db.SP_AddNewss(newstitle, newsdetail, thumbBytes, detailBytes,Session["LogedUserID"].ToString());
                            //db.SaveChanges();
                            ViewBag.successMessage = "Record has been saved successfully";
                            ViewBag.errorMessage   = "";
                        }
                    }
                    if (action == "edit")
                    {
                        //HttpPostedFileBase thumbnail = Request.Files["tthumbnailimage"];
                        // HttpPostedFileBase detailimage = Request.Files["ddetailimage"];
                        if (Request.Files.Count == 2)
                        {
                            thumbBytes   = util.ConvertToBytes(Request.Files[0]);
                            detailBytes  = util.ConvertToBytes(Request.Files[1]);
                            thumbBase64  = "data:image/png;base64," + Convert.ToBase64String(thumbBytes);
                            detailBase64 = "data:image/png;base64," + Convert.ToBase64String(detailBytes);
                        }

                        newsid     = Request.Form["newsid"].ToString();
                        newstitle  = Request.Form["newstitle"].ToString();
                        newsdetail = Request.Form["newsdetail"].ToString();
                        long nid     = Convert.ToInt64(newsid);
                        News newsObj = new News();
                        newsObj = db.News.Where(n => n.newsID == nid && n.active == true).FirstOrDefault();
                        if (newsObj != null)
                        {
                            newsObj.active              = true;
                            newsObj.newsTitle           = newstitle;
                            newsObj.newsDetail          = newsdetail;
                            newsObj.newsThumbnailBase64 = thumbBase64;
                            newsObj.newsImageBase64     = detailBase64;
                            newsObj.mb = Session["LogedUserID"].ToString();
                            newsObj.md = System.DateTime.UtcNow;
                            db.Entry(newsObj).State = EntityState.Modified;
                            db.SaveChanges();
                        }

                        //db.sp_UpdateNews(Convert.ToInt64(newsid), newstitle, newsdetail, thumbBytes, detailBytes, Session["LogedUserID"].ToString(), System.DateTime.Now);
                        //db.SaveChanges();
                        ViewBag.successMessage = "Record has been saved successfully";
                        ViewBag.errorMessage   = "";
                    }
                    if (action == "delete")
                    {
                        newsid = Request.Form["newsid"].ToString();
                        db.sp_DeleteNews(Convert.ToInt64(newsid), Session["LogedUserID"].ToString(), System.DateTime.Now);
                        db.SaveChanges();
                        ViewBag.successMessage = "Record has been deleted successfully";
                        ViewBag.errorMessage   = "";
                    }
                    var __existingnewsList = db.SP_SelectNewss();
                    return(View(__existingnewsList));
                }
                catch (Exception ex)
                {
                    ViewBag.errorMessage = "Error occurred while processing your request.";
                    var _existingnewsList = db.SP_SelectNewss();
                    return(View(_existingnewsList));
                }
            }
            else
            {
                return(RedirectToAction("AdminLogin", "Account"));
            }
        }
Beispiel #13
0
        public async System.Threading.Tasks.Task <ActionResult> Create(FormCollection collection)
        {
            if (Session["LogedUserID"] != null)
            {
                var rolename = "";
                var desc     = "";
                var roleid   = "";
                ViewBag.successMessage = "";
                ViewBag.errorMessage   = "";
                try
                {
                    var action = Request.Form["action"].ToString();
                    if (action == "create")
                    {
                        rolename = Request.Form["rolename"].ToString();
                        desc     = Request.Form["desc"].ToString();

                        var role = new RoleManager <IdentityRole>(
                            new RoleStore <IdentityRole>(new ApplicationDbContext()));
                        if (!(role.RoleExists(rolename)))
                        {
                            var rm = new RoleManager <ApplicationRole>(

                                new RoleStore <ApplicationRole>(new ApplicationDbContext()));

                            var idResult = rm.Create(new ApplicationRole(rolename));
                            if (idResult.Succeeded)
                            {
                                AspNetRole thisRole = db.AspNetRoles.Where(r => r.Name.Equals(rolename, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                                thisRole.Description     = desc;
                                db.Entry(thisRole).State = EntityState.Modified;
                                db.SaveChanges();
                            }

                            ViewBag.successMessage = "Record has been saved successfully";
                            ViewBag.errorMessage   = "";
                        }
                        else
                        {
                            ViewBag.errorMessage   = "Role already exists.";
                            ViewBag.successMessage = "";
                        }
                    }
                    if (action == "edit")
                    {
                        //roleid = Request.Form["id"].ToString();
                        rolename = Request.Form["rolename"].ToString();
                        desc     = Request.Form["desc"].ToString();
                        AspNetRole thisRole = db.AspNetRoles.Where(r => r.Name.Equals(rolename, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                        thisRole.Description     = desc;
                        thisRole.Name            = rolename;
                        db.Entry(thisRole).State = EntityState.Modified;
                        db.SaveChanges();
                        ViewBag.successMessage = "Record has been saved successfully";
                        ViewBag.errorMessage   = "";
                        var _existingroleList = db.AspNetRoles.ToList();
                        return(View(_existingroleList));
                    }
                    if (action == "delete")
                    {
                        roleid = Request.Form["id"].ToString();
                        AspNetRole thisRole = db.AspNetRoles.Where(r => r.Id.Equals(roleid, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                        db.AspNetRoles.Remove(thisRole);
                        db.SaveChanges();
                        ViewBag.successMessage = "Record has been deleted successfully";
                        ViewBag.errorMessage   = "";
                    }
                    var __existingroleList = db.SP_SelectRole();
                    return(View(__existingroleList));
                }
                catch (Exception ex)
                {
                    ViewBag.errorMessage = "Error occurred while processing your request.";
                    var _existingroleList = db.SP_SelectRole();
                    return(View(_existingroleList));
                }
            }
            else
            {
                return(RedirectToAction("AdminLogin", "Account"));
            }
        }
        public async Task <IHttpActionResult> PutDoctorTiming(long id, DoctorTimingsModel doctorTimingModel)
        {
            var doctorTiming = new DoctorTiming();
            var timingsList  = GetDoctorTimingByDoctorId(id);
            var alreadItems  = timingsList
                               .Where(o => o.day == doctorTimingModel.day &&
                                      (o.from == doctorTimingModel.from || o.to == doctorTimingModel.to
                                       ||
                                       (
                                           DateTime.ParseExact(doctorTimingModel.from, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay >=
                                           DateTime.ParseExact(o.from, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay
                                           &&
                                           DateTime.ParseExact(doctorTimingModel.from, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay <=
                                           DateTime.ParseExact(o.to, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay

                                       )
                                       ||
                                       (
                                           DateTime.ParseExact(doctorTimingModel.to, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay >=
                                           DateTime.ParseExact(o.from, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay
                                           &&
                                           DateTime.ParseExact(doctorTimingModel.to, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay <=
                                           DateTime.ParseExact(o.to, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay
                                       )

                                       ||
                                       (
                                           DateTime.ParseExact(doctorTimingModel.from, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay <=
                                           DateTime.ParseExact(o.from, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay
                                           &&
                                           DateTime.ParseExact(doctorTimingModel.to, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay >=
                                           DateTime.ParseExact(o.to, "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay
                                       )

                                      )).ToList();

            if (alreadItems.Count >= 0)
            {
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != doctorTimingModel.doctorTimingsID)
            {
                return(BadRequest());
            }
            doctorTiming.doctorID        = doctorTimingModel.doctorID;
            doctorTiming.doctorTimingsID = id;
            doctorTiming.day             = doctorTimingModel.day;
            doctorTiming.active          = true;
            doctorTiming.md = DateTime.Now;
            doctorTiming.mb = doctorTimingModel.username;

            DateTime dateTimeFrom = DateTime.ParseExact(doctorTimingModel.from,
                                                        "hh:mm tt", CultureInfo.InvariantCulture);
            DateTime dateTimeTo = DateTime.ParseExact(doctorTimingModel.to,
                                                      "hh:mm tt", CultureInfo.InvariantCulture);

            doctorTiming.from = dateTimeFrom.TimeOfDay;
            doctorTiming.to   = dateTimeTo.TimeOfDay;

            db.Entry(doctorTiming).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DoctorTimingExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Beispiel #15
0
        public async Task <HttpResponseMessage> EditPatientMedication(long medicationID, PatientMedication_Custom model)
        {
            try
            {
                Medication medication = new Medication();
                if (medicationID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Medicine ID is not valid."
                    });
                    return(response);
                }
                if (model.frequency == null && model.frequency == "")
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Frequency is not valid."
                    });
                    return(response);
                }
                if (model.medicineName == null || model.medicineName == "")
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Medicine name is not valid. Only letters and numbers are allowed."
                    });
                    response.ReasonPhrase = "Medicine name is not valid.";
                    return(response);
                }
                if (model.patientId == 0 || model.patientId == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Patient ID is not valid."
                    });
                    return(response);
                }
                medication = db.Medications.Where(m => m.patientId == model.patientId && m.medicationID != medicationID && m.medicineName.Trim() == model.medicineName.Trim() && m.active == true).FirstOrDefault();
                if (medication != null)
                {
                    //conditionID = -1;
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Medicine already exists."
                    });
                    response.ReasonPhrase = "Medicine already exists.";
                    return(response);
                }

                medication = db.Medications.Where(m => m.medicationID == medicationID).FirstOrDefault();
                if (medication == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Medication record not found."
                    });
                    return(response);
                }

                medication.frequency       = model.frequency;
                medication.medicineName    = model.medicineName;
                medication.md              = System.DateTime.Now;
                medication.mb              = model.patientId.ToString();
                db.Entry(medication).State = EntityState.Modified;
                await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                return(ThrowError(ex, "EditPatientMedication in PatientMedicationController."));
            }


            response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                ID = medicationID, message = ""
            });
            return(response);
        }
Beispiel #16
0
        public async Task <DataAccess.CustomModels.UserModel> UniversalLogin(PatientLoginApiModel model, HttpRequestMessage request)
        {
            string[] lines = { "UniversalLogin", new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(model) };
            string   path  = System.IO.Path.Combine(@"C:\ApiLogs\", DateTime.Now.ToString("yyMMddHHmmssff"));

            // string fullSavePath = Path.Combine(("~/Content/ApiLogs/{0}.txt", DateTime.Now.ToString()));
            //  string fullSavePath = System.Web.HttpContext.Current.Server.MapPath(string.Format("~/Content/{0}.txt", DateTime.Now.ToString()));
            System.IO.File.WriteAllLines(path, lines);

            var userModel = new DataAccess.CustomModels.UserModel
            {
                Email = model.Email
            };

            if (!request.IsValidClient())
            {
                var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content      = new StringContent("Unauthorized, Client is not valid"),
                    ReasonPhrase = "Bad Request"
                };
                throw new HttpResponseException(resp);
            }


            //if (model.Role.ToLower() == "patient" || model.Role.ToLower() == "doctor")
            //{

            try
            {
                //    var id = headerValues.FirstOrDefault();
                // This doen't count login failures towards lockout only two factor authentication
                // To enable password failures to trigger lockout, change to shouldLockout: true
                var result = await SignInManager.PasswordSignInAsync(model.Email.Trim(), model.Password.Trim(), false, shouldLockout : false);

                if (result == SignInStatus.Success)
                {
                    /* if (model.offset != null)
                     * {
                     *    if (model.offset.Equals("330")) model.offset = "-330";
                     *    if (model.offset.Trim().Equals("")) model.offset = "-300";
                     * }
                     * else model.offset = "-300";*/


                    var userId     = UserManager.FindByName(model.Email.Trim())?.Id;
                    var roleFromDb = UserManager.GetRoles(userId).FirstOrDefault();

                    SwiftKareDBEntities db = new SwiftKareDBEntities();
                    if (roleFromDb.ToString().ToLower() == "doctor")
                    {
                        string iOSToken     = model.iOSToken;
                        string androidToken = model.andriodToken;

                        //update doctor table with  Tokens
                        Doctor doctor = db.Doctors.SingleOrDefault(o => o.userId == userId);
                        if (doctor != null)
                        {
                            if (model.offset != null)

                            {
                                if (model.offset.Trim() != "")
                                {
                                    if (doctor.timezoneoffset != model.offset.Replace("+", ""))
                                    {
                                        model.offset = model.offset.Replace("+", "");
                                        DataAccess.TimeZone tz = db.TimeZones.FirstOrDefault(t => t.zoneOffset == model.offset);
                                        if (tz != null)
                                        {
                                            doctor.timezone       = tz.zoneName;
                                            doctor.timezoneoffset = tz.zoneOffset;
                                        }
                                    }
                                }
                            }
                            if (iOSToken.Trim() != "" && iOSToken.Trim().ToLower() != "iostoken")
                            {
                                doctor.iOSToken = iOSToken;
                            }
                            if (androidToken.Trim() != "" && androidToken.Trim().ToLower() != "androidtoken")
                            {
                                doctor.AndroidToken = androidToken;
                            }
                            db.Entry(doctor).State = EntityState.Modified;
                            await db.SaveChangesAsync();
                        }
                        // var doctor = db.Doctors.SingleOrDefault(o => o.userId == userId);

                        if (doctor != null)
                        {
                            if (doctor.status == null || doctor.status == false)
                            {
                                userModel.Errors = new List <string>();
                                userModel.Errors.Add("Account review is in progress. You can login after approval.");
                            }
                            else
                            {
                                userModel.Id           = doctor.doctorID;
                                userModel.FirstName    = doctor.firstName;
                                userModel.LastName     = doctor.lastName;
                                userModel.Email        = doctor.email;
                                userModel.title        = doctor.title;
                                userModel.timeZone     = doctor.timezoneoffset;// timezoneoffset
                                userModel.userId       = doctor.userId;
                                userModel.role         = roleFromDb.ToString();
                                userModel.iOSToken     = doctor.iOSToken;
                                userModel.AndroidToken = doctor.AndroidToken;
                            }
                        }
                        else
                        {
                            userModel.Errors = new List <string>();
                            userModel.Errors.Add("User does not exist with this role.");
                        }
                    }
                    else if (roleFromDb.ToString().ToLower() == "patient")
                    {
                        string iOSToken     = model.iOSToken;
                        string androidToken = model.andriodToken;
                        //update patient table with  Tokens
                        Patient patient = db.Patients.SingleOrDefault(o => o.userId == userId);
                        if (model.offset != null)
                        {
                            if (model.offset.Trim() != "")
                            {
                                if (patient.timezoneoffset != model.offset.Replace("+", ""))
                                {
                                    model.offset = model.offset.Replace("+", "");
                                    DataAccess.TimeZone tz = db.TimeZones.FirstOrDefault(t => t.zoneOffset == model.offset);
                                    if (tz != null)
                                    {
                                        patient.timezone       = tz.zoneName;
                                        patient.timezoneoffset = tz.zoneOffset;
                                    }
                                }
                            }
                        }

                        if (iOSToken.Trim() != "" && iOSToken.Trim().ToLower() != "iostoken")
                        {
                            patient.iOSToken = iOSToken;
                        }
                        if (androidToken.Trim() != "" && androidToken.Trim().ToLower() != "androidtoken")
                        {
                            patient.AndroidToken = androidToken;
                        }
                        db.Entry(patient).State = EntityState.Modified;
                        await db.SaveChangesAsync();

                        if (patient != null)
                        {
                            userModel.Id        = patient.patientID;
                            userModel.FirstName = patient.firstName;
                            userModel.LastName  = patient.lastName;
                            //  userModel.userId = patient.userId;
                            userModel.title        = patient.title;
                            userModel.timeZone     = patient.timezoneoffset;
                            userModel.userId       = patient.userId;
                            userModel.role         = roleFromDb.ToString();
                            userModel.iOSToken     = patient.iOSToken;
                            userModel.AndroidToken = patient.AndroidToken;
                            userModel.pictureUrl   = System.Configuration.ConfigurationManager.AppSettings["profilePictureURL"].ToString();
                        }
                        else
                        {
                            userModel.Errors = new List <string>();
                            userModel.Errors.Add("User does not exist with this role.");
                        }
                    }
                }
                else if (result == SignInStatus.Failure)
                {
                    userModel.Errors = new List <string>();
                    userModel.Errors.Add("Login fail,Incorrect User name or Password.");
                }
                else if (result == SignInStatus.LockedOut)
                {
                    userModel.Errors = new List <string>();
                    userModel.Errors.Add("Account has been locked");
                }
                else if (result == SignInStatus.RequiresVerification)
                {
                    userModel.Errors = new List <string>();
                    userModel.Errors.Add("Account need to verify");
                }
            }

            catch (Exception ex)
            {
                userModel.Errors = new List <string>();
                userModel.Errors.Add("Exception Occur:" + ex.Message);
                //userModel.Errors.Add(model.Email + "," + model.Password + "," + model.offset + "," + model.iOSToken);
                return(userModel);

                /* throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                 *   {
                 *       //Content = new StringContent("An error occurred while posting in api/account/login, please try again or contact the administrator."),
                 *       Content = new StringContent(ex.Message),
                 *       ReasonPhrase = ex.Message
                 *
                 *   });
                 * }*/
            }
            //}
            //else
            //{
            //var resp = new HttpResponseMessage(HttpStatusCode.NotImplemented)
            //{
            //    Content = new StringContent("Role is undefined"),
            //    ReasonPhrase = "Undefined Role"
            //};
            //throw new HttpResponseException(resp);
            //}
            if (userModel.Id <= 0 && userModel.Errors == null)
            {
                userModel.Errors = new List <string>();
                userModel.Errors.Add("Unexpected error from api/login");
            }
            return(userModel);
        }
Beispiel #17
0
        public async Task <HttpResponseMessage> EditPatientCondition(long conditionID, PatientConditions_Custom model)
        {
            Condition condition = new Condition();

            try
            {
                if (conditionID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid condition ID."
                    });
                    return(response);
                }
                if (model.conditionName == null || model.conditionName == "" || !Regex.IsMatch(model.conditionName.Trim(), "^[0-9a-zA-Z ]+$"))
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid condition name.Only letters and numbers are allowed."
                    });
                    return(response);
                }
                if (model.patientID == null || model.patientID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid patient ID."
                    });
                    return(response);
                }
                //check for duplicate names
                condition = db.Conditions.Where(m => m.patientID == model.patientID && m.conditionID != conditionID && m.conditionName == model.conditionName.Trim() && m.active == true).FirstOrDefault();
                if (condition != null)
                {
                    //conditionID = -1;
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Condition name already exists."
                    });
                    response.ReasonPhrase = "Condition name already exists.";
                    return(response);
                }

                condition = db.Conditions.Where(m => m.conditionID == conditionID).FirstOrDefault();
                if (condition == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Condition not found."
                    });
                    return(response);
                }
                else
                {
                    condition.conditionName   = model.conditionName;
                    condition.md              = System.DateTime.Now;
                    condition.mb              = condition.patientID.ToString();
                    db.Entry(condition).State = EntityState.Modified;
                    await db.SaveChangesAsync();
                }
            }
            catch (Exception ex)
            {
                return(ThrowError(ex, "EditPatientCondition in PatientConditionController."));
            }

            response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                ID = conditionID, message = ""
            });
            return(response);
        }
Beispiel #18
0
        public async System.Threading.Tasks.Task <ActionResult> Create(FormCollection collection)
        {
            if (Session["LogedUserID"] != null)
            {
                ViewBag.successMessage = "";
                ViewBag.errorMessage   = "";

                var  id         = "";
                var  userid     = "";
                var  firstName  = "";
                var  lastName   = "";
                var  email      = "";
                var  password   = "";
                bool isAllValid = true;

                try
                {
                    var action = Request.Form["action"].ToString();
                    if (action == "create")
                    {
                        firstName = Request.Form["firstName"].ToString();
                        lastName  = Request.Form["lastName"].ToString();
                        email     = Request.Form["email"].ToString();
                        password  = Request.Form["password"].ToString();
                        if (!Regex.IsMatch(firstName, @"^[a-zA-Z\s]+$"))
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "Provide valid First Name";
                            var _existingdList = db.SP_SelectDoctor();
                            return(View(_existingdList));
                        }
                        if (!Regex.IsMatch(lastName, @"^[a-zA-Z\s]+$"))
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "Provide valid Last Name";
                            var _existingdList = db.SP_SelectDoctor();
                            return(View(_existingdList));
                        }
                        Utility util = new Utility();
                        if (!(util.IsValid(email)))
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "Provide valid Email Address";
                            var _existingdList = db.SP_SelectDoctor();
                            return(View(_existingdList));
                        }

                        //db.SP_AddDoctor(firstName, lastName, email, password, Session["LogedUserID"].ToString());
                        //db.SaveChanges();
                        var user = new ApplicationUser
                        {
                            UserName  = email,
                            Email     = email,
                            FirstName = firstName,
                            LastName  = lastName,
                        };
                        var result = await UserManager.CreateAsync(user, password);

                        if (result.Succeeded)
                        {
                            var doctor = new DataAccess.Doctor();
                            doctor.userId    = user.Id;
                            doctor.lastName  = user.LastName;
                            doctor.firstName = user.FirstName;
                            doctor.email     = user.Email;
                            doctor.cb        = Session["LogedUserID"].ToString();
                            doctor.active    = true;
                            doctor.status    = false;
                            db.Doctors.Add(doctor);
                            db.SaveChanges();

                            var userAssignRole = new UserAssignRoleModel();
                            userAssignRole.UserId = user.Id;//"8466ba63-b903-4d0a-8633-ce399ed1b542";//
                            userAssignRole.Role   = "Doctor";


                            var     strContent = JsonConvert.SerializeObject(userAssignRole);
                            var     response   = ApiConsumerHelper.PostData("api/Roles/AssignRole", strContent);
                            dynamic resultAdd  = JsonConvert.DeserializeObject(response);
                            ViewBag.successMessage = "Record has been saved successfully";
                            ViewBag.errorMessage   = "";
                        }
                        else
                        {
                            ViewBag.successMessage = "";
                            foreach (var error in result.Errors)
                            {
                                ViewBag.errorMessage = error;
                            }
                            var _existingdList = db.SP_SelectDoctor();
                            return(View(_existingdList));
                        }
                    }
                    if (action == "edit")
                    {
                        id       = Request.Form["id"].ToString();
                        userid   = Request.Form["userid"].ToString();
                        password = Request.Form["password"].ToString();
                        string token = await UserManager.GeneratePasswordResetTokenAsync(userid);

                        //var firstName = Request.Form["firstName"].ToString();
                        //var lastName = Request.Form["lastName"].ToString();
                        //var email = Request.Form["email"].ToString();
                        //db.sp_ResetDoctorPassword(Convert.ToInt64(id), password, Session["LogedUserID"].ToString(), System.DateTime.Now);
                        //db.SaveChanges();
                        var result = await UserManager.ResetPasswordAsync(userid, token, password);

                        if (result.Succeeded)
                        {
                            ViewBag.successMessage = "Record has been saved successfully";
                            ViewBag.errorMessage   = "";
                        }
                        else
                        {
                            ViewBag.successMessage = "";
                            foreach (var error in result.Errors)
                            {
                                ViewBag.errorMessage = error;
                            }
                            var _existingdList = db.SP_SelectDoctor();
                            return(View(_existingdList));
                        }
                    }
                    if (action == "delete")
                    {
                        id     = Request.Form["id"].ToString();
                        userid = Request.Form["userid"].ToString();
                        Doctor doc = db.Doctors.Where(a => a.userId == userid).FirstOrDefault();
                        if (doc != null)
                        {
                            doc.active          = false;
                            doc.mb              = Session["LogedUserID"].ToString();
                            doc.md              = DateTime.Now;
                            db.Entry(doc).State = EntityState.Modified;
                            db.SaveChanges();
                            ViewBag.successMessage = "Record has been deleted successfully";
                            ViewBag.errorMessage   = "";
                        }
                        else
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "Doctor not found.";
                        }
                    }


                    var _existingdoctorsList = db.SP_SelectDoctor();
                    return(View(_existingdoctorsList));
                }
                catch (Exception ex)
                {
                    ViewBag.errorMessage = "Error occurred while processing your request.";
                    return(View());
                }
            }
            else
            {
                return(RedirectToAction("AdminLogin", "Account"));
            }
        }
Beispiel #19
0
        public HttpResponseMessage GetPatientDoseSpotUrl(long patientId)
        {
            try
            {
                //Search if patient contains doseSpot Id
                var oPatientInfo = db.Patients.FirstOrDefault(x => x.patientID == patientId);

                int?DoseSpotPatientId = null;
                if (oPatientInfo != null)
                {
                    var oDoseSpotPatientEntry = new DoseSpotPatientEntry
                    {
                        PatientId   = DoseSpotPatientId,
                        FirstName   = oPatientInfo.firstName,
                        LastName    = oPatientInfo.lastName,
                        MiddleName  = "",
                        Address1    = oPatientInfo.address1,
                        Address2    = oPatientInfo.address2,
                        City        = oPatientInfo.city,
                        State       = oPatientInfo.state,
                        ZipCode     = oPatientInfo.zip,
                        Gender      = oPatientInfo.gender,
                        Phone       = oPatientInfo.cellPhone,
                        DateOfBirth = oPatientInfo.dob.Value,
                        PharmacyId  = oPatientInfo.pharmacyid
                    };

                    if (string.IsNullOrEmpty(oPatientInfo.DoseSpotPatientId))
                    {
                        var oRet = DoseSpotHelper.RegisterPatientWithDoseSpot(oDoseSpotPatientEntry);

                        int DoseSpotPatId;
                        int.TryParse(oRet, out DoseSpotPatId);

                        if (DoseSpotPatId != 0)
                        {
                            oPatientInfo.DoseSpotPatientId = oRet;

                            db.Entry(oPatientInfo).State = EntityState.Modified;
                            db.SaveChanges();
                        }

                        oDoseSpotPatientEntry.PatientId = DoseSpotPatId;
                    }
                    else
                    {
                        oDoseSpotPatientEntry.PatientId = Convert.ToInt32(oPatientInfo.DoseSpotPatientId);
                    }

                    //Register Patient
                    var cFinalUrl = DoseSpotHelper.GetEPrescriptionUrl(oDoseSpotPatientEntry);
                    return(Request.CreateResponse(HttpStatusCode.OK, cFinalUrl));
                }

                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "This patient does not exists"));
            }
            catch (Exception ex)
            {
                //return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
                return(ThrowError(ex, "GetPatientDoseSpotUrl in DoseSpotController"));
            }
        }
Beispiel #20
0
        public ActionResult Create(FormCollection collection)
        {
            var  rovname = "";
            long rovid;

            ViewBag.successMessage = "";
            ViewBag.errorMessage   = "";
            try
            {
                var action = Request.Form["action"].ToString();
                if (action == "create")
                {
                    rovname = Request.Form["rovname"].ToString();
                    var obj_rov = (
                        from p in db.ROVs
                        where (p.name == rovname && p.active == true)
                        select p
                        ).FirstOrDefault();
                    if (obj_rov != null)
                    {
                        ViewBag.successMessage = "";
                        ViewBag.errorMessage   = "Reason of Visit already exists";
                    }
                    if (obj_rov == null)
                    {
                        ROV dbrov = new ROV();
                        dbrov.name   = rovname;
                        dbrov.cd     = DateTime.Now;
                        dbrov.cb     = SessionHandler.UserId;
                        dbrov.active = true;
                        db.ROVs.Add(dbrov);
                        db.SaveChanges();
                        ViewBag.successMessage = "Record has been saved successfully";
                        ViewBag.errorMessage   = "";
                    }
                }
                if (action == "edit")
                {
                    rovid   = Convert.ToInt32(Request.Form["id"].ToString());
                    rovname = Request.Form["rovname"].ToString();
                    ROV dbrov = new ROV();
                    dbrov                 = db.ROVs.Where(r => r.rovID == rovid).FirstOrDefault();
                    dbrov.name            = rovname;
                    dbrov.md              = DateTime.Now;
                    dbrov.mb              = SessionHandler.UserId;
                    db.Entry(dbrov).State = EntityState.Modified;
                    db.SaveChanges();
                    ViewBag.successMessage = "Record has been saved successfully";
                    ViewBag.errorMessage   = "";
                }
                if (action == "delete")
                {
                    rovid = Convert.ToInt32(Request.Form["id"].ToString());
                    ROV dbrov = new ROV();
                    dbrov                 = db.ROVs.Where(r => r.rovID == rovid).FirstOrDefault();
                    dbrov.active          = false;
                    db.Entry(dbrov).State = EntityState.Modified;
                    db.SaveChanges();
                    ViewBag.successMessage = "Record has been deleted successfully";
                    ViewBag.errorMessage   = "";
                }
                var rov = db.ROVs.Where(r => r.active == true).ToList();
                return(View(rov));
            }
            catch (Exception ex)
            {
                ViewBag.errorMessage = "Error occurred while processing your request.";
                var _rov = db.ROVs.Where(r => r.active == true).ToList();
                return(View(_rov));
            }
        }
        public async Task <HttpResponseMessage> EditPatientAllergy(long allergyID, PatientAllergies_Custom model)
        {
            PatientAllergy pallergy = new PatientAllergy();

            try
            {
                if (model.allergyName == "" || model.allergyName == null || !Regex.IsMatch(model.allergyName.Trim(), "^[0-9a-zA-Z ]+$"))
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid allergy name.Only letters and numbers are allowed."
                    });
                    return(response);
                }
                if (model.patientID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid patient ID."
                    });
                    return(response);
                }
                if (allergyID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid allergies ID."
                    });
                    return(response);
                }
                pallergy = db.PatientAllergies.Where(all => all.patientID == model.patientID && all.allergyName.Trim() == model.allergyName.Trim() && all.allergiesID != allergyID && all.active == true).FirstOrDefault();
                if (pallergy != null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Allergy already exists."
                    });
                    response.ReasonPhrase = "Allergy already exists";
                    return(response);
                }
                pallergy = db.PatientAllergies.Where(m => m.allergiesID == allergyID).FirstOrDefault();
                if (pallergy == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Allergy not found."
                    });
                    return(response);
                }


                pallergy.allergyName     = model.allergyName;
                pallergy.severity        = model.severity;
                pallergy.reaction        = model.reaction;
                pallergy.md              = System.DateTime.Now;
                pallergy.mb              = pallergy.patientID.ToString();
                db.Entry(pallergy).State = EntityState.Modified;
                await db.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                return(ThrowError(ex, "EditPatientAllergy in PatientAllergiesController."));
            }


            response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                ID = allergyID, message = ""
            });
            return(response);
        }
Beispiel #22
0
        public async Task <HttpResponseMessage> EditPatientFile(long fileID, EditFilesModel model)
        {
            UserFile patFile = new UserFile();

            try
            {
                if (fileID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid file ID."
                    });
                    return(response);
                }
                if (model.FileName == null || model.FileName == "" || !Regex.IsMatch(model.FileName.Trim(), "^[0-9a-zA-Z ]+$"))
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid file name. Only letters and numbers are allowed."
                    });
                    return(response);
                }
                if (model.patientID == null || model.patientID == 0)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Invalid patient ID."
                    });
                    return(response);
                }

                if (model.fileContent == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "File is empty. "
                    });
                    return(response);
                }
                if (model.documentType == null || model.documentType == "")
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "Please provide document type. "
                    });
                    return(response);
                }

                //check for duplicate names
                patFile = db.UserFiles.Where(m => m.fileID != fileID && m.patientID == model.patientID && m.FileName == model.FileName.Trim() && m.active == true).FirstOrDefault();
                if (patFile != null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "File name already taken."
                    });
                    return(response);
                }

                patFile = db.UserFiles.Where(m => m.fileID == fileID).FirstOrDefault();
                if (patFile == null)
                {
                    response = Request.CreateResponse(HttpStatusCode.BadRequest, new ApiResultModel {
                        ID = 0, message = "File not found."
                    });
                    return(response);
                }
                else
                {
                    patFile.active          = true;
                    patFile.FileName        = model.FileName;
                    patFile.md              = System.DateTime.Now;
                    patFile.fileContent     = model.fileContent;
                    patFile.documentType    = model.documentType;
                    patFile.mb              = model.patientID.ToString();
                    db.Entry(patFile).State = EntityState.Modified;
                    await db.SaveChangesAsync();

                    response = Request.CreateResponse(HttpStatusCode.OK, new ApiResultModel {
                        ID = fileID, message = ""
                    });
                    return(response);
                }
            }
            catch (Exception ex)
            {
                return(ThrowError(ex, "EditPatientCondition in PatientFileController."));
            }
        }
Beispiel #23
0
        public async System.Threading.Tasks.Task <ActionResult> Create(FormCollection collection)
        {
            if (Session["LogedUserID"] != null)
            {
                ViewBag.successMessage = "";
                ViewBag.errorMessage   = "";
                var id        = "";
                var firstName = "";
                var lastName  = "";
                var email     = "";
                var password  = "";
                var roleID    = "";


                try
                {
                    var action = Request.Form["action"].ToString();
                    if (action == "create")
                    {
                        firstName = Request.Form["firstname"].ToString();
                        lastName  = Request.Form["lastname"].ToString();
                        email     = Request.Form["email"].ToString();
                        password  = Request.Form["password"].ToString();
                        //roleID = Request.Form["sltRole"].ToString();
                        var roles = db.AspNetRoles.ToList();
                        //if (roleID == "")
                        //{
                        //    ViewBag.successMessage = "";
                        //    ViewBag.errorMessage = "Select valid Role";
                        //    var _existingadminList = db.SP_SelectAdmin();
                        //    //var roles = db.Roles
                        //    //  .Where(a => a.active == true).ToList();

                        //    ViewBag.Roles = roles;
                        //    return View(_existingadminList);
                        //}
                        if (!Regex.IsMatch(firstName, @"^[a-zA-Z\s]+$"))
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "Provide valid First Name";
                            var _existingadminList = db.SP_SelectAdmin();
                            //var roles = db.Roles
                            //.Where(a => a.active == true).ToList();

                            ViewBag.Roles = roles;
                            return(View(_existingadminList));
                        }
                        if (!Regex.IsMatch(lastName, @"^[a-zA-Z\s]+$"))
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "Provide valid Last Name";
                            var _existingadminList = db.SP_SelectAdmin();
                            //var roles = db.Roles
                            //.Where(a => a.active == true).ToList();
                            ViewBag.Roles = roles;

                            return(View(_existingadminList));
                        }
                        Utility util = new Utility();
                        if (!(util.IsValid(email)))
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "Provide valid Email Address";
                            var _existingadminList = db.SP_SelectAdmin();
                            //var roles = db.Roles
                            //.Where(a => a.active == true).ToList();

                            ViewBag.Roles = roles;
                            return(View(_existingadminList));
                        }
                        var checkemail = (
                            from p in db.AdminUsers
                            where (p.email == email && p.active == true)
                            select p
                            ).FirstOrDefault();
                        if (checkemail == null)
                        {
                            var user = new ApplicationUser
                            {
                                UserName  = email,
                                Email     = email,
                                FirstName = firstName,
                                LastName  = lastName,
                            };
                            var result = await UserManager.CreateAsync(user, password);

                            if (result.Succeeded)
                            {
                                db.SP_AddAdmin(firstName, lastName, email, user.Id, Session["LogedUserID"].ToString());
                                db.SaveChanges();

                                var userAssignRole = new UserAssignRoleModel();
                                userAssignRole.UserId = user.Id;//"8466ba63-b903-4d0a-8633-ce399ed1b542";//
                                userAssignRole.Role   = "Admin";
                                var     strContent = JsonConvert.SerializeObject(userAssignRole);
                                var     response   = ApiConsumerHelper.PostData("api/Roles/AssignRole", strContent);
                                dynamic resultAdd  = JsonConvert.DeserializeObject(response);

                                ViewBag.successMessage = "Record has been saved successfully";
                                ViewBag.errorMessage   = "";
                            }
                            else
                            {
                                ViewBag.successMessage = "";
                                foreach (var error in result.Errors)
                                {
                                    ViewBag.errorMessage = error;
                                }

                                var _existingadminList = db.SP_SelectAdmin();
                                return(View(_existingadminList));
                            }
                        }
                        else
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "User with this Email Address already exists";
                            var _existingadminList = db.SP_SelectAdmin();
                            //var roles = db.Roles
                            //.Where(a => a.active == true).ToList();

                            ViewBag.Roles = roles;
                            return(View(_existingadminList));
                        }
                    }
                    if (action == "edit")
                    {
                        id        = Request.Form["id"].ToString();
                        firstName = Request.Form["firstName"].ToString();
                        lastName  = Request.Form["lastName"].ToString();
                        email     = Request.Form["email"].ToString();
                        password  = Request.Form["password"].ToString();
                        //roleID = Request.Form["sltRole"].ToString();
                        var rroles = db.AspNetRoles.ToList();
                        //if (roleID == "")
                        //{
                        //    ViewBag.successMessage = "";
                        //    ViewBag.errorMessage = "Select valid Role";
                        //    var _existingadminList = db.SP_SelectAdmin();
                        //    //var roles = db.Roles
                        //    //  .Where(a => a.active == true).ToList();

                        //    ViewBag.Roles = rroles;
                        //    return View(_existingadminList);
                        //}
                        if (!Regex.IsMatch(firstName, @"^[a-zA-Z\s]+$"))
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "Provide valid First Name";
                            var _existingadminList = db.SP_SelectAdmin();
                            //var roles = db.Roles
                            //  .Where(a => a.active == true).ToList();

                            ViewBag.Roles = rroles;
                            return(View(_existingadminList));
                        }
                        if (!Regex.IsMatch(lastName, @"^[a-zA-Z\s]+$"))
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "Provide valid Last Name";
                            var _existingadminList = db.SP_SelectAdmin();
                            // var roles = db.Roles
                            //.Where(a => a.active == true).ToList();

                            ViewBag.Roles = rroles;
                            return(View(_existingadminList));
                        }
                        Utility util = new Utility();
                        if (!(util.IsValid(email)))
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "Provide valid Email Address";
                            var _existingadminList = db.SP_SelectAdmin();
                            // var roles = db.Roles
                            //.Where(a => a.active == true).ToList();

                            ViewBag.Roles = rroles;
                            return(View(_existingadminList));
                        }


                        var checkemail = (
                            from p in db.AspNetUsers
                            where (p.Email == email && p.Id != id)
                            select p
                            ).FirstOrDefault();
                        if (checkemail == null)
                        {
                            string token = await UserManager.GeneratePasswordResetTokenAsync(id);

                            var result = await UserManager.ResetPasswordAsync(id, token, password);

                            if (result.Succeeded)
                            {
                                AdminUser adminUser = db.AdminUsers.Where(a => a.userId == id).FirstOrDefault();
                                if (adminUser != null)
                                {
                                    //Update AdminUsers table
                                    adminUser.lastName  = lastName;
                                    adminUser.FirstName = firstName;
                                    adminUser.email     = email;
                                    adminUser.mb        = Session["LogedUserID"].ToString();
                                    adminUser.md        = DateTime.Now;
                                    db.AdminUsers.Add(adminUser);
                                    db.Entry(adminUser).State = EntityState.Modified;
                                }
                                //Update AspNetUsers table
                                AspNetUser aspnetUser = await db.AspNetUsers.FindAsync(id);

                                if (aspnetUser == null)
                                {
                                    ViewBag.successMessage = "";
                                    ViewBag.errorMessage   = "Admin user not found.";
                                    return(View());
                                }
                                aspnetUser.LastName  = lastName;
                                aspnetUser.FirstName = firstName;
                                aspnetUser.Email     = email;
                                db.AspNetUsers.Add(aspnetUser);
                                db.Entry(aspnetUser).State = EntityState.Modified;

                                await db.SaveChangesAsync();

                                ViewBag.successMessage = "Record has been saved successfully";
                                ViewBag.errorMessage   = "";
                            }
                            else
                            {
                                ViewBag.successMessage = "";
                                foreach (var error in result.Errors)
                                {
                                    ViewBag.errorMessage = error;
                                }
                                var _existingadminList = db.SP_SelectAdmin();
                                return(View(_existingadminList));
                            }
                        }
                        else
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "User with this Email Address already exists";
                            var _existingadminList = db.SP_SelectAdmin();
                            //var roles = db.Roles
                            //.Where(a => a.active == true).ToList();

                            ViewBag.Roles = rroles;
                            return(View(_existingadminList));
                        }
                    }
                    if (action == "delete")
                    {
                        id = Request.Form["id"].ToString();
                        var       userid    = Request.Form["userid"].ToString();
                        AdminUser adminUser = db.AdminUsers.Where(a => a.userId == userid).FirstOrDefault();
                        if (adminUser != null)
                        {
                            //Update AdminUsers table
                            adminUser.active          = false;
                            adminUser.mb              = Session["LogedUserID"].ToString();
                            adminUser.md              = DateTime.Now;
                            db.Entry(adminUser).State = EntityState.Modified;
                            db.SaveChanges();
                            ViewBag.successMessage = "Record has been deleted successfully";
                            ViewBag.errorMessage   = "";
                        }
                        //db.sp_DeleteAdmin(Convert.ToInt64(id), Session["LogedUserID"].ToString(), System.DateTime.Now);
                        //AspNetUser admin = db.AspNetUsers.Find(userid);

                        //db.AspNetUsers.Remove(admin);

                        //db.AspNetUsers.Remove(admin);
                        //db.SaveChanges();
                        else
                        {
                            ViewBag.successMessage = "";
                            ViewBag.errorMessage   = "Admin user not found.";
                        }
                    }
                    //Send Email//


                    //Send Email//
                    var __existingadminList = db.SP_SelectAdmin();
                    // var _roles = db.Roles
                    //.Where(a => a.active == true).ToList();
                    var _roles = db.AspNetRoles.ToList();
                    ViewBag.Roles = _roles;
                    return(View(__existingadminList));
                }
                catch (Exception ex)
                {
                    ViewBag.errorMessage = "Error occurred while processing your request.";
                    var _existingadminList = db.SP_SelectAdmin();
                    var roles = db.AspNetRoles.ToList();
                    ViewBag.Roles = roles;
                    return(View(_existingadminList));
                }
            }
            else
            {
                return(RedirectToAction("AdminLogin", "Account"));
            }
        }