How to deal with a non existing session variable? - asp.net-mvc

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

Related

REST API check if email exists

I would like to check if the user exists with the email in the database. I want to do this in the API, it should simply return true or false. This is what i get; when the user exists it returns true if the user does not exist in DB it returns a 500 internal server error. How could I solve this? Thanks in advance
public IHttpActionResult GetUserEmail(string Email)
{
var User = (db.Users
.Where(p => p.Email == Email)
.First());
if (User == null)
{
return Ok(false);
}
else
{
return Ok(true);
}
}
The answer has been given above, I am leaving an example code block just as an example. :)
var User = db.Users.FirstOrDefault(p => p.Email == Email);
if (User == null)
{
return Ok(false);
}
else
{
return Ok(true);
}
// or
var User = db.Users.Any(p => p.Email == Email);
if (!User)
{
return Ok(false);
}
else
{
return Ok(true);
}
code block with the changes as mentioned by #Dawood Awan in the comments –
public IHttpActionResult GetUserEmail(string Email)
{
var User = (db.Users
.Where(p => p.Email == Email)
.FirstOrDefault());
if (User == null)
{
return Ok(false);
}
else
{
return Ok(true);
}
}

The bool value always is always taken as false but its true in database? MVC

I have defined user(admin) type as 'bit' data type in my database. So if value is true it should go to a specific page otherwise it should return the same view. But whenever I pass object (adminObj) with different values the if statement only returns 'false' from database. Can somebody help where is the problem ?
here is my logic
[HttpPost]
public ActionResult Login(tbl_Admin adminObj)
{
studentDBEntities db = new studentDBEntities();
var adminvar = db.tbl_Admin.Where(x => x.Email == adminObj.Email && x.Password == adminObj.Password).FirstOrDefault();
var type=adminObj.Type;
if (adminvar != null)
{
/*var isGlobal=*/
if (adminObj.Type == true)
{
return RedirectToAction("ListAdmin");
}
else
{
return View();
}
}
else
{
return View();
}
}
Values in Database-Table:
When Type=1
Alright, I found the logical error here. I was calling the login object instead of the object which was actually storing the fetched data. So I should call var type=adminvar.Type; instead of var type=adminObj.Type;
So The Corrected logic will be
[HttpPost]
public ActionResult Login(tbl_Admin adminObj)
{
studentDBEntities db = new studentDBEntities();
var adminvar = db.tbl_Admin.Where(x => x.Email == adminObj.Email && x.Password == adminObj.Password).FirstOrDefault();
if (adminvar != null)
{
if (adminvar.Type== true)
{
return RedirectToAction("ListAdmin");
}
else
{
return View();
}
}
else
{
return View();
}
}

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

Dashed routing in ASP.NET Core MVC?

