Select and Match Data from List using LINQ C# - c#

I have data in List, and i want to do login if data matches with any of records.
public HttpResponseMessage Post(form model)
{
List<form> user = new List<form>();
user.Add(new form { username = "admin", password = "admin" });
user.Add(new form { username = "Gopal", password = "123" });
user.Add(new form { username = "niit", password = "niit" });
if (model.username == user.Select(p => p.username.Equals(model.username))
{
}
}
I want to like this - (Done with Hard coded data)
if (model.username == "admin" && model.password == "admin")
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
else { return Request.CreateResponse(HttpStatusCode.InternalServerError); }
This is my Model Class - Form
public class form
{
[Required]
public string username { get; set; }
[Required]
public string password { get; set; }
}
I have done this with hard coded data but want to do with list. Please help me this out. How Can I do it?

Try this way
if (user.Where(a => a.username == model.username && a.password == model.password).Select(p => p).Count() != 0)
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
or you can simply use any
if (user.Any( a => a.username.Contains(model.username) && a.password.Contains(model.password)))
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}

I hope this isn't production code! You will want to use password salting + hashing if that user data is being stored. Best not to write your own code with this kind of stuff if you aren't experienced.
BUT to answer your question, you most likely want this:
user.Any(u => u.username == model.username && u.password == model.password)
There are better data structures though. For example, a Dictionary will allow O(1) lookup of the user (form?) by username rather than needing to iterate through the whole collection.

