ID not showing in the parameter - asp.net-mvc

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?

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

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

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.

Showing pop up View when calling redirect in MVC

Scenario :
The scenario is if user press tab after entering AWB No. which he previously temporary saved, all ex values must populate on run time.
Problem :
Everything is working fine but view which is populated with ex values is opening as a pop up.
JavaScript for onchange
<script type="text/javascript">
$("#AWBNO").change(function () {
var AWB = $("#AWBNO").val();
var IGMa = $("#IGMa").val();
$.ajax({
url: '#Url.Content("~/IMPORTAWBs/AuthenticatingAWB")?awb=' + AWB + '&igm=' + IGMa,
async: false,
success: function (result) {
if (result == "Authenticated AWB!") {
$("input:disabled").removeAttr('disabled');
$("select:disabled").removeAttr('disabled');
$("#AWBNO").removeAttr('disabled');
$("#process").removeAttr('disabled');
$("#PAGENO").focus();
}
else {
$("#dialog").dialog({ appendTo: "#AWBNO" }).html(result);
$("input:enabled").prop('disabled', true);
$("select:enabled").prop('disabled', true);
$("#AWBNO").removeAttr('disabled');
$("#process").removeAttr('disabled');
$("#AWBNO").focus();
}
},
error: function (xhr, stats, errorMessage) {
alert(errorMessage);
}
});
});
Code for sending instance to Edit Method:
public ActionResult AuthenticatingAWB(string awb, string igm)
{
if (igm != null && awb != null)
{
string igmNO = igm;
var IgmNo = context.IMPORTAWBs.Where(f => f.IGMNO == igmNO && f.AWBNO == awb).FirstOrDefault();
var awbPart = context.IMPORTAWBs.Where(f => f.AWBNO == awb && f.IGMNO != igm && (f.SHIPMENTTYPE == "Part" || f.SHIPMENTTYPE == "Short")).FirstOrDefault();
if (awbPart == null)
{
if (awb != null)
{
if (IgmNo == null)
{
return CheckAuthenticatedAWB(awb);
}
return Content("Duplicate Airway Bill Provided against above IGM No. , please verify again.");
}
else
{
IsAuthencatedAWB = false;
return Content("Invalid Airway Bill Number Provided, Please verify it according to formula.");
}
}
else
{
return RedirectToAction("Edit", awbPart);
}
}
return Content(null);
}
Edit.cshtml
public ActionResult Edit(int? id,IMPORTAWB RunTimeImportAWBInstance)
{
var awbno = TempData["AWBNO"];
var igmno = TempData["IGMNO"];
if (awbno != null && igmno != null)
{
var importawb = context.IMPORTAWBs.Where(x => x.AWBNO == awbno && x.IGMNO == igmno).FirstOrDefault();
var deliveryInfo = context.DELIVERYINFOes.Where(f => f.AWBNO == importawb.AWBNO).FirstOrDefault();
if (deliveryInfo != null)
{
DeliveryInfo(importawb, deliveryInfo);
}
DetailSessionHandleClass = context.IMPORTAWBDETAILs.Where(f => f.AWBNO == importawb.AWBNO).ToList();
ViewBagList();
ViewBag.PossibleIGM = context.IMPORTMANIFIESTs.Where(f => f.IGMNO == importawb.IGMNO).FirstOrDefault();
CargoEntities._olderInstancea = importawb;
return View(importawb);
}
else {
var importawb = (RunTimeImportAWBInstance == null) ? context.IMPORTAWBs.Where(x => x.AWBId == id).FirstOrDefault() : RunTimeImportAWBInstance;
var deliveryInfo = context.DELIVERYINFOes.Where(f => f.AWBNO == importawb.AWBNO).FirstOrDefault();
if (deliveryInfo != null)
{
DeliveryInfo(importawb, deliveryInfo);
}
DetailSessionHandleClass = context.IMPORTAWBDETAILs.Where(f => f.AWBNO == importawb.AWBNO).ToList();
ViewBagList();
ViewBag.PossibleIGM = context.IMPORTMANIFIESTs.Where(f => f.IGMNO == importawb.IGMNO).FirstOrDefault();
CargoEntities._olderInstancea = importawb;
return View(importawb);
}
This is very simple, the pop up is being displayed because your code is written to display that:
$("#dialog").dialog({ appendTo: "#AWBNO" }).html(result);
The code above picks up #dialog element uses jQuery dialog() method appends it to element #AWBNO and then .html() method changes the mark up of that dialog to the variable result.
According to your AuthenticatingAWB Action the content that you can expect in your pop up is:
Duplicate Airway Bill Provided against above IGM No. , please
verify again
Invalid Airway Bill Number Provided, Please verify it according to formula.
RedirectToAction("Edit", awbPart);
The content you have posted screenshots for is because of the RedirectToAction("Edit", awbPart); when it returns the new page it's mark up is added to element `#dialog' hence the result is in pop up.
The official documentation:
.html()
.html( htmlString )

Resources