Before Core, I used something like this in MVC:
public class HyphenatedRouteHandler : MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
requestContext.RouteData.Values["controller"] = requestContext.RouteData.Values["controller"].ToString().Replace("-", "_");
requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"].ToString().Replace("-", "_");
return base.GetHttpHandler(requestContext);
}
}
How can I in ASP.Net Core use dashes in urls? ... like http://www.example.com/my-friendly-url ... and convert it to action my_friendly_url.
I don't want to use Attribute Routes.
Thanks
Add this convention in Startup in ConfigureServices method:
options.Conventions.Add(new DashedRoutingConvention());
Routes in UseMvc will not work. They simply will not be considered by ASP.Net itself. I have created issue on GitHub... but not sure how it will go. For now you can specify routes with attributes on methods. Convention will reuse/copy original routes and update/add new dashed path in format {controller}/{action}.
public class DashedRoutingConvention : IControllerModelConvention
{
public void Apply(ControllerModel controller)
{
string parent = this.Convert(controller.ControllerName);
foreach (ActionModel action in controller.Actions)
{
string child = this.Convert(action.ActionName);
string template = $"{parent}/{child}";
if (this.Lookup(action.Selectors, template) == true)
continue;
List<SelectorModel> selectors = action.Selectors.Where(item => item.AttributeRouteModel?.Template == null).ToList();
if (selectors.Count > 0)
{
foreach (SelectorModel existing in selectors)
{
if (existing.AttributeRouteModel == null)
existing.AttributeRouteModel = new AttributeRouteModel();
existing.AttributeRouteModel.Template = template;
}
}
else
{
selectors = action.Selectors.Where(item => item.AttributeRouteModel?.Template != null).ToList();
foreach (SelectorModel existing in selectors)
{
SelectorModel selector = new SelectorModel(existing);
selector.AttributeRouteModel.Template = template;
if (action.Selectors.Any(item => this.Compare(item, selector)) == false)
action.Selectors.Add(selector);
}
}
}
}
private string Convert(string token)
{
if (token == null)
throw new ArgumentNullException(nameof(token));
if (token == string.Empty)
throw new ArgumentException("Failed to convert empty token.");
return Regex.Replace(token, "(?<!^)([A-Z][a-z]|(?<=[a-z])[A-Z])", "-$1", RegexOptions.Compiled).Trim().ToLower();
}
private bool Lookup(IEnumerable<SelectorModel> selectors, string template)
{
foreach (SelectorModel selector in selectors)
{
string current = selector.AttributeRouteModel?.Template;
if (string.Compare(current, template, StringComparison.OrdinalIgnoreCase) == 0)
return true;
}
return false;
}
private bool Compare(SelectorModel existing, SelectorModel adding)
{
if (existing.AttributeRouteModel == null && adding.AttributeRouteModel != null)
return false;
if (existing.AttributeRouteModel != null && adding.AttributeRouteModel == null)
return false;
if (existing.AttributeRouteModel != null && adding.AttributeRouteModel != null)
{
if (existing.AttributeRouteModel.Template != adding.AttributeRouteModel.Template)
return false;
if (existing.AttributeRouteModel.Order != adding.AttributeRouteModel.Order)
return false;
}
if (existing.ActionConstraints == null && adding.ActionConstraints != null)
return false;
if (existing.ActionConstraints != null && adding.ActionConstraints == null)
return false;
if (existing.ActionConstraints != null && adding.ActionConstraints != null)
{
if (existing.ActionConstraints.Count != adding.ActionConstraints.Count)
return false;
}
return true;
}
}

How to edit/update records using "TryUpdateModel" with "User.Identity.GetUserId()" in mvc.net?

This following code works fine
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int? id, string[] selectedCourses)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var instructorToUpdate = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses)
.Where(i => i.ID == id)
.Single();
if (TryUpdateModel(instructorToUpdate, "",
new string[] { "LastName", "FirstMidName", "HireDate", "OfficeAssignment" }))
{
try
{
if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment.Location))
{
instructorToUpdate.OfficeAssignment = null;
}
UpdateInstructorCourses(selectedCourses, instructorToUpdate);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
PopulateAssignedCourseData(instructorToUpdate);
return View(instructorToUpdate);
}
private void UpdateInstructorCourses(string[] selectedCourses, Instructor instructorToUpdate)
{
if (selectedCourses == null)
{
instructorToUpdate.Courses = new List<Course>();
return;
}
var selectedCoursesHS = new HashSet<string>(selectedCourses);
var instructorCourses = new HashSet<int>
(instructorToUpdate.Courses.Select(c => c.CourseID));
foreach (var course in db.Courses)
{
if (selectedCoursesHS.Contains(course.CourseID.ToString()))
{
if (!instructorCourses.Contains(course.CourseID))
{
instructorToUpdate.Courses.Add(course);
}
}
else
{
if (instructorCourses.Contains(course.CourseID))
{
instructorToUpdate.Courses.Remove(course);
}
}
}
}
But I don't want to get id from view and I am using string id = User.Identity.GetUserId(); but only my checkboxes are getting updated and not the other database.
I tried db.Entry(abc).State = EntityState.Modified; but it gives an error. It says, context is already in use. How to update both tables?

Resources