Okay so I am trying to compare a login textbox password and username with a custom validator using linq to get information from the database it always returns false though on the validator could someone please tell me where my code below is going wrong. This will be very much appreciated... thank you in advanced...
protected void LoginValidate(object source, ServerValidateEventArgs args)
{
TiamoDataContext context = new TiamoDataContext();
var UsernameCheck = from User in context.Users
where User.Username == TextBoxLoginUsername.Text && User.Password == TextBoxLogInPassword.Text
select User.Username;
var PasswordCheck = from User in context.Users
where User.Username == TextBoxLoginUsername.Text && User.Password == TextBoxLogInPassword.Text
select User.Password;
String test1 = PasswordCheck.ToString();
String test2 = UsernameCheck.ToString();
if (test1 == TextBoxLogInPassword.Text && test2 == TextBoxLoginUsername.Text)
{
args.IsValid = true;
Session["Username"] = TextBoxLoginUsername;
Response.Redirect("UserProfile.aspx");
}
else
{
args.IsValid = false;
}
}
I dont know where I am going wrong I know its most probably some sort of silly mistake and me being inexperienced at this...
UsernameCheck and PasswordCheck are going to be collections, not single values. Therefore the ToString() method isn't returning what you think it should.
It's probably returning "IEnumerable<string>"
You need to force your LINQ queries to return a single result rather than a collection.
var user = context.Users.Where(u => u.Username==TextBoxLoginUsername.Text &&
u.Password == TextBoxLogInPassword.Text)
.FirstOrDefault();
string userNameCheck = user.Username;
string passwordCheck = user.Password;
As a side note, this is why using the var keyword is a little dangerous if you're not absolutely positive of the return type of the statement you're writing. If you would change your vars to strings, the compiler would have caught the type mismatch at compile time.
Related
My null checker fails, whats wrong here ?
I am trying to check if the user claims does exist for the variable sID which is just the staffID of the postback model
So I added a try catch statement to stop it crashing
var sID = ViewModel_CreateNewAgent.Tbl_Brands_Staff.BranchStaffID.ToString();
var staffIDExists = _context.AspNetUserClaims.Where(c => c.ClaimValue == sID).FirstOrDefaultAsync();
/// VALIDATE STAFF ID
var claimsExists = await _userManager.GetClaimsAsync(user);
var doesStaffIDExist ="";
try
{
doesStaffIDExist = staffIDExists.Result.ClaimValue ?? doesStaffIDExist;
//doesStaffIDExist = staffIDExists.Result.ClaimValue != null ? staffIDExists.Result.ClaimValue : doesStaffIDExist ;
}catch(Exception err) { }
Don't use try-catch for normal workflow, try to fix the real problem.
Here staffIDExists and/or staffIDExists.Result and/or ClaimValue could be null. Use the null conditional operator ? to make your code safe and readable:
var staffIDExists = _context.AspNetUserClaims.Where(c => c.ClaimValue == sID).FirstOrDefaultAsync();
string doesStaffIDExist = claimsExists?.Result?.ClaimValue ?? "";
However, does that code make sense? The Where checks for c.ClaimValue == sID, so doesStaffIDExist is always either ""(if there is no such claim) or sid.
I am trying to check if the user claims does exist for the variable
sID
Well, then this code would be easier:
return _context.AspNetUserClaims.Any(c => c.ClaimValue == sID);
I'm a greenhorn when it comes to LINQ. I've read some null exceptions and most of them pointed out
... in sth.AsEnumerable() ...
as root of the problem.
I've run into:
The function evaluation requires all threads to run.
I tried to retrieve
fieldname
from TrashPlaces (it has 2 fields only - id and name) by string Id I get from UserPlace record (UserPlace has 2 keys - 1 is userId that can be retrieved from AspNetUsers and the other is TrashPlace id). I've run into null problem on this LINQ code:
public ActionResult JsonResult()
{
var users = db.AspNetUsers;
//this was added, so I could root out mismatch in the queryId
var nameformyuser = User.Identity.Name;
//the null starts here and no-shock it goes further (meaning query is null and
//can't do nothing later)
var queryId = from user in users.AsEnumerable()
where user.Email == User.Identity.Name
select user.Id;
var placerecord = db.UserPlace;
var userplace = from uplace in placerecord.AsEnumerable()
where uplace.usersId == queryId.ToString()
select uplace.placesId;
var places = db.TrashPlaces;
var field = from blah in places.AsEnumerable()
where blah.Id == userplace.ToString()
select blah.nameOfThePlace;
TempData["username"] = User.Identity.Name;
TempData["fieldname"] = field.ToString();
TempData["datename"] = DateTime.Now;
List<TrashViewModel> json = (List<TrashViewModel>)TempData["jsonList"];
return View(json);
}
Would be grateful for help and or/advice what's the best approach towards cascading LINQ.
Thanks!
You could do all in one (don't enumerate to early by the way, this is not good for performance).
Not sure why you use ToString() you shouldn't have to if your ids are of the same type.
var query = from u in db.AspNetUsers
join up in db.db.UserPlace on u.Id equals up.usersId
join tp in db.TrashPlaces on up.placesId equals tp.Id
where u.Email == User.Identity.Name
select tp.nameOfThePlace;//or more data if you need to.
var result = query.FirstOrDefault(); //or query.AsEnumerable()
Then you can do a null check
if (result == null)
In your case, for TempData, you may just do
TempData["fieldname"] = result == null ? string.Empty : result;
or
TempData["fieldname"] = result;
But then you'll have to check if TempData["fieldname"] is not null before using it.
...
I have this controller:
public ActionResult NameSearch(SearchModel userSearch)
{
if (ModelState.IsValid)
{
var db = new reviewlogsEntities();
return View(db.logrecords.Where(m => m.username == userSearch.userName).ToList());
}
return RedirectToAction("index", "home");
}
My question is the user that is currently searching for logs is looking for a username once they have a username they can output a list. The problem I am having right now is what would my requirements be if they don't enter a username. What should happen is all users and their logs should come up. I could just make an if statement that says if left empty just do
return View(db.logrecords.ToList());
I feel like there is another way I could do it without having to do that. Because my thought process is, what if the search needs to be more complex. Where they might not enter a username but they could enter a date they are looking specifically for, or vise versa. I couldn't really do if statements then without it being super messy. Any help would really be appreciated!
You can add an if condition and do more filtering on the logrecords dbset as needed.
Assuming db is an object of your DbContext and db.logrecords is of type DbSet<LogRecord>
IQueryable<LogRecord> recordsDbSet = db.logrecords;
if(!String.IsNullOrEmpty(userSearch.UserName))
{
recordsDbSet = recordsDbSet.Where(m => m.username == userSearch.userName)
}
var resultList = recordsDbSet.ToList();
return View(resultList);
If you are planning to create more search fields in the future, you will want to set up your query to accommodate that without refactoring. Here's is a common approach:
var searchResults = db.logresults.AsQueryable();
//User Name
if (userSearch.username != string.empty)
searchResults = searchResults.Where(l => l.username == userSearch.username);
//From Date
if (userSearch.FromDate != DateTime.MinValue)
searchResults = searchResults.Where(l => l.CreatedDate >= userSearch.FromDate);
//To Date
if (userSearch.ToDate != DateTime.MinValue)
searchResults = searchResults.Where(l => l.CreatedDate <= userSearch.ToDate);
//Category (because logs always end up categorized)
if (userSearch.Category != LogCategories.All) //assuming enum here
searchResults = searchResults.Where(l => l.Category == userSearch.Category);
Setting up your method like this is easy to follow and extend when new search criteria are added, and the resulting query only includes the parameters entered by the user.
i have a problem with linq, i have the following code:
Models.Users user = null;
foreach (var item in db.Users)
{
if (item.username.Equals(username))
{
ausgabe = true;
user = item;
}
}
// linq, does not work
user = null;
var test = from u in db.Users
where u.username.Equals(username)
select u;
user = (Models.Users)test;
at the runtime i get a error because test i IQueryable, but how to make this conversation?
It looks like the problem is casting a query to a user, when you want to execute the query, so probably:
user = test.SingleOrDefault();
(see also FirstOrDefault(), First(), and Single())
Also, for convenience and readability, can I suggest:
where u.username == username
(which also, in regular code, avoids the problem of u.username being null, and thus causing a NullReferenceException)
Your cast is wrong, you want assign a list of objects to one object:
var test = from u in db.Users
where u.username.Equals(username)
select u;
user = (Models.Users)test; // wrong part.
Do
user = test.FirstOrDefault();
Or
user = db.Users.FirstOrDefault(x=>x.username.Equals(username));
Morning all.
I have the following method that I use to to try and bring back a bool:
public static bool GetShowCatSubProdStatus(string memberid, string username)
{
MyEnts showcatsubprodstatus = new MyEnts.PDC_VDSOREntities35();
var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
where p.MemberID == memberid && p.UserName == username
select p.ShowCatSubProd;
return r.Any();
}
When I call this method and debug it, the result is correct. However, when I run this method in a page load, although the method result returns the correct result, when I step through, the boolean value changes!
bool showcatsubprodstatus = MyEnts.GetShowCatSubProdStatus(_memberid, _username);
if (showcatsubprodstatus != true)
{
panCatSubProd.Visible = false;
}
Can someone explain what is going on here and how I can solve this puzzler?!
PS: Apologies for being thick.
EDIT - Right, narrowed it down to the variable. It is always return 'true' regardless of the method result?!?!
This piece of code returns an IEnumerable<bool> :
var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
where p.MemberID == memberid && p.UserName == username
select p.ShowCatSubProd;
By calling the .Any() you are asking it if there are any items in the IEnumerable. If there are you return true;
That is why you always get true back, because it always finds something.
The solution
Either you go for calling .SingleOrDefault() which returns the only element there is (if there is one) or returns the default value of that type.
var r = from p in showcatsubprodstatus.tblKeyAccountInfoes
where p.MemberID == memberid && p.UserName == username
select p.ShowCatSubProd;
return r.SingleOrDefault(); //assuming p.ShowCatSubProd is a bool and not a Nullable<bool> else you need to adjust your return type or cast it to a boolean using .GetValueOrDefault().