Setting condition for action method - c#

I have a table used to track a patient appointments in a clinic.
Check In and out are used to track his presence.
I need to be able to create an appointment only if he had checked out
public class Appointment
{
[Key]
public virtual int ID { get; set; }
[Required]
[Display(Name = "Case Number")]
public virtual string MRN { get; set; }
[Required]
[Display(Name = "Department")]
public virtual int DepID { get; set; }
[Required]
[Display(Name = "Check IN")]
public virtual DateTime Check_IN { get; set; }
[Display(Name = "Check Out")]
public virtual DateTime? Check_OUT { get; set; }
}
I created this method inside the controller to check whether or not he checked out.
private bool CheckedOut (string MRN)
{
return _context.Appointments.Any(a => a.MRN == MRN && !a.Check_Out.HasValue);
}
And my Create action method.
public async Task<IActionResult> Create(string MRN, Appointment appointment)
{
ViewData["MRN"] = MRN;
if (CheckedOut(appointment.MRN))
{
_context.Add(appointment);
await _context.SaveChangesAsync();
return RedirectToAction("Index", "Patients");
}
return View();
}
But the appointment is still created even if the patient has one which he hadn't checked out from.
Any ideas?

Does it create an appointment if the User has checked out?
Because to me it looks like you are checking if any open appointments exist and returning true on that.
should be:
return !_context.Appointments.Any(a => a.MRN == MRN && !a.Check_Out.HasValue);

the problem has to be you LINQ query.
i would suggest that you extract variables and set a breakpoint to see what is going on:
private bool CheckedOut (string MRN)
{
var mrn = MRN;
var hasCheckedOut = a.Check_Out.HasValue;
return _context.Appointments.Any(a => a.MRN == mrn && !hasCheckedOut);
}

Related

pass model data between razor pages

I try pass model data between two Razor pages, data is not string or bool or int
data that i want pass to second page is a model,
i do taht with this way,
public class AskLibrarian
{
public int Id { get; set; }
public string FullName { get; set; }
public string Subject { get; set; }
public string Email { get; set; }
public string Text { get; set; }
public string UserIp { get; set; }
public DateTime CreateDate { get; set; }
public bool ReadIt { get; set; }
public bool Answer { get; set; }
public string reciptCode { get; set; }
}
And on Get method pass data with this way:
[BindProperty]
public AskLibrarian AskLibrarian { get; set; }
public async Task<IActionResult> OnPostQuestionAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
AskLibrarian.Answer = false;
AskLibrarian.CreateDate = DateTime.Now;
AskLibrarian.ReadIt = false;
string userIp = $"{ HttpContext.Connection.RemoteIpAddress}";
if (string.IsNullOrEmpty(userIp))
{
userIp = "127.0.0.1";
}
AskLibrarian.UserIp = userIp;
string rndNuber = Business.RandomNumberForQuestion.randCode;
AskLibrarian.reciptCode = rndNuber;
await _emailSenderService.SendEmailAsync(AskLibrarian.Email, AskLibrarian.FullName, rndNuber);
_context.AskLibrarians.Add(AskLibrarian);
await _context.SaveChangesAsync();
Message = "your message sended";
//return RedirectToPage("/Subfolder/Index", new { SFId = 7 });
return RedirectToPage("/Subfolder/AskLibrarianCode", new { asklib = AskLibrarian });
}
In post method in second page, like to get data on this way:
public void OnGet(Model.AskLibrarian asklib)
{
askLibrarianVM = new AskLibrarianVM
{
Answered = false,
CreateDate = asklib.CreateDate,
LastUpdate = asklib.CreateDate,
RandomeCode = asklib.reciptCode,
Status = false,
};
}
But asklib is empty ,I set a breakpoint at end of Get method and I sow that asklib if filled with valid values but in post method when i try to get data, asklib is empty
what is my mistake
The simple answer was :
return RedirectToPage("/Subfolder/AskLibrarianCode", AskLibrarian );
My mistake was
... new{asklib = AskLibrarian});
After more than two hours
The lowest friction way is to return View("SomeViewForTheModel", AskLibrarian) and do your thing with a completely different view. Your second page controller action really isn't doing anything.
Otherwise, you'll have to save the ID associated with your AskLibrarian object, presumably in a database, and then look it up on the second page either by putting the ID in the URL path (be sure to validate the user should see it!), or by looking up in the database whatever is owned by the user.

Is there any other Method to create Login/Signup form without session in MVC?

