Checking multiple validations using if statement - asp.net-mvc

I'm trying to work on ForgotPassword section, not in advance but normally by checking conditions. Here trying to check if the user input values Username, Mail Id, Usertype are correct otherwise, show error messages such as username or mailid or type doesn't match. But here am failing to show error messages such that the else part isn't working.
controller
public ActionResult Forgotpassword1( FormCollection collection)
{
string username = collection["username"];
string mail = collection["mail"];
string type = collection["type"].ToString();
Random rand = new Random();
var password = rand.Next().ToString();
var getrandomkey = password.Substring(0, 5);
var lgn = db.tb_log.Where(ob => (ob.username == username) && (ob.usertype == type)).FirstOrDefault();
string userid = lgn.username;
if (lgn != null)
{
if (lgn.usertype == ("User"))
{
Session["username"] = lgn.username;
Session["type"] = lgn.usertype;
userid = lgn.username;
var useraccount = db.tb_reg.Where(i => i.gmail == mail && i.usertype == type && i.username == username).FirstOrDefault();
if (useraccount != null)
{
tb_log login = db.tb_log.Where(i => i.username == username && i.usertype == type).FirstOrDefault();
if (login != null)
{
login.code = getrandomkey;
db.tb_log.Add(login);
int i = db.SaveChanges();
if (i > 0)
{
ViewBag.s = "Verification Code has been send to your registered mail id";
}
else
{
ViewBag.f = "Something went wrong";
}
}
else
{
ViewBag.f = "Username or type not match";
}
}
else
{
ViewBag.f = "Username or Mail not match";
}}

Related

asp.net mvc core A second operation was started on the context before the first operation is completed

I am using this code for authorization on controllers.
with [Authorize(Policy = "CustomRole")]
The thing happened that after 3 or 4 request it fails with
A second operation started on this context before a previous operation completed
public class CustomRoleRequirement : AuthorizationHandler<CustomRoleRequirement>, IAuthorizationRequirement
{
public CMSContext _context = new CMSContext();
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRoleRequirement requirement)
{
var routeobj = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;
var c = routeobj.RouteData.Values.Values.ToList();
var keys = routeobj.RouteData.Values.Keys.ToList();
string area = "";
string id = "";
string controller = "";
string action = "";
string module = "";
foreach (var item in keys)
{
if (item=="area")
{
int indexs = keys.FindIndex(cc => cc == "area");
area = c[indexs].ToString();
}
else if (item == "id")
{
int indexs = keys.FindIndex(cc => cc == "id");
id = c[indexs].ToString();
}
else if (item == "controller")
{
int indexs = keys.FindIndex(cc => cc == "controller");
controller = c[indexs].ToString();
}
else if (item == "module")
{
int indexs = keys.FindIndex(cc => cc == "module");
module = c[indexs].ToString();
}
else if (item == "action")
{
int indexs = keys.FindIndex(cc => cc == "action");
action = c[indexs].ToString();
}
}
string modulelink = controller;
if (!string.IsNullOrEmpty(module))
{
modulelink = modulelink + "/" + module;
}
List<string> Roles = new List<string>();
int UserId = Auth.UserID;
string UserName = Auth.UserName;
if (UserName == "superadmin")
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
// apparently the error occurred here
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
if (moduleobj != null)
{ // 69 role is assessing news module
//60 role is accessing page module
var RolesModulesobj = _context.AppRolesModules.FirstOrDefault(q => q.ModuleId == moduleobj.ModuleId && q.RolesId == Auth.RoleId);
if (RolesModulesobj != null)
{
string permissionsobj = RolesModulesobj.Permissions;
List<string> PermissionsListobj = permissionsobj.Split(',').Select(x => x.Trim()).ToList();
var FindFullAccess = PermissionsListobj.FirstOrDefault(q => q.Contains("FullAccess:true"));
if (FindFullAccess != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
var abc = PermissionsListobj.FirstOrDefault(q => q.Contains(action + ":true"));
if (abc != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
context.Fail();
return Task.CompletedTask;
}
}
}
}
}
The error occurred at this line above
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
How can I make task wait before the second operation started in the method above?
You can't use a singleton DB context. You either create one each time you need one or you pool them.

Session Value is not correct

I have 2 tables, User and RolesDetail
and
I want to store Session["role"] from RolesDetail but when i stored the value is System.Data.Entity.DynamicProxies.....
I want to store session with value from joined table
public ActionResult Login(User u)
{
var user = db.Users.SingleOrDefault(a => a.Username == u.Username && a.Password == u.Password);
if (this.IsCaptchaValid("Captcha Is Not Valid !!"))
{
if (user != null)
{
Session["role"] = user.RolesDetail.Roles;
Session["user"] = user.Username;
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Username or Password is Wrong !!");
}
}
ViewBag.ErrMessage = "Error: Captcha Is Not Valid !!";
return View();
}
Session["user"] work just fine

How to increase the performance for login response

I am working on one MVC application. After clicking on login button it is taking me almost 7 second to redirect on home page which is not a good response time as per performance. Please help me how to make response time better.
Below is my controller code.
public ActionResult UserLogIn(Models.LogIn user)
{
if (ModelState.IsValid)
{
if (IsValid(user.User_Id, user.User_Password))
{
using (var db = new CopaRuleContext())
{
var ApproveUsers = db.tbl_User.Where(u => u.User_Approved == "Yes" && u.User_Id == user.User_Id).ToList();
var UserDetails = db.tbl_User.FirstOrDefault(u => u.User_Id == user.User_Id);
string UserRole = UserDetails.User_Role;
if (UserRole != null)
{
Session["UserRole"] = UserDetails.User_Role;
}
var rolename = db.tbl_Roles.FirstOrDefault(u => u.Role_Name == UserRole);
if (rolename != null)
{
Session["RoleName"] = rolename.Role_Description;
}
var firstname = UserDetails.User_First_Name;
var lastname = UserDetails.User_Last_Name;
firstname = firstname.Substring(0, 1).ToUpper() + firstname.Substring(1).ToLower();
lastname = lastname.Substring(0, 1).ToUpper() + lastname.Substring(1).ToLower();
Session["UserName"] = firstname + ' ' + lastname;
Session["UserId"] = UserDetails.User_Id;
if (ApproveUsers != null && ApproveUsers.Count() > 0)
{
if (UserDetails.User_Is_Deleted != 1)
{
Session["Process"] = "PP";
if (UserRole == "Role-1")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Notification", "Inbox");
}
else if (UserRole == "Role-2")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Clear", "Clear");
}
if (UserRole == "Role-3")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Notification", "Inbox");
}
if (UserRole == "Role-4")
{
FormsAuthentication.SetAuthCookie(user.User_Id, false);
return RedirectToAction("Notification", "Inbox");
}
}
}
}
}
}
return View(user);
}
I was having problem with password encryption. I was using salt hash technique to encrypt the password which was affecting the performance of login. I have changed it with SHA1 encryption and performance has became incredibly fast.