You can do this,
if (user.Any(use => model.username.Contains(use.username) && model.username.password(use.password))
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
else { return Request.CreateResponse(HttpStatusCode.InternalServerError); }

Use following code:
if (user.Where(x=> x.username.Equals(model.username) && x.password.Equals(model.password)).FirstOrDefault() != null)
{
return Request.CreateResponse(HttpStatusCode.Accepted);
}
else { return Request.CreateResponse(HttpStatusCode.InternalServerError); }
hope it will help you.

Related

ASP.NET MVC how to check if instance already exists before creating a new one

ASP.NET MVC how can I check if instance of a class already exists before creating a new one? Here is the class:
public class Doctor
{
public int Id {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
public string Address {get;set;}
}
In the controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Title,Id,FirstName,LastName,Address,Facility,IsAvailable")] Doctor doctor)
{
if (ModelState.IsValid)
{
db.Doctors.Add(doctor);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(doctor);
}
How can I check if the dcotor already exists, by comparing firstName and LastName? I think I need something like:
var doctors = from d in db.Doctors select d;
doctors = doctors.FirstOrDefault(d => d.FirstName == search && d.LAstName == searchlast); return RedirectToAction("Index", "Doctor");
Basically if the doctor already exists I do not want to be able to create a new one.
You need to try to get the doctor with the input doctor's firstname and lastname from the database.
Which you can do by
var doc = doctors.FirstOrDefault(d => d.FirstName == doctor.FirstName && d.LastName == doctor.LastName);
And check if doc is null or not. If it is null that means the doctor with the specified firstname and lastname do not exist, and in that case a new doctor should be added to the database.
if (doc == null)
{
db.Doctors.Add(doctor);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return RedirectToAction("Index", "Doctor");
}
You're almost there
var doctor = doctors.FirstOrDefault(d => d.FirstName == search && d.LAstName == searchlast);
if(doctor == default)
//doctor not found - maybe add it?
else
//doctor found - return it?
return RedirectToAction("Index", "Doctor");
If you always want to return a doctor and only add it if it is not found, remove the else and assign a new doctor in the if. If your c# is older and doesn't understand the default keyword, use null instead
first of all create a separate method for it helps you reuse it some day you wana create client validation too.
private bool isDuplicateName(string fname,string lname)
{
return db.Doctors.Any(d=>d.FirstName == fname and d.LastName == lname);
}
then in your action just call it
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Title,Id,FirstName,LastName,Address,Facility,IsAvailable")] Doctor doctor)
{
if (ModelState.IsValid)
{
if(isDuplicateName(doctor.FirstName,doctor.LastName) == false)
{
db.Doctors.Add(doctor);
db.SaveChanges();
}else{
return RedirectToAction("Index");
}
}
return View(doctor);
}
You can do it like this:
var doctorExist = db.Doctors.Where(d => d.FirstName == search && d.LastName == searchlast).Count() > 0;
if(doctorExist){
//doctor found
}else{
//doctor not found
}
If it found more than 0 results then doctorExist = true.
Hope this helps.

I got connection error it does not read data from database

In Xamarin forms, I tried to make a login form using MVVM. When I write the code there is no error but it does not give the desired output.
public Command Login
{
get
{
return new Command(() =>
{
var d = database.loggin(Usernamelogin, Passwordlogin);
if (d != null)
{
if (d.UserName == Usernamelogin && d.Password == Passwordlogin)
{
App.Current.MainPage.DisplayAlert("Notification", "Successfully Login", "Okay");
}
else
{
App.Current.MainPage.DisplayAlert("Notification", "Error Login", "Okay");
}
}
else
{
App.Current.MainPage.DisplayAlert("Notification", "No data", "Okay");
}
});
}
}
this is login command
public Register_person loggin(string mail,string pass )
{
return Conn.Table<Register_person>().FirstOrDefault(t => (t.Email == mail && t.Password == pass));
}
I only get the display message when the database is null statement. I cannot find why.
public ICommand Login { get; set; }
then add a constructor
public LoginViewModel()
{
Login = new Command(Login_Clicked);
}
then create a method Login_Clicked
private void Login_Clicked()
{
database = new Database();
var Logindata = database.GetUsername(_usernamelogin);
if (string.IsNullOrWhiteSpace(_usernamelogin) || string.IsNullOrWhiteSpace(_passwordlogin))
{
// your code
}
else
{
if (Logindata != null)
{
if (Logindata.UserName == _usernamelogin && Logindata.Password == _passwordlogin)
{
// your code
}
else
{
// your code
}
}
else
{
// your code
}
}
}
linc query
return Conn.Table<your Table name>().FirstOrDefault(t => t.Email == mail);
I extract email in the table

Make Foreach after meeting a condition in List

I am creating a static sign in page using List to save the data. I am using a ForEach to loop through the list but the issue I am facing is I want my for loop to stop immediately the condition is true.
NB: I have tried using a break and a return but they are not working as expected.
The code is here:
List<User> users = new List<User>(3);
public MainWindow()
{
InitializeComponent();
User superAdmin = new User()
{
userType = "Super Admin",
uniqueCode = "123456",
password = "password1"
};
User admin = new User()
{
userType = "Admin",
uniqueCode = "654321",
password = "password16"
};
User userOperator = new User()
{
userType = "Operator",
uniqueCode = "109105",
password = "specialpassword"
};
users.Add(superAdmin);
users.Add(admin);
users.Add(userOperator);
}
private void login_OnClick(object sender, RoutedEventArgs e)
{
string userType = cmbAdminType.Text;
string uniqueCode = txtUniqueCode.Text;
string password = txtPassword.Text;
foreach (User userPick in users)
{
if (userPick.userType == userType && userPick.uniqueCode == uniqueCode)
{
MessageBox.Show("Cool you are in!");
break;
}
else
{
MessageBox.Show("Err, not found!");
break;
}
}
}
}
public class User
{
public string userType { get; set; }
public string uniqueCode { get; set; }
public string password { get; set; }
}
Please, what else can I do?
Others have pointed out the flaw in your current code, but I'd suggest using a LINQ approach here. It's much shorter and easier to read - at least when you're used to LINQ:
bool validUser = users.Any(user => user.userType == userType && user.uniqueCode == uniqueCode);
MessageBox.Show(validUser ? "Cool you are in!" : "Err, not found!");
Any is short-circuiting: it stops as soon as it finds a match.
As a side-note, I'd strongly encourage you to start following .NET naming conventions for your properties.
I believe that this could be because you have a logical error in the way that your code is working.
Currently, you break from your foreach loop on the first successful match, or the first unsucessful match. So basically, your enumeration will break after 1 iteration whether successful or not.
You could introduce a flag that you use to record success, or not, and then test this after the enumeration, as so:
private void login_OnClick(object sender, RoutedEventArgs e)
{
string userType = cmbAdminType.Text;
string uniqueCode = txtUniqueCode.Text;
string password = txtPassword.Text;
bool isMatched = false;
foreach (User userPick in users)
{
if (userPick.userType == userType && userPick.uniqueCode == uniqueCode)
{
isMatched = true;
break;
}
}
if (isMatched)
{
MessageBox.Show("Cool you are in!");
}
else
{
MessageBox.Show("Err, not found!");
}
}
Your loop stops after the first object found in the list. I think what you want to accomplish is that it breaks either when the object you looked for is found either at the end of the loop, if the object you were looking for had not been found. The code:
bool userInside = false;
foreach (User userPick in users)
{
if (userPick.userType == userType && userPick.uniqueCode == uniqueCode)
{
MessageBox.Show("Cool you are in!");
userInside=true;
break;
}
}
if (userInside==false)
{
MessageBox.Show("Err, not found!");
}
I hope this helps. ^^

Constraint Violation When Creating AD User Object with account management extension class attributes

I'm creating a WCF service to retrieve and update/create AD Person objects, and have run into a snag. I created an extension class to manage extended attributes (delivered schema attributes, but not in the default account management class attribute set). I have no problem retrieving or updating these extended attributes, but when I try to create a new person object in AD, I receive a constraint violation
System.DirectoryServices.DirectoryServicesCOMException: A constraint violation occurred.
I'm currently testing this in debug mode in Visio 2013 on a Windows 8.1 desktop. Code below. Any hints or insight anyone can offer is most appreciated.
Hopefully the code below is documented well enough and makes sense. Thanks in advance!
Update: I should have been more clear. The reason I am pretty sure it is the extension attributes is when I comment out those lines in the calling code (now commented in code section below) that set those attributes it will create the object without errors.
This is my calling code:
....other code.....
PrincipalContext pc = null;
try {
pc = new PrincipalContext(ContextType.Domain, MyProject.ADAccountService.Properties.Settings.Default.Domain, MyProject.ADAccountService.Properties.Settings.Default.PeopleDN, MyProject.ADAccountService.Properties.Settings.Default.AdminAcct, MyProject.ADAccountService.Properties.Settings.Default.AdminPW);
}
catch (Exception e) {
defaultLogger.Warn(MyProject.ADAccountService.App_GlobalResources.Messages.PrincipalContextCreateFail, e);
// Application.Exit();
}
....other code looking for whether ADObject already exists...
// Create the new UserPrincipal object
if (!newADPerson.personExists) {
using (ADeXt userNew = new ADeXt(pc)) {
string randomPassword = System.Web.Security.Membership.GeneratePassword(20, 4);
if (newADPerson.officePhone != null && newADPerson.officePhone.Length > 0) { userNew.VoiceTelephoneNumber = newADPerson.officePhone; }
if (newADPerson.department != null && newADPerson.department.Length > 0) { userNew.department = newADPerson.department; } //offending codeline
if (newADPerson.title != null && newADPerson.title.Length > 0) { userNew.title = newADPerson.title; } //offending codeline
if (newADPerson.faxNumber != null && newADPerson.faxNumber.Length > 0) { userNew.facsimileTelephoneNumber = newADPerson.faxNumber; } //offending codeline
if (newADPerson.officeLocation != null && newADPerson.officeLocation.Length > 0) { userNew.physicalDeliveryOfficeName = newADPerson.officeLocation; } //offending codeline
if (newADPerson.isEmployee) {
//if an employee and (newADPerson.script == null) use default value from global project settings
userNew.ScriptPath = newADPerson.script ?? MyProject.ADAccountService.Properties.Settings.Default.defaultScript;
}
if (newADPerson.lastName != null && newADPerson.lastName.Length > 0) { userNew.Surname = newADPerson.lastName; }
if (newADPerson.firstName != null && newADPerson.firstName.Length > 0) { userNew.GivenName = newADPerson.firstName; }
if (newADPerson.emplID != null) { userNew.EmployeeId = newADPerson.emplID; }
if (newADPerson.displayName != null && newADPerson.displayName.Length > 0) { userNew.DisplayName = newADPerson.displayName; }
userNew.SamAccountName = AccountID;
userNew.Name = AccountID;
userNew.UserPrincipalName = AccountID + MyProject.ADAccountService.Properties.Settings.Default.ExchangeAddress;
try {
userNew.Save();
userNew.SetPassword(randomPassword);
}
catch (Exception e) {
pc.Dispose();
}
}
}
Extension class code:
namespace MyProject.ADAccountService.Classes {
[DirectoryObjectClass("user")]
[DirectoryRdnPrefix("CN")]
class ADeXt : UserPrincipal {
public ADeXt(PrincipalContext context)
: base(context) {
}
public ADeXt(
PrincipalContext context,
string Container, //new constructor parameter added resolving issue
string samAccountName,
string password,
bool enabled
)
: base(
context,
samAccountName,
password,
enabled
) {
}
public static new ADeXt FindByIdentity(PrincipalContext context, string identityValue) {
return (ADeXt)FindByIdentityWithType(context, typeof(ADeXt), identityValue);
}
[DirectoryProperty("physicalDeliveryOfficeName")]
public string physicalDeliveryOfficeName {
get {
object[] result = this.ExtensionGet("physicalDeliveryOfficeName");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("physicalDeliveryOfficeName", value);
}
}
[DirectoryProperty("department")]
public string department {
get {
object[] result = this.ExtensionGet("department");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("department", value);
}
}
[DirectoryProperty("title")]
public string title {
get {
object[] result = this.ExtensionGet("title");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("title", value);
}
}
[DirectoryProperty("facsimileTelephoneNumber")]
public string facsimileTelephoneNumber {
get {
object[] result = this.ExtensionGet("facsimileTelephoneNumber");
if (result != null) {
return (string)result[0];
}
else {
return null;
}
}
set {
this.ExtensionSet("facsimileTelephoneNumber", value);
}
}
}
}
Thanks Marc, that hint helped me solve. added new parameter for the container in the extension constructor and that did the trick.
Changed the constructor in the extension class to add the default container. New constructor now lists like this:
public ADeXt(
PrincipalContext context,
**string Container,**
string samAccountName,
string password,
bool enabled
)
: base(
context,
samAccountName,
password,
enabled
) {
}
For anyone looking into this error. It could mean a lot of things, the first Google results will show that it has something to do with the PDC Emulator or replicating.
In my case it was due to too many characters for the employeeID (16 max). Sometimes it is initials (6 max) or samAccountName (19 max). Just peel of fields until it works as a starting point.

How do i return enumaration status if invalid password but return record if their is

I have modified my validate to return the record if it finds one but how would I also return an enumeration type to identify if its an incorrect password or username that the user has entered ??
eg like I have showed in the return for false password.
public user isValidUser(string username, string userPassword)
{
try
{
var _currentUser = _db.users.FirstOrDefault(a => a.username == username);
if (_currentUser != null)
{
string descriptedPassword = encrypt.DecryptRijndael(_currentUser.password, _currentUser.salt.ToString());
if (descriptedPassword == userPassword)
return _currentUser;
else
return recordEnum.invalidPassword ????
}
}
catch (Exception ex)
{
Mercentwarehousecms
.Logging
.ExceptionUtility
.LogErrorMessage("isValidUser Error DB Context", ex, "~");
}
}
The isValidUser name sounds like it should return bool.
My suggestion is to create new class
public sealed UserValidationResult
{
public User User { get; set; }
public LoginStatus Status { get; set; }
}
And modify your method to return UserValidationResult like
public UserValidationResult CheckUser(string userName, string userPassword)
{
var user = GetUser(username, userPassword);
return user != null ?
new UserValidationResult { Status = LoginStatus.Sucess, User = user }
: new UserValidationResult { Status = LoginStatus.Failed; }
}
Add an out parameter:
public user isValidUser(string username, string userPassword, out LoginStatus loginStatus)
{
...
}
enum LoginStatus
{
success,
badPassword,
badUsername
}
So, in your code set the value of loginStatus to reflect what happened. Usually I'll set the return value to null if there is a problem and describe the problem with the enum.
Call the method like this:
LoginStatus result;
user userResult = isValidUser(username, password, out result);//Be sure to use the word "out" before your paramter
if (result == LoginStatus.success)
{//Yay!}
else if (result == LoginStatus.badPassword)
{//awww...}
else if (result == LoginStatus.badUsername)
{//awww...}

Categories