I am creating my Login form in my project as same from Session, but now in this project i want to create Login form without using any session. Anyone here to guide me?
There is my Work using Session,
This is Controller of LogIn:
public class LoginController : Controller
{
IMEI_WEB_MVC.Connections.IMEI_DBEntities imeidb = new Connections.IMEI_DBEntities();
Functions func = new Functions();
// GET: Login
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Autherize(log_variable logvariable_model)
{
log_variable lgv = new Models.log_variable();
string pwd = func.security(logvariable_model.usr_pwd);
var userDetails = imeidb.new_usr.Where(x => x.usr_nam == logvariable_model.usr_nam && x.usr_pwd == pwd).FirstOrDefault();
if (userDetails == null)
{
logvariable_model.LogErrorMessage = " Invalid Name or Password";
return View("Index", logvariable_model);
}
else
{
Session["usr_id"] = userDetails.usr_id;
Session["com_id"] = logvariable_model.com_id;
Session["br_id"] = logvariable_model.br_id;
//lgv.usr_id = userDetails.usr_id;
//lgv.com_id = logvariable_model.com_id;
//lgv.br_id = logvariable_model.br_id;
return RedirectToAction("index", "m_dpt");
This is my Model:
public class log_variable
{
[Required(ErrorMessage = "User Name cannot be blank")]
[DisplayName("Name")]
public string usr_nam { get; set; }
[Required(ErrorMessage = "Password cannot be Blank")]
[DataType(DataType.Password)]
[DisplayName("Password")]
public string usr_pwd { get; set; }
public int usr_id { get; set; }
[Required(ErrorMessage = "Company ID cannot be blank")]
[MaxLength(2)]
[DisplayName("Company_ID")]
public string com_id { get; set; }
[Required(ErrorMessage ="Branch ID cannot be blank")]
[MaxLength(3)]
[DisplayName("BRANCH_ID")]
public string br_id { get; set; }
public string LogErrorMessage { get; set; }
}
AFAIK, to control this kind of user's access, you have basically only two options:
You can manage when they logging in and when they are logging out (sessions), OR
You can give them a ticket and they have to pass it to your application (Security token, like JWT).
(If anybody knows anotehr method to do it, please, tell me)
Ask your boss if it's about storing data in a in-memory session, or to avoid cookis, bc there are ways to do that with sessions. Take a look at
this (sessions in db) and this (cookieless sessions)
If you find any other way, please, tell us.
Good luck.

Compare Multiple Variables to Same Value Efficiently

I'm looking for alternative methods in C# to compare multiple variables to the same value, and I would optimally like for them to share the same subsequent instructions based on their conditional results.
For example, I have the following code:
string DOBResultsError = VerifySingleRecordReturned(DOBResults, APIParameters, 1);
string NameResultsError = VerifySingleRecordReturned(NameResults, APIParameters, 2);
if (DOBResultsError != string.Empty)
{
PatientRecordUpdate(DOBResults, APIParameters.PatientID, DOBResultsError);
}
else if (NameResultsError != string.Empty)
{
PatientRecordUpdate(NameResults, APIParameters.PatientID, NameResultsError);
}
I'm having to do explicitly instruct PatientRecordUpdate to be performed for each variable being compared to String.Null.
What I would like to have happen is something like the following:
if (DOBResultsError != string.Empty || NameResultsError != string.Empty)
{
//whichever isn't an empty string use to perform PatientRecordUpdate()
}
Is such syntax possible in C#?
Employing the switch keyword won't make a difference because even though I can have multiple circumstances resulting in the same instructions being performed, if I need to use the one of the comparison variables I would still need to explicitly state the code using the variable for each possible case.
string DOBResultsError = VerifySingleRecordReturned(DOBResults, APIParameters, 1);
string NameResultsError = VerifySingleRecordReturned(NameResults, APIParameters, 2);
string SSNResultsError = VerifySingleRecordReturned(SSNResults, APIParameters, 3);
string EmptyString = String.Empty;
switch (EmptyString)
{
case DOBResultsError:
case SSNResultsError: //can't use SSNResultsError with PatientRecordUpdate() without stating PatientRecordUpdate() again
PatientRecordUpdate(DOBResults, APIParameters.PatientID, DOBResultsError);
case NameResultsError:
PatientRecordUpdate(NameResults, APIParameters.PatientID, NameResultsError);
}
Any help appreciated.
UPDATE: Requested additional info
This is what VerifySingleRecordReturnedFrom() does. It checks a few conditions that would cause errors in the program and writes an error message to be added on the record in an SQL DB.
public static string VerifySingleRecordReturnedFrom(List<PatientList3> ReturnedPatientList, AutoPatientLookup APIParameters, int SearchCriteria = 0)
{
string ErrorMessage = String.Empty;
if (ReturnedPatientList.Count == 0)
{
//Error Message for Dob
if (SearchCriteria == 1)
{
ErrorMessage = string.Format("No patients were returned from for DOB ....");
return ErrorMessage;
}
//Error Message for Name
else if (SearchCriteria == 2)
{
ErrorMessage = string.Format("No patients were returned from for patient name ....");
return ErrorMessage;
}
//Error Message for PracticePatientNumber
else if (SearchCriteria == 3)
{
ErrorMessage = string.Format("No patients were returned from for PracticePatientNumber...");
return ErrorMessage;
}
}
// more than one patient in common results list from AttemptToMatchPatientsByDemographics() or results using PatientNumber
else if (ReturnedPatientList.Count() > 1)
{
switch(SearchCriteria)
{
case 1:
case 2:
ErrorMessage = String.Format("{0} number of patients were returned...");
break;
//More than one patient returned from for any given PracticePatientNumber
case 3:
ErrorMessage = String.Format("{0} number of patients were returned....");
break;
}
return ErrorMessage;
}
//No error in number of results from
return ErrorMessage;
}
All of the results(DOB/Name/SSN) types are List objects of the following PatientList3 object (I've included sub classes):
public class PatientList3
{
public Patient PatientNameID { get; set; }
public string PatientNumber { get; set; }
public string ChartNumber { get; set; }
public Gender2 Gender { get; set; }
public string DOB { get; set; }
public string PhoneNumber { get; set; }
public string SSN { get; set; }
}
public class Patient
{
public int ID { get; set; }
public PtName Name { get; set; }
}
public class PtName
{
public string First { get; set; }
public string Middle { get; set; }
public string Last { get; set; }
public string Suffix { get; set; }
public string Full { get; set; }
public string Preferred { get; set; }
}
public class Gender2
{
public string LookupType { get; set; }
public string Code { get; set; }
public string Description { get; set; }
public int Order { get; set; }
public bool Active { get; set; }
public List<AlternateCodes> AlternateCodes { get; set; } //Not important, didn't include AlternativeCodes class
}
This is the class of APIParameters:
public class AutoPatientLookup
{
public string DOB { get; set; }
public string Gender { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int? PatientNumber { get; set; }
public string SSN { get; set; }
public int PracticeID { get; set; }
public int PatientID { get; set; }
}
Consider leveraging a base result type for some generic logic like this:
// assuming both results inherit from or implement some base type...
List<ResultBase> results = new List<ResultBase>()
{
DOBResults,
NameResults
}; // order matters since it's used for the parameter index
// Note that a class would be a much better option than a tuple here.
// Select will verify each result but only upon request until FirstOrDefault is fulfilled
Tuple<ResultBase, string> firstResultError = results
.Select((result, index) => new Tuple<ResultBase, string>(
result,
VerifySingleRecordReturned(result, APIParameters, index + 1)))
.FirstOrDefault(result => !string.IsNullOrEmpty(result.Item2 /* Error message */));
// If there was at least one error, call the original patient update record
// with the associated information.
if (firstResultError != null)
{
PatientRecordUpdate(
firstResultError.Item1 /* Failed result */,
APIParameters.PatientID,
firstResultError.Item2 /* Error message for that result */);
}
You'll want to use a new class instead of a tuple for maintainability reasons, but besides that this should get you started in a good direction.

How to insert data from MS Access to SQL after checking whether the data exists or not in the database using Entity Framework

Hopefully, the question header is clear enough to tell that I'm trying to read an Access file and upload the data to the database but checking at first whether the data already exists or not in the database.
I receive a daily report from a third-party company in Access file. I'm trying to create a windows service that will check for the file every morning, and if the new file exist, then it'll read and upload the data to the database. I'm trying to use Entity Framework. I read the article on Navigation Property, but I'm still confused on that; I never used navigation property before. Here are my models:
[Table("ClaimsTable")]
public partial class ClaimsTable
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int ClaimsID { get; set; }
public string EOPAID { get; set; }
public string AuthID { get; set; }
public string PAStatus { get; set; }
public string UserName { get; set; }
[DataType(DataType.Date)]
public DateTime EffectiveDate { get; set; }
[DataType(DataType.Date)]
public DateTime EndDate { get; set; }
public string RecordType { get; set; }
public int RxID { get; set; }
public int MemberID { get; set; }
public int PrescriberID { get; set; }
public string EditNumber { get; set; }
public string OriginSource { get; set; }
public string OriginMethod { get; set; }
/*
[ForeignKey("RxID")]
public virtual RxTable Prescription { get; set; }
[ForeignKey("MemberID")]
public virtual MembersTable Member { get; set; }
[ForeignKey("PrescriberID")]
public virtual PrescribersTable Prescriber { get; set; }
*/
}
...
[Table("MembersTable")]
public partial class MembersTable
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int MemberID { get; set; }
[DataType(DataType.Date), Display(Name= "Date of Birth"), DisplayFormat(DataFormatString="{0:mm/dd/yyyy}", ApplyFormatInEditMode=true)]
public DateTime DateofBirth { get; set; }
public string CardholderID { get; set; }
public string MemberFirstName { get; set; }
public string MemberLastName { get; set; }
//public virtual ICollection<AddressTable> Address { get; set; }
}
...
[Table("PrescribersTable")]
public partial class PrescribersTable
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int PrescriberID { get; set; }
public string NPI { get; set; }
public string PrescriberFirstName { get; set; }
public string PrescriberLastName { get; set; }
public string PhysicianType { get; set; }
//public ICollection<AddressTable> Address { get; set; }
}
....
using(OleDbConnection conn = new OleDbConnection(strDSN))
{
OleDbDataReader reader = null;
OleDbCommand command = new OleDbCommand("Select * from table", conn);
try
{
conn.Open();
}
catch(OleDbException o)
{
return o.Message;
}
reader = command.ExecuteReader();
List<ClaimsTable> Claim = new List<ClaimsTable>();
List<PrescribersTable> PrescriberInDB = new List<PrescribersTable>();
List<MembersTable> MembersInDB = new List<MembersTable>();
while(reader.Read())
{
PrescriberInDB = context.Prescribers.ToList();
MembersInDB = context.Members.ToList();
//CREATE LOCAL VARIABLE
string recordType = //check if the member and the prescriber exist in the database
int prescriberID = 0;
int prodID = 0;
int memberID = 0;
int drugID = 0;
int RxID = 0;
int claimID = 0;
//check if the member and the prescriber exist in the object before inserted into the database.
//the data will be uploaded to the database in bulk
//int newPrescriberID = Prescriber.Where(x => x.PrescriberFirstName == reader["Prescriber First Name"] && x.PrescriberLastName == reader["Prescriber Last Name"] && x.NPI == reader["Prescribing Physician"]).Select(x => x.PrescriberID).FirstOrDefault();
//int newMemberID = Member.Where(x => x.MemberFirstName == reader["Member First Name"] && x.MemberLastName == reader["Member Last Name"] && x.CardholderID == reader["CardhHolder"]).Select(x => x.MemberID).FirstOrDefault();
//insert the data if it doesn't exist
if(!PresciberExist(prescriberFirstName, prescriberLastName, npi, PrescriberInDB))
{
var prescriber = new PrescribersTable()
{
PrescriberFirstName = prescriberFirstName,
PrescriberLastName = prescriberLastName,
NPI = npi,
PhysicianType = physicianType
};
context.Prescribers.Add(prescriber);
context.SaveChanges();
prescriberID = GetPrescriberID(prescriberFirstName, prescriberLastName, physicianType, PrescriberInDB);
}
if(!MemberExist(memberFirstName, memberLastName, cardholderID, MembersInDB))
{
var member = new MembersTable()
{
MemberFirstName = memberFirstName,
MemberLastName = memberLastName,
CardholderID = cardholderID,
DateofBirth = dob
};
context.Members.Add(member);
context.SaveChanges();
memberID = GetMemberID(memberFirstName, memberLastName, cardholderID, MembersInDB);
}
}
}
return "Done uploading";
}
private bool MemberExist(string memberFirstName, string memberLastName, string cardholderID, List<MembersTable> MembersInDB)
{
return MembersInDB.Exists(x => x.MemberFirstName == memberFirstName && x.MemberLastName == memberLastName && x.CardholderID == cardholderID);
}
private bool PresciberExist(string prescriberFirstName, string prescriberLastName, string npi, List<PrescribersTable> PrescriberInDB)
{
return PrescriberInDB.Exists(x => x.PrescriberFirstName == prescriberFirstName && x.PrescriberLastName == prescriberLastName && x.NPI == npi);
}
The access database contains sensitive information, so I won't be able to add those data as an example. But here's a made up data for test. The data contains claims of patients.
Now, because there are many drugs and many claims for the same patient, and many patients for a prescriber.. I broke the database as it's shown above. Needs improvement? I welcome suggestion. The reason I did this is because I don't want my database to have repeated records which will make managing really troubling. This way, I'll have unique members in memberstable, unique prescribers in prescriberstable and so on and so forth.
The challenge I'm facing is that when I read the data from the access database, I'm assuming it reads row-wise. The code should first check the database whether the member exist or not. If it does, then get the member id which is an identity column. If it doesn't, then it should insert the member's info only, and then get the memberID. Similarly, I do the same thing with the prescriber's data. Check and insert if needed. This is the long way, and this is the only way I could figure out how to do it.
I know this is not a very good programming. I'm just an analyst who unfortunately has to do a lot of programming. And I'm learning as I go. With that said, there's a lot of ways to improve this code - I just don't know any. Can you point me to the right direction? Also, an example of how to check and insert the data if it doesn't exist in the database using navigation property. Currently, the data is read and uploaded just fine, but I saw in the database that it didn't quite do what I wanted it to do. It still added a couple of already existing members. I seriously needs some help.

MVC 4 Conditional Model Validation with Entity Framework

Is it possible to place conditions on a ViewModel where data equals a specific value in one field within the entity framework, the required element or entire object is removed from the ViewModel before using TryValidateModel on the ViewModel?
I would like to remove HomeValue and PurchasePrice from the Model validation where OwnOrRent (model.OwnOrRent) is not equal to 1 or 9.
Model.cs
public class Address
{
public int Id { get; set; }
[DisplayName("House Name or Number")]
[StringLength(50)]
public string HouseNameOrNumber { get; set; }
[DisplayName("Post Town")]
[StringLength(50)]
public string PostTown { get; set; }
[Required(ErrorMessage = "Own or Rent is Required")]
[DisplayName("Own or Rent")]
[StringLength(50)]
public string OwnOrRent { get; set; }
[Required(ErrorMessage = "Mortgage/Rent Amount is Required")]
[DisplayName("Mortgage/Rent Amount")]
[StringLength(50)]
public string MortgageRent { get; set; }
[Required(ErrorMessage = "Home Value is Required")]
[DisplayName("Home Value")]
[StringLength(50)]
public string HomeValue { get; set; }
[Required(ErrorMessage = "Purchase Price is Required")]
[DisplayName("Purchase Price")]
[StringLength(50)]
public string PurchasePrice { get; set; }
}
HomeController.cs
public ActionResult Application(int id)
{
var viewAddressModel = new Address();
using (
var dbEntities = new DbEntities(new EntityConnection(_df.DbEntities)))
{
var model = dbEntities.Applications.Single(e => e.Id == id);
viewAddressModel.Id = Id;
viewAddressModel.HouseNameOrNumber = model.HouseNameOrNumber;
viewAddressModel.PostTown = model.PostTown;
viewAddressModel.OwnOrRent = GetStatus(model.OwnOrRent);
viewAddressModel.MortgageRent = model.MortgageRent.ToString();
viewAddressModel.HomeValue = model.HomeValue;
viewAddressModel.PurchasePrice = model.PurchasePrice;
if (model.OwnOrRent != "1" || model.OwnOrRent != "9")
{
ModelState.Remove("HomeValue");
ModelState.Remove("PurchasePrice");
}
if (!TryValidateModel(viewAddressModel))
{
return PartialView("Address", viewAddressModel);
}
}
var vm = new ApplicationViewModel { Item = CreateApp(id) };
return PartialView("Application", vm);
}
As you can see I have tried to use ModelState.Remove but this has no effect.
Any assistance with this would be much appreciated?
Based on your comments you want to populate a model from the database, then validate it (because its old data which may not be valid), but not display errors for HomeValue or PurchasePrice based on the value of OwnOrRent, in which case you need to call TryValidateModel first, then remove ModelState errors
var viewAddressModel = new Address();
.... // set values
if (!TryValidateModel(viewAddressModel))
{
if (model.OwnOrRent != "1" || model.OwnOrRent != "9")
{
if (ModelState.ContainsKey("HomeValue"))
{
ModelState["HomeValue"].Errors.Clear();
}
if (ModelState.ContainsKey("PurchasePrice"))
{
ModelState["PurchasePrice"].Errors.Clear();
}
}
}
You can now use if (ModelState.IsValid) to check if there are any other validation errors and return the appropriate view
Side note: I just used your if condition relating to the OwnOrRent value, but I suspect what you really want is
if (!(model.OwnOrRent == "1" || model.OwnOrRent == "9"))
There is a thread about the different options to do conditional validation:
ASP.NET MVC Conditional validation

Categories

Resources