ID not showing in the parameter

I have a code that sends email to user. In the email, there's a link in there that they should visit with the corresponding ID in order for them to be directed to a certain page.
Here's my code:
public void Notify(int appr_id = 0)
{
var check = db.rms_approval_routing.Where(s => s.appr_id == appr_id && s.appr_isactive == true).FirstOrDefault();
try
{
if (check != null)
{
check.status_id = 8;
db.Entry(check).State = EntityState.Modified;
db.SaveChanges();
var getinfo = db.rms_approval_route_vw.Where(s => s.appr_id == appr_id && s.appr_isactive == true).FirstOrDefault();
var getpayment = db.rms_payment.Where(s => s.appr_id == appr_id).FirstOrDefault();
if (getinfo != null && getpayment != null)
{
var ref_email = getinfo.ref_email;
var cc_email = getinfo.user_email;
var pay = getpayment.p_amount;
var body = "";
body = "Good day!<br><br>Please be informed that you have successfully referred <u>" + getinfo.Fullname + "</u> and you are entitled to receive <u>P " + pay + "</u> which will be credited on the next payout for your successful referral.<br>Kindly visit the link to acknowledge the payment: http://localhost:8119/ReferralLetter/Acknowledge/" + appr_id + " <br>Thanks!";
SendEmailController email = new SendEmailController();
email.SendReferrer(ref_email, cc_email, body);
}
}
}
catch (Exception)
{
throw;
}
}
public ActionResult Acknowledge(int appr_id = 0)
{
var check = db.rms_emails.Where(s => s.appr_id == appr_id && s.email_date_ack == null && s.email_isactive == true).FirstOrDefault();
if (check != null) {
ViewBag.email_id = check.email_id;
ViewBag.appr_id = appr_id;
return PartialView();
}
return RedirectToAction("Denied");
}
In this line: http://localhost:8119/ReferralLetter/Acknowledge/" + appr_id
The appr_id value is 0 when I tried to breakpoint the Acknowledge function. When I received the email, it showed there this line: http://localhost:8119/ReferralLetter/Acknowledge/23
Meaning there's an ID in there but why in the Acknowledge function the ID was 0?

Insert data into database(MVC)

I am trying to insert datas to Appointment table of my database. I did registration part of my project which works well. There are 2 tables, Patient and Appointment. After Login patients can make an appointment. Patient number comes like this
MyUser.PatientNo = Guid.NewGuid().GetHashCode();
For appointment date and description comes from textbox. And I want to insert PatientNo from Patient table to Appointment table. For me it looks done but when I choose date and write description but I got error on this line app.PatientNo = patient.PatientNo;
An exception of type 'System.NullReferenceException' occurred in DentAppSys.dll but was not handled in user code
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Make(Models.AppModel User)
{
if (Session["UserEmail"] != null)
{
using (var db = new MaindbModelDataContext())
{
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
var app = new Appointment();
app.Date = User.Date;
app.Description = User.Description;
app.Status = "true";
app.PatientNo = patient.PatientNo;
db.Appointments.InsertOnSubmit(app);
db.SubmitChanges();
return RedirectToAction("Make", "Appointment");
}
}
else
{
return RedirectToAction("Index", "User");
}
}
}
}
and this is registration part which is working well
public ActionResult RegAndLogin(Models.RegAndLog User)
{
if (User.RegisterModel != null)
{
if (ModelState.IsValid)
{
using (var db = new MaindbModelDataContext())
{
var Person = db.Patients.FirstOrDefault(u => u.Email == User.RegisterModel.Email);
if (Person == null)
{
string Hash = BCrypt.Net.BCrypt.HashPassword(User.RegisterModel.Password);
var MyUser = new Patient();
MyUser.Name = User.RegisterModel.Firstname;
MyUser.Surname = User.RegisterModel.Lastname;
MyUser.Birthday = User.RegisterModel.Birthday;
MyUser.Email = User.RegisterModel.Email;
MyUser.Password = Hash;
MyUser.PatientNo = Guid.NewGuid().GetHashCode();
db.Patients.InsertOnSubmit(MyUser);
db.SubmitChanges();
Session["UserEmail"] = User.RegisterModel.Email;
return RedirectToAction("Index", "Patient", User.RegisterModel);
}
else
{
ModelState.AddModelError("", "There is a user with this Email. Please enter another Email !!!");
return View();
}
}
}
else
{
ModelState.AddModelError("", "Data is incorrect !!!");
}
}
else
{
if (ModelState.IsValid && IsValid(User.LoginModel.Email, User.LoginModel.Password))
{
var TempUser = new Models.RegisterModel();
Session["UserEmail"] = User.LoginModel.Email;
using (var db = new MaindbModelDataContext())
{
var person = db.Patients.FirstOrDefault(u => u.Email == User.LoginModel.Email);
TempUser.Firstname = person.Name;
TempUser.Lastname = person.Surname;
//TempUser.RegisterModel.Birthday = (DateTime)person.BirthDate;
TempUser.Email = person.Email;
}
return RedirectToAction("Index", "Patient", TempUser);
}
else
{
ModelState.AddModelError("", "Check your E-mail or Password then try again !!!");
}
}
return View();
If you're getting a null exception on the line
app.PatientNo = patient.PatientNo;
It will be because either app or patient are null at when it's executed. I would suspect patient.
Check that patient is found correctly at the line
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
if it isn't found patient will be null.

Resources