How to increase the performance for login response - asp.net-mvc

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.

Related

Checking multiple validations using if statement

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";
}}

How to deal with a non existing session variable?

I am trying to check if a booking record exists, then show its details. Otherwise return to Bookparking page but else part isn't working and shows Object reference not set to an instance of an object because there is no such field with the Session[""]
Controller:
public ActionResult Viewparking()
{
if (IsUserLoggedIn(Session, Request) == false)
{
return RedirectToAction("login");
}
else
{
String id = Session["username"].ToString();
ViewBag.userid = id;
var checkbooking = db.tb_booking.Where(s => s.username == id).FirstOrDefault();
if (checkbooking != null)
{
var show = db.tb_booking.Where(e => e.username == id).FirstOrDefault();
}
else
{ //ViewBag.f = "You have no booking yet!!";
return RedirectToAction("Bookparking", "user");
}
return View();
}
}
As Gabriel noted, you have not null checked the value from the session. Code would be something like this:
public ActionResult Viewparking()
{
if (IsUserLoggedIn(Session, Request) == false)
{
return RedirectToAction("login");
}
else
{
String id = Session["username"]?.ToString();
if (id != null)
{
ViewBag.userid = id;
var checkbooking = db.tb_booking.FirstOrDefault(s => s.username == id);
if (checkbooking != null)
{ // TODO: checkbooking is currently unused, except to check if you can fetch it.
return View();
}
}
// If you reach this code, then either id is null, or the booking was not found
return RedirectToAction("Bookparking", "user");
}
}

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.

Sorting Details Page MVC

I cant figured out how perform sort in a details page. I have a classic page with list of order and for each row i have a actionlink to return details view of that order.
i try this
public ActionResult Details(int? anno,int? nr, string centro, string sortOrder)
{
ViewBag.Codice = String.IsNullOrEmpty(sortOrder) ? "Articolo_desc" : "";
if (anno == null && nr == null && string.IsNullOrEmpty(centro))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
else
{
string s = "anno=" + Request.QueryString["anno"] + "&nr=" + Request.QueryString["nr"] + "&centro=" + Request.QueryString["centro"];
ViewBag.search = s.Replace("search=", "").Replace("%3D", "=");
}
var righe = from d in db.DETAILS
where d.Anno == anno && d.Num == nr && d.Centro == centro
select new DetailsOrdersView
{
Articolo = r.Codice,
...
};
if (righe == null)
return HttpNotFound();
switch(sortOrder)
{
case "Articolo_desc":
righe = righe.OrderByDescending(i => i.Articolo);
break;
default:
righe = righe.OrderBy(i => i.Articolo);
break;
}
return View(righe);
}
}
and in details view
#Html.ActionLink("codice","Details", new { sortOrder = ViewBag.Codice, ViewBag.search })
but i on sorting I get bad request and this is the route
Orders/Details?sortOrder=Articolo_desc&search=anno%3D2017%26nr%3D6%26centro%3D1
#Html.ActionLink("codice", "Details", new { sortOrder = ViewBag.Codice, anno = ViewBag.Anno, centro = ViewBag.Centro , nr= ViewBag.Numero })
i solved as above

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?

Resources