In my ASP.NET MVC application, in the signup form, I want to check the user-entered values with my current database table and get the Id if a record is matched.
Here from the user's end, I'm getting their email address, surname, date of birth .
Then in the controller, I'm trying to match any record from the above details to get the existing record Id.
The issue is that it happens takes more time to run this query and returns as timeout.
Is there any way of searching the record more efficiently way?
This is my Controller code
public JsonResult SignUpCustomer(string emailAddress, string password, string surName, string name, DateTime dateOfBirth, string timeZone)
{
int customerId = 0;
try
{
customerId = db.Customer.AsEnumerable().Where(x => x.Sur_Name.ToLower().Contains(surName.ToLower()) && x.Date_of_birth.Date == dateOfBirth.Date && x.Email_Primary.ToLower() == emailAddress.ToLower()).Select(x => x.Id).FirstOrDefault();
if (customerId == 0) {
customerId = db.Customer.AsEnumerable().Where(x => x.Email_Primary.ToLower() == emailAddress.ToLower() && x.Date_of_birth.Date == dateOfBirth.Date).Select(x => x.Id).FirstOrDefault();
if (customerId == 0) {
customerId = db.Customer.AsEnumerable().Where(x => x.Sur_Name.ToLower().Contains(surName.ToLower()) && x.Date_of_birth.Date == dateOfBirth.Date).Select(x => x.Id).FirstOrDefault();
}
}
if (customerId != 0) {
UserAccounts accounts = new UserAccounts();
accounts.Email_Address = emailAddress;
accounts.Surname = surName;
accounts.Name = name;
accounts.Password = Crypto.Hash(password);
accounts.Status = true;
accounts.Created_Date = DateTime.UtcNow.AddMinutes(int.Parse(timeZone));
accounts.Customer_Id = customerId;
dbs.UserAccounts.Add(accounts);
dbs.SaveChanges();
} else {
UserAccounts accounts = new UserAccounts();
accounts.Email_Address = emailAddress;
accounts.Surname = surName;
accounts.Name = name;
accounts.Password = Crypto.Hash(password);;
accounts.Status = true;
accounts.Created_Date = DateTime.UtcNow.AddMinutes(int.Parse(timeZone));
accounts.Customer_Id = customerId;
dbs.UserAccounts.Add(accounts);
dbs.SaveChanges();
}
return Json(new {
Success = true,
}, JsonRequestBehavior.AllowGet);
} catch (Exception ex) {
throw;
}
}
You can clear your Linq query to something like this:
var loweredName=surName.ToLower();
var loweredEmailAddress=surName.ToLower();
var dateOfBirthDateDatePart=dateOfBirth.Date;
customerID = db.Customer.FirstOrDefault(
x => x.Sur_Name.ToLower().Contains(loweredName)
&& x.Date_of_birth.Year== dateOfBirthDateDatePart.Year
&& x.Date_of_birth.Month == dateOfBirthDateDatePart.Month
&& x.Date_of_birth.Day == dateOfBirthDateDatePart.Day
&& x.Email_Primary.ToLower() == loweredEmailAddress)?.Id;
Change other selects too.
Date comparison options are totally diffrenet depending on the version of Ef of efCore you are using. For choosing the best way check here
Related
I'm new to Javascript, and I'm trying to loop over an array of JSON [{},{},{}, ...]
I have created this function to loop on a static Array of JSON constant, but it's not working properly even after checking online and trying.
function saveAccount() {
const userName = document.getElementById('user_name');
const userPassword = document.getElementById('user_password');
const formErrorMessage = document.getElementById('fillFormError');
if(userName.value == '' || userPassword.value == '')
{
formErrorMessage.textContent = 'Please fill the form fields first!';
formErrorMessage.style.color = 'red';
event.preventDefault();
}
else
{
localStorage.setItem('userName', userName.value);
const allUsers = '[{"username":"test3","email":"test3#hotmail.com","password":"123"},{"username":"test2","email":"test2#hotmail.com","password":"123123"},{"username":"test1","email":"test1#hotmail.com","password":"456456456"}]';//JSON.parse(localStorage.getItem('users'));
for(var i = 0; i < allUsers.length; i++){
var user = allUsers[i];
console.log(user.username);
//alert(user["username"])
if(user.username == userName){
console.log('USERNAME FOUND!!!!!');
}
}
}
}
the purpose is to find if the username exists in my array of users.
console.log(user.username); -> return undifined and the .parse also returns an error.
allUser is currently defined as a string, which you can't loop over.
Try this:
const allUsers = [{"username":"test3","email":"test3#hotmail.com","password":"123"},{"username":"test2","email":"test2#hotmail.com","password":"123123"},{"username":"test1","email":"test1#hotmail.com","password":"456456456"}]
I am using a Modal Partial View in my app. I am validating my model if it has errors I am returning the model using ModelState.AddModelError() but it is not working fine. Also, I could not load the SelectLists.
public ActionResult StockOut(StockOut model)
{
if (ModelState.IsValid)
{
var stock = (from s in db.Stocks where s.ProductId == model.ProductId select s).FirstOrDefault();
if (stock.Quantity > 0 && model.Quantity <= stock.Quantity)
{
var weight = ((from p in db.Products where p.Id == model.ProductId select p).FirstOrDefault().NetWeight) * model.Quantity;
stock.Quantity -= model.Quantity;
stock.TotalWeight -= weight;
StockOut entity = new StockOut()
{
DriverId = model.DriverId,
LastUpdated = DateTime.Now,
ProductId = model.ProductId,
Quantity = model.Quantity,
TotalWeight = weight
};
db.StockOut.Add(entity);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("Quantity", "Please Enter A Valid Quantity");
ViewBag.ProductId = new SelectList(db.Products.ToList(), model.ProductId);
ViewBag.DriverId = new SelectList(db.Products.ToList(), model.DriverId);
}
}
ViewBag.ProductId = new SelectList(db.Products.ToList(), model.ProductId);
ViewBag.DriverId = new SelectList(db.Users.ToList(), model.DriverId);
return PartialView(model);
}
Before Submitting:
After Getting an Error
fix you select lists, you are creating them twice, remove one set (inside of if)
ViewBag.ProductId = new SelectList(db.Products.ToList(),"Id", "Name" , model.ProductId);
///Are you sure that you have have to use products again?
ViewBag.DriverId = new SelectList(db.Products.ToList(),"Id",
"Name" , model.DriverId);
and if you want to use AddModelError you have to add to form
#Html.ValidationSummary(false)
auth.onAuthStateChanged(function(user){
if(user.uid){
var db = firebase.firestore();
document.getElementById("empUpd_email").value = user.email;
db.collection("employee").doc(user.uid).get().then(result => {
console.log(`${result.id} => ${result.data()}`);
document.getElementById('empUpd_fullname').value=result.fullName;
});
}else{
//no user is signed in
}
});**strong text**
i wanna gender value how i get it
And Database looks like
address
"abdul"
(string)
bio
"abdul"
dob
"2020-08-22"
fullName
"abdul"
gender
"Female"
serName
"abdul"
You can just retrieve the value of gender, using the same way how you did it for fullName.
Try something like this,
auth.onAuthStateChanged(function(user) {
if (user.uid) {
var db = firebase.firestore();
document.getElementById("empUpd_email").value = user.email;
db.collection("employee").doc(user.uid).get().then((result) => {
const results = result.data();
document.getElementById('empUpd_fullname').value = results.fullName;
document.getElementById('empUpd_gender').value = results.gender; // Tag ID is a guess!
});
} else {
//no user is signed in
}
});
Hope that works!
DocumentReference documentReference = fStore.collection("User").document(Objects.requireNonNull(fAuth.getCurrentUser()).getUid());
documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
profileName.setText(documentSnapshot.getString("Name"));
profileEmail.setText(documentSnapshot.getString("Email"));
}
}
});
I am doing some JavaScript front-end and I have a heavy load of forms, all of which need validation. As of now I am using this structure :
function validateForm() {
let form = document.forms["form-add-consumer"];
let id = form["input-id"].value;
let lastName = form["input-last-name"].value;
let firstName = form["input-first-name"].value;
...
let missing = false;
if (lastName.trim() === "") {
document.getElementById("input-last-name-error").className = "error";
missing = true;
}
if (firstName.trim() === "") {
document.getElementById("input-first-name-error").className = "error";
missing = true;
}
if(missing){
return false
} else {
return buildRequest(id, firstName, lastName, ...);
}
}
As you can see, for large forms the function will quickly grow. The code is a bit redundant for each field:
Declare form field
Check its value against a boolean condition
If boolean failed, display the error label and set the failed boolean to true to not send the request
How could I improve this code without complexyfing it too much (no library if possible) ?
Perhaps you could create an object that contians per-field validators, with selectors for respective fields, so that you can perform the nessisary validation in a more concise way like so:
function validateForm() {
let form = document.forms["form-add-consumer"];
let id = form["input-id"].value;
let lastName = form["input-last-name"].value;
let firstName = form["input-first-name"].value;
...
// Construct an object with selectors for the fields as keys, and
// per-field validation functions as values like so
const fieldsToValidate = {
'#input-id' : value => value.trim() !== '',
'#input-last-name' : value => value.trim() !== '',
'#input-first-name' : value => value.trim() !== '',
...,
'#number-field' : value => parseInt(value) > 0, // Different logic for number field
...
}
const invalidFields = Object.entries(fieldsToValidate)
.filter(entry => {
// Extract field selector and validator for this field
const fieldSelector = entry[0];
const fieldValueValidator = entry[1];
const field = form.querySelector(fieldSelector);
if(!fieldValueValidator(field.value)) {
// For invalid field, apply the error class
field.className = 'error'
return true;
}
return false;
});
// If invalid field length is greater than zero, this signifies
// a form state that failed validation
if(invalidFields.length > 0){
return false
} else {
return buildRequest(id, firstName, lastName, ...);
}
}
I have a user profile form with 15 text fields and some dropdown and an textarea. the scene is that user can input field in profile form. On save it is no necessary to fill all fields, whatever the user fills in fields i have to validate and save in database via ajax call.
for now i am using validation like this,
var first_name = document.getElementById('id_candidate_profile-first_name').value;
....
var status = false;
if(first_name != ''){
status = regex_test(first_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-first_name').innerHTML = "first name should only have alphabets";
}
else{
status = true;
}
}
if(middle_name != "" & status = true){
status = regex_test(middle_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-middle_name').innerHTML = "middle name should only have alphabets";
}
else{
status = true;
}
}
if (last_name != '' & status = true){
status = regex_test(last_name, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-last_name').innerHTML ="last name should only have alphabets";
}
else{
status = true;
}
}
if (date_of_birth != '' & status = true){
status = regex_test(date_of_birth, ck_date);
if(status==false){
document.getElementById('candidate_profile_error-date_of_birth').innerHTML ="date of birth should be in YYYY-MM-DD format";
}
else{
status = true;
}
}
if (birth_place != '' & status = true){
status = regex_test(birth_place, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-birth_place').innerHTML ="birth_place should only have alphabets";
}
else{
status = true;
}
}
if (nic != '' & status = true){
status = regex_test(nic, ck_name);
if(status==false){
document.getElementById('candidate_profile_error-nic').innerHTML ="nic should be in this format 12345-1234567-1";
}
else{
status = true;
}
}
if (status = true) {
// made ajax call
}
function regex_test(variable, regex){
var _result = false;
if(!regex.test(variable)){
_result = false;
}
else {
_result = true;
}
return _result;
}
Can be seen that there are lots of nested if else involved that irritate me, need some better way to do this? any best alternative?
You could create an array of validation objects, each object containing properties reg_ex, field, error_msg_container_id and error_msg:
var validationRules = [
{ reg_ex: first_name,
field: ck_name,
error_msg_container_id: candidate_profile_error-first_name,
error_msg: "first name should only have alphabets" },
{ reg_ex: date_of_birth,
field: ck_date,
error_msg_container_id: candidate_profile_error-date_of_birth,
error_msg: "date of birth should be in YYYY-MM-DD format" }
];
In the validation function, you just iterate through the whole array. That also makes it easier to maintain further input fields which you might add later.
P.S.: If you don't know how to iterate over an array, let me know.
Edit: Since requested by OP, an iteration function would look similar to this:
function isFormDataValid() {
for (i=0; i< validationRules.length; i++) {
// do the validation inside here, it will be repeated once for each validation rule;
}
return status;
}
In case you need variable property names from the array to read/write, use this syntax
Object[variable]
where variable contains the string that is the name of the property you need to access.
var myObject = {
name: "peter",
age: 46
};
var validationRules = [ { fieldname: 'name'}, { fieldname: 'age' } ];
for (var i=0; i< validationRules.length; i++) {
alert(myObject[validationRules[i].fieldname]);
}
You can use any form validation library. I personally recommend Parsley.
There's a simple validation form example: http://parsleyjs.org/doc/examples/simple.html