Byte conversion in Linq - c#

please help me in Linq. i am completely new in linq. please see my code below.
public Entities.ServiceResult<Customer> CustomerChangePassword(string CustomerId, string OldPassword, string NewPassword)
{
long _customerId = Convert.ToInt32(CustomerId);
byte _oldPassword = Convert.ToByte(OldPassword);
var _result = (from c in context.customers where (c.CustomerId == _customerId && c.Password == _oldPassword) select c.Password.Single).SingleOrDefault();
if (_result != null)
{
string newpassword;
newpassword = Convert.ToString(_result.Password);
newpassword = NewPassword;
context.SaveChanges();
return new Entities.ServiceResult<Customer>
{
ErrorState = 0,
Message = "Password Changed Successfully."
};
}
else
{
return new Entities.ServiceResult<Customer>
{
ErrorState = 1,
Message = "Old Password Is Wrong."
};
}
}
the above code i am doing a change password functionality. in this code c.Password is byte column, and i am passing from mobile as string. in this case how to handle this. please help me to do this

there is no need to check the password in finding the customer. That's because your are dealing with an IQueriable and you can not do this kind od job easily there. Also you should change the password in place to tell the context to save it for you.
Consider the code for Converting string to byte array as well.
With SequenceEqual method you check the equality of two arrays.
I hope the following code helps :
public Entities.ServiceResult<Customer> CustomerChangePassword(string CustomerId, string OldPassword, string NewPassword)
{
long _customerId = Convert.ToInt32(CustomerId);
byte[] _oldPassword = Encoding.ASCII.GetBytes(OldPassword);
var _result = from c in context.customers where (c.CustomerId == _customerId) select c;
if (_result == null || _result.Count() == 0)
{
return new Entities.ServiceResult<Customer>
{
ErrorState = 1,
Message = "User does not exists."
};
}
var customer = _result.First();
if (!customer.Password.SequenceEqual(_oldPassword))
{
return new Entities.ServiceResult<Customer>
{
ErrorState = 1,
Message = "Old Password Is Wrong."
};
}
customer.Password = Encoding.ASCII.GetBytes(NewPassword);
context.SaveChanges();
return new Entities.ServiceResult<Customer>
{
ErrorState = 0,
Message = "Password Changed Successfully."
};
}
Good Luck.

Related

NullReferenceException When Using VerifyHashedPassword in asp.net core

Here's what happen i am working on login controller where i need to verify user input password with password hash that is in the database. When i'm trying to verify the correct password it is returning NullReferenceException: Object reference not set to an instance of an object. But when i debug it, the line with this code :
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
is skipped and does not executed but when i return the value of verified.toString() directly after calling above line of code, it is printing a "Success" string. But when it is failed to verify, the code just work properly. Here's the full code :
public dbSearchResponse dbSearch(string username, string password, ADResponse ldapResult)
{
LoginResponse finalResult = new LoginResponse();
TableSystemUser resultData = new TableSystemUser();
PasswordHasher<OldLoginParamModel> hasher = new PasswordHasher<OldLoginParamModel>(
new OptionsWrapper<PasswordHasherOptions>(
new PasswordHasherOptions()
{
CompatibilityMode = PasswordHasherCompatibilityMode.IdentityV2
}));
OldLoginParamModel inputModel = new OldLoginParamModel();
inputModel.grant_type = "password";
inputModel.password = password;
inputModel.username = username;
string hashedPassword = hasher.HashPassword(inputModel, inputModel.password);
using (var connection = new NpgsqlConnection(configuration.GetValue<string>("dbServer:connectionData")))
{
connection.Open();
try
{
var value = connection.Query<TableSystemUser>(
"SELECT id, email, emailconfirmed, passwordhash, phonenumber, username, fullname, dateofbirth, gender, COALESCE(usercredit.saldo, 0) as saldo, pricing.psc, pricing.psm, pricing.plc, pricing.plm, pricing.csc, pricing.csm, pricing.clc, pricing.clm, pricing.ssc, pricing.ssm, pricing.slc, pricing.slm FROM systemuser LEFT OUTER JOIN usercredit ON systemuser.id = usercredit.systemuserid INNER JOIN userpricing ON UUID(systemuser.id) = userpricing.systemuserid INNER JOIN pricing ON userpricing.pricingid = pricing.pricingid WHERE systemuser.email= '" + username + "' and systemuser.emailconfirmed = true;"
);
resultData = value.First();
}
catch (Exception e)
{
//Failed response
dbSearchResponse dbRespNRErr = new dbSearchResponse();
dbRespNRErr.loginResponse = null;
dbRespNRErr.userid = null;
dbRespNRErr.response = "Email not registered.";
return dbRespNRErr;
}
}
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
/*But when return the verified.toString() value here, it is returning "Success"
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = verified.toString();
return dbRespErr; */
if (verified.toString() == "Success")
{
finalResult.FullName = resultData.fullname;
finalResult.Gender = resultData.gender;
//11/26/1998 12:00:00 AM
finalResult.DateOfBirth = resultData.dateofbirth.ToString("MM/dd/yyyy HH:mm:ss tt");
finalResult.Phone = resultData.phonenumber;
finalResult.Email = resultData.email;
finalResult.UserName = resultData.username;
finalResult.PLC = resultData.plc.ToString();
finalResult.PLM = resultData.plm.ToString();
finalResult.PSC = resultData.psc.ToString();
finalResult.PSM = resultData.psm.ToString();
finalResult.SLC = resultData.slc.ToString();
finalResult.SLM = resultData.slm.ToString();
finalResult.SSC = resultData.ssc.ToString();
finalResult.SSM = resultData.ssm.ToString();
finalResult.CLC = resultData.clc.ToString();
finalResult.CLM = resultData.clm.ToString();
finalResult.CSC = resultData.csc.ToString();
finalResult.CSM = resultData.csm.ToString();
finalResult.PayLater = ldapResult.memberof;
finalResult.Credit = resultData.saldo.ToString();
dbSearchResponse dbResp = new dbSearchResponse();
dbResp.loginResponse = finalResult;
dbResp.userid = resultData.id;
dbResp.response = "success";
return dbResp;
}
//Failed response
dbSearchResponse dbRespErr = new dbSearchResponse();
dbRespErr.loginResponse = null;
dbRespErr.userid = null;
dbRespErr.response = "The user name or password is incorrect.";
return dbRespErr;
}
Anyone know what happen and how to solve it? Thanks
After i do some detailed run check, i notice that the null part of the code is,
finalResult.PayLater = ldapResult.memberof;
But i don't understand why is the error response given suggest that the null was this line of code
var verified = hasher.VerifyHashedPassword(inputModel, resultData.passwordhash, password);
so in that case, i thanks to everyone who have responded to my question.

SHA512 hashed credentials fail on validation

I got this register form where i get the user email and password and hash the password using SHA512
public Boolean IsRegistered(String email, String pass)
{
SHA512 shaM = new SHA512Managed();
if (pass.Length > 0 && email.Length > 0)
{
byte[] data = Encoding.UTF8.GetBytes(pass);
String encryptedpass = Encoding.UTF8.GetString(shaM.ComputeHash(data));
using (ModelContainer db = new ModelContainer())
{
//User usr = db.UserSet.Where(u => u.PasswordDigest == encryptedpass && u.Email == email).First();
int matches = (from u in bd.UserSet
where u.PasswordDigest == encryptedpass&& u.Email == email
select new
{
Id = u.Id
}
).Count();
if (matches > 0)
{
return true;
}
}
}
return false;
}
I use this method each time the user logs in and it works like a charm (i guess),
thing is when i prompt the user to change his/her password i cannot seem to be able to validate the old one here is what i try
I do the following to retrive the user data on the MyAccount form's constructor
User user;.
public MyAccount()
{
InitializeComponent();
try
{
using (ModelContainer db = new ModelContainer())
{
user = (from u in db.UserSet where u.Id == 2 select u).First();
txtName.Text = user.Name;
txtEmail.Text = user.Email;
}
}
catch (Exception x)
{
ErrorAlert error = new ErrorAlert("Error: " + x.Message);
error.Owner = getParentWindow();
error.ShowDialog();
}
}
then I validate it on the forms button_click
using (ModelContainer db = new ModelContainer())
{
SHA512 shaM = new SHA512Managed();
string oldpass = Encoding.UTF8.GetString(shaM.ComputeHash(Encoding.UTF8.GetBytes(ptxtOldPassword.Password)));
shaM.Dispose();
db.UserSet.Attach(user);
Regex rgx = new Regex(#"\A[\w+\-.]+#[a-z\d\-.]+\.[a-z]+\z");
if (rgx.IsMatch(txtEmail.Text))
{
if (oldpass == user.PasswordDigest)
{
if (ptxtNewPassword.Password.Equals(ptxtNewPassword2.Password))
{
string newpass = Encoding.UTF8.GetString(shaM.ComputeHash(Encoding.UTF8.GetBytes(ptxtNewPassword.Password)));
user.Name = txtName.Text;
user.Email = txtEmail.Text;
user.PasswordDigest = newpass;
db.SaveChanges();
}
else
{
ErrorAlert error = new ErrorAlert("Passwords do not match");
error.Owner = getParentWindow();
error.ShowDialog();
}
When I comapare the old password in the database with the one the user enter they do not match since they are strings I've tried using equals with no luck I thought == would work but I was wrong, i looked into other answers and found this Sha512 not returning equal in c# hash validation sadly it didn't work for me, I need to understand why my first validation work and the second doesnt
so any help is apreciated Have a nice day
You don't really need to compare the final strings, test at the bytes-level. Check this previous question.
Also, if you already validated the existence of the user (by email or any other mechanism), why don't just change / update with the new password? You could validate with the email and re-use the working function for login / signin.

Foreach is not checking properly in mvc when doing a workflow

Am doing a workflow cheching in which i have 2 values and the when the foreach condition is checked only one time it enters the loop and exits out without going to the next one.
public CustomBusinessServices InvokeWorkFlowPermissionBusinessRule(dynamic workFlowImplemented, out string serviceName, out int permissionId)
{
try
{
List<WorkflowEligibilityMapping> workFlowPermissionService = new List<WorkflowEligibilityMapping>();// to handle null values
int current_ControllerId = Convert.ToInt32(workFlowImplemented); //ControllerId
using (var db = new AdminDb())
{
//to select services against this controller
workFlowPermissionService = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId)
select new WorkflowEligibilityMapping
{
Service = permission.Service,
WorkFlowPermissionId = permission.WorkFlowPermissionId
}).ToList();
}
int[] workFlowServiceDetails = workFlowPermissionService.Select(x => x.WorkFlowPermissionId).ToArray();
//to Login userId
var userId = Assyst.PanERP.Common.AppSession.Common.UserID;
/*******************Issue in foreach i think**************************************/
foreach (int workFlowServiceDetail in workFlowServiceDetails)
/*******workFlowServiceDetails have 2 valus********/
{
using (var db = new AdminDb())
{
string workFlowServiceDtl = (from perm in db.WorkFlowPermission.AsNoTracking()
where perm.WorkFlowPermissionId == workFlowServiceDetail
select perm.Service).FirstOrDefault();
//to select eligibility rules against this service
string eligibility = (from definition in db.WorkFlowDefinition.AsNoTracking()
join model in db.WorkFlowModel.AsNoTracking()
on definition.WorkFlowDefinitionId equals model.WorkFlowDefinitionId
join permission in db.WorkFlowPermission.AsNoTracking()
on model.WorkFlowDefinitionId equals permission.WorkFlowDefinitionId
where model.ControllerNameId.Equals(current_ControllerId) && permission.WorkFlowPermissionId == workFlowServiceDetail
select permission.EligibilityRule).FirstOrDefault();
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
string[] strTxt = workFlowServiceDtl.Split(';'); //split the service name by ';' and strore it in an array
string serviceUrl = string.Empty;
string workFlowServiceName = string.Empty;
string classpath = string.Empty;
workFlowServiceName = strTxt[0].ToString();
workFlowServiceName = workFlowServiceName.Replace(" ", "");//get the service name by removing empty blank space for the word
classpath = strTxt[1].ToString();
//Invoke REST based service (like Node.Js service)
if (strTxt.Length == 4)
{
serviceUrl = strTxt[3].ToString();
}
//Invoke c# based service
else
{
serviceUrl = string.Empty;
}
var userLists = PermissionCallMethod(classpath, workFlowServiceName, new[] { workFlowImplemented, eligibility }, serviceUrl);
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Assyst.PanERP.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
}
}
serviceName = string.Empty;
permissionId = 0;
return null;
}
catch (Exception ex)
{
throw ex;
return null;
}
}
workFlowServiceDetails have 2 values and the workFlowServiceDetail takes the first one and checks for it.goes through the loop and mapes the role for the first one to the user list at the end and the without checking the for the second vale it moves out of the loop. Please help me to make the loop work for 2 values.Is it some problem in the return part...?
if (eligibility == null)
{
string validationMessage = "";
validationMessage = "Please set eligibility for workflow permission";
serviceName = null;
permissionId = 0;
return new CustomBusinessServices() { strMessage = validationMessage };
}
if (userLists.UserList.Contains(userId))
{
serviceName = strTxt[0].ToString() + ";Assyst.PanERP.Common.WorkFlowNotificationServices;" + strTxt[2].ToString();
permissionId = workFlowServiceDetail;
return userLists;
}
If any of the above if statements evaluates to true, your loop will exit without looping through the second item in your array. The reason for this is that you are in your first conditional check do the following:
return new CustomBusinessServices() { strMessage = validationMessage };
And in your second:
return userLists;
The return statement will exit your method, and therefore terminate the foreach as well.
Try building your object first, and after your loop has walked through each item, do a return statement returning your object.

how to Update same member_id if Phone number and Country code exist in database

public class RegistrationController : ApiController
{
public DefaultRespons GetRegister(int os_id, string device_id, int country_code, long mobile_no)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
registration reg = new registration();
reg.os_id = os_id;
reg.device_id = device_id;
reg.country_code = country_code;
reg.mobile_number = mobile_no;
reg.verification_code = new Random().Next(1000, 9999);
dc.registrations.InsertOnSubmit(reg);
dc.SubmitChanges();
Twilio.TwilioRestClient client = new Twilio.TwilioRestClient("ACcount", "token");
Twilio.SMSMessage message = client.SendSmsMessage("+16782493911", "+" + reg.country_code + "" + reg.mobile_number, "Your verification code for Locii is: " + reg.verification_code);
if (message.RestException != null)
Debug.WriteLine(message.RestException.Message);
return new DefaultRespons(1, "OK",Registration.getResponse(reg));
}
public DefaultRespons GetActivate(int registration_id, int verification_code)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
registration reg = dc.registrations.Where(r => r.id == registration_id && r.verification_code == verification_code && r.registration_date==null).SingleOrDefault();
if (reg!=null)
{
List<registration> previous = dc.registrations.Where(r => r.mobile_number == reg.mobile_number && r.country_code == reg.country_code).ToList();
foreach (registration r in previous)
{
member mem = dc.members.Where(mb => mb.registration_id == r.id).SingleOrDefault();
if (mem!=null)
mem.online_status = -1;
}
member m = new member();
m.registration_id = reg.id;
m.online_status = 0;
reg.registration_date = DateTime.Now;
dc.members.InsertOnSubmit(m);
dc.SubmitChanges();
return new DefaultRespons(1, "Activated", Activation.getResponse(m));
}
else
{
return new DefaultRespons(1, "Failed", "");
}
}
Here is My code from which i am creating new Member_id . when i Enter following parameter and i activate from code then in response there is new Member_id id creating and it return . now i want when i register with same Phone number and country code whose Member id is already create i want to return same member_id it should not update new Member id please help me how to check the Phone number and country code already exist in database and return same member id. please help me i am not able to do this how to check .
Hi Anil try this sample code:
make required changes as per your code
public int CheckUser(int countrycode, long mobileno)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
int id = from b in dc.registrations
where b.country_code.Equals(countrycode) && b.mobile_number.Equals(mobileno)
select b.registration_id;
return id;
}
public DefaultRespons GetRegister(int os_id, string device_id, int country_code, long mobile_no)
{
LociDataClassesDataContext dc = new LociDataClassesDataContext();
int reg_id = CheckUser(country_code, mobile_no);
if (reg_id == 0)
{
registration reg = new registration();
reg.os_id = os_id;
reg.device_id = device_id;
reg.country_code = country_code;
reg.mobile_number = mobile_no;
reg.verification_code = new Random().Next(1000, 9999);
dc.registrations.InsertOnSubmit(reg);
dc.SubmitChanges();
Twilio.TwilioRestClient client = new Twilio.TwilioRestClient("AC3c23fee017f23f5061a6b5d3be6f74da", "6fe81560f88f3850c5ad5d4a7b8a5f50");
Twilio.SMSMessage message = client.SendSmsMessage("+16782493911", "+" + reg.country_code + "" + reg.mobile_number, "Your verification code for Locii is: " + reg.verification_code);
if (message.RestException != null)
Debug.WriteLine(message.RestException.Message);
return new DefaultRespons(1, "OK", Registration.getResponse(reg));
}
else
{
//your code what you want to do with the reg_id
}
}
#Arijit - For best practice, please make sure to not include your auth token in your code examples, or at least make sure to reset it any time you share it. Thanks!

Either an issue with my linq statement or with my GetCollection<T>()

Here is my code:
This is the function being called by fiddler using:
http://localhost:3334/Service/Login/?json={'username':'cara','password':'password'}
public ActionResult Login(JObject JSON)
{
var response = JsonResponse.OKResponse();
var username = JSON["username"].ToString();
var password = JSON["password"].ToString();
var helper = new MemberHelper();
//goes into here and never returns
if (helper.ValidateUser(username, password))
{
MongoCollection<User> users = db.GetCollection<User>();
var usr = users.FindAll().FirstOrDefault(u => u.UserName.Equals(username));
response.data.Add(usr);
}
else
{
return Json(JsonResponse.ErrorResponse("Invalid username or password provided!"), JsonRequestBehavior.AllowGet);
}
return Json(response, JsonRequestBehavior.AllowGet);
}
And the validateUser method within MemberHelper:
public override bool ValidateUser(string username, string password)
{
var hash = Encoding.ASCII.GetBytes(password);
var provider = new SHA256CryptoServiceProvider();
for (int i = 0; i < 1024; i++) // 1024 round SHA256 is decent
hash = provider.ComputeHash(hash);
var pass = Convert.ToBase64String(hash);
MongoCollection<User> users = db.GetCollection<User>();
//***The following statement is where the program just stops***
var usr = users.FindAll().FirstOrDefault(u => u.UserName.Equals(username) && u.Password.Equals(pass));
...
}
And getCollection....
public MongoCollection<T> GetCollection<T>(string name = null)
{
string collectionName = name;
if (collectionName == null) {
collectionName = typeof(T).Name;
}
return Database.GetCollection<T>(collectionName);
}
I really don't know what is going wrong. I am new to linq so I am not sure if there is some golden rule that I am breaking. Please help! Let me know if there is anything else I need to add.
You can also change it to something like
var usr = users.AsQueryable().Where(u => u.UserName.Equals(username)).FirstOrDefault();
The problem was indeed within the method GetCollection<>() once I replaced it with the following code, it worked just fine:
public MongoCollection<T> GetCollection<T>(string name = null)
{
string collectionName = name;
if (collectionName == null)
collectionName = typeof(T).Name;
if (Database.CollectionExists(collectionName) == false)
Database.CreateCollection(collectionName);
return Database.GetCollection<T>(collectionName);
}

Categories

Resources