Unreachable code detected [ModelState]…? - c#

Unreachable code detected [ModelState]
// POST: Home/Register
[HttpPost]
public ActionResult Register(AccountUser user)
{
if (ModelState.IsValid)
{
using (ourDbContext db = new ourDbContext())
{
db.AccountUsers.Add(user);
db.SaveChanges();
return View();
}
ModelState.Clear();
ViewBag.Message = user.UserName + " " + "Success";
}
return View();
}

Related

How to handle WebClient response to display error message to user?

I am working on a MVC Web App which is calling a Web API. In my Create (POST) method, a user will enter email addresses of some users in the database. I have a check to enter the email only if the email does not already exist in the database or not. If it already exists, I want to be able to show an error message to the user "Email already exists".
I don't know how to handle the response to display an error message to the user when it fails to create an approveduser? I am trying with a try-catch case, but it is not working. I have ViewBag.Message = error which I am trying to display in my Index View when it fails. But nothing is displaying. When I debug, it doesn't even go to the catch when the email exists in the database, it just takes me to the Index view.
public ActionResult Create([Bind(Include = "Email,FirstName,LastName")] ApprovedUsers approvedUsers)
{
try
{
using (WebClient client = new WebClient())
{
token = Session.GetDataFromSession<string>("access_token");
client.Headers.Add("authorization", "Bearer " + token);
byte[] response = client.UploadValues(apiUrl, "POST", new NameValueCollection()
{
{ "Email", approvedUsers.Email },
{ "FirstName",approvedUsers.FirstName },
{ "LastName",approvedUsers.LastName }
});
string result = System.Text.Encoding.UTF8.GetString(response);
return RedirectToAction("Index");
}
}
catch
{
return RedirectToAction("Index", new { error = "Email exists" });
}
}
Index Action
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, string error)
{
ViewBag.Message = error;
This is the API method being called.
public IHttpActionResult PostApprovedUsers(ApprovedUsers approvedUsers)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (!db.ApprovedUsers.Any(u => u.Email == approvedUsers.Email))
{
db.ApprovedUsers.Add(approvedUsers);
db.SaveChanges();
}
return CreatedAtRoute("DefaultApi", new { id = approvedUsers.Email }, approvedUsers);
Try this:
public ActionResult Create([Bind(Include = "Email,FirstName,LastName")] ApprovedUsers approvedUsers)
{
try
{
using (WebClient client = new WebClient())
{
token = Session.GetDataFromSession<string>("access_token");
client.Headers.Add("authorization", "Bearer " + token);
byte[] response = client.UploadValues(apiUrl, "POST", new NameValueCollection()
{
{ "Email", approvedUsers.Email },
{ "FirstName",approvedUsers.FirstName },
{ "LastName",approvedUsers.LastName }
});
string result = System.Text.Encoding.UTF8.GetString(response);
}
}
catch
{
TempData["Error"] = "Email Exists";});
}
RedirectToAction("Index");
}
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, string error)
{
ViewBag.Message = TempData["Error"].ToString();
}
It was my API that was causing the issue. Even when it failed to create the duplicate email, it never went to the catch because I didn't have a bad request return if the email did exist in the database.
Changed my API to this and then it was working.
if (db.ApprovedUsers.Any(u => u.Email == approvedUsers.Email))
{
return Content(HttpStatusCode.BadRequest, "Email exists already");
}
else
{
db.ApprovedUsers.Add(approvedUsers);
}
try
{
db.SaveChanges();
}
catch (DbUpdateException e)
{
if (ApprovedUsersExists(approvedUsers.Id))
{
return Conflict();
}
throw e;

Passing message in ViewBag from controller to view in ASP.Net MVC

I am new to ASP.Net MVC . I have a view named Index.cshtml .I have two actions in homeController, 'Index' and 'saveAttendance'. First, Index action takes place and the datas from view returned by 'Index' action is sent to 'saveAttendance' action. After all the functions in 'saveAttendance' action is completed I need to return to view to 'Index.cshtml' with a success message in viewbag. I don't have a view assigned to 'saveAttendance' action. I just need to return to view in 'Index' action.
My homeController's code:
public ActionResult Index()
{
try
{
ViewBag.nepali_date = dc.ToBS(DateTime.Now);
}
catch (Exception ex)
{
throw ex;
}
return View();
}
public void saveAttendance(attendance_entry entryObj)
{
try
{
DateConverter dc = new DateConverter();
DateTime current_date = entryObj.current_date;
string nep_date = entryObj.nep_date;
DateTime current_time = entryObj.current_time;
string current_day = entryObj.current_day;
int staff_id = Convert.ToInt32(Session["staff_id"]);
string in_time = entryObj.in_time;
string out_time = entryObj.out_time;
if( DAL.Attendance.Model.exists(staff_id.ToString())!=0)
{
ViewBag.message = "Attendance for today is already made.";
return;
}
DAL.Attendance.Model.insert(nep_date, staff_id,current_date, current_time, current_day,in_time,out_time);
ViewBag.message = "Record saved successfully";
RedirectToAction("Index");
}
catch (Exception)
{
ViewBag.message = "Failed to save attendance record";
}
}
Rename saveAttenance to Index to handle POST.
public ActionResult Index() {
ViewBag.nepali_date = dc.ToBS(DateTime.Now);
return View();
}
[HttpPost]
public ActionResult Index(attendance_entry entryObj) {
try {
var dc = new DateConverter();
var current_date = entryObj.current_date;
var nep_date = entryObj.nep_date;
var current_time = entryObj.current_time;
var current_day = entryObj.current_day;
var staff_id = Convert.ToInt32(Session["staff_id"]);
var in_time = entryObj.in_time;
var out_time = entryObj.out_time;
if( DAL.Attendance.Model.exists(staff_id.ToString())!=0) {
ViewBag.message = "Attendance for today is already made.";
} else {
DAL.Attendance.Model.insert(nep_date, staff_id,current_date, current_time, current_day,in_time,out_time);
ViewBag.message = "Record saved successfully";
}
} catch (Exception) {
ViewBag.message = "Failed to save attendance record";
}
ViewBag.nepali_date = dc.ToBS(DateTime.Now);
return View();
}
And update the form in the view to POST to the the correct action.
The problem is the return type of function "saveAttendance" which is void and in the end of "saveAttendance" you are doing RedirectToAction("Index") which eventually calls the index ActionResult but as "saveAttendance" is void you wont be redirected to Index View.
Just make three small tweaks
Change public void saveAttendance(attendance_entry entryObj) to public ActionResult Index(attendance_entry entryObj)
In the end of saveAttendance function just write
Return RedirectToAction("Index");
instead of
RedirectToAction("Index");
Use [ChildActionOnly] so that saveAttendance is not accessed by url
Here is the code
[ChildActionOnly]
public ActionResult saveAttendance(attendance_entry entryObj)
{
try
{
DateConverter dc = new DateConverter();
DateTime current_date = entryObj.current_date;
string nep_date = entryObj.nep_date;
DateTime current_time = entryObj.current_time;
string current_day = entryObj.current_day;
int staff_id = Convert.ToInt32(Session["staff_id"]);
string in_time = entryObj.in_time;
string out_time = entryObj.out_time;
if (DAL.Attendance.Model.exists(staff_id.ToString()) != 0)
{
ViewBag.message = "Attendance for today is already made.";
return;
}
DAL.Attendance.Model.insert(nep_date, staff_id, current_date, current_time, current_day, in_time, out_time);
ViewBag.message = "Record saved successfully";
return RedirectToAction("Index");
}
catch (Exception)
{
ViewBag.message = "Failed to save attendance record";
}
}`

MVC.Net Custom registration/login error “The salt was not in an expected format of {int}.{string}”

I need your help. I'm trying to make a custom registration/login in MVC.Net, which uses SimpleCripto to encrypt the passwords. After I register a user everything is saved in my table and it seems all right, but when I try to LogIn I get an error - "The salt was not in an expected format of {int}.{string}", which comes from my "IsValid" method, in the statement "if (user.Password == crypto.Compute(user.PasswordSalt, password))". I'll post my AuthenticantionController with the Register and LogIn methods and if you can point where the problem is and how to solve it I'll be grateful. Thanks in advance !
namespace Final.Controllers
{
public class AuthenticationController : Controller
{
[HttpGet]
public ActionResult LogIn()
{
return View();
}
[HttpPost]
public ActionResult LogIn(Models.User user)
{
if (IsValid(user.Email, user.Password))
{
FormsAuthentication.SetAuthCookie(user.Email, false);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Login details are wrong.");
}
return View(user);
}
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(Models.User user)
{
try
{
if (ModelState.IsValid)
{
using (AppContext db = new AppContext())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrypPass = crypto.Compute(user.Password);
var newUser = db.Users.Create();
newUser.FirstName = user.FirstName;
newUser.LastName = user.LastName;
newUser.Email = user.Email;
newUser.CompanyName = user.CompanyName;
newUser.Password = encrypPass;
newUser.PasswordSalt = crypto.Salt;
newUser.AdminCode = 0;
user.Password = encrypPass;
user.PasswordSalt = crypto.Salt;
db.Users.Add(newUser);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "Data is not correct");
}
}
catch (DbEntityValidationException e)
{
foreach (var validationErrors in e.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation(
"Class: {0}, Property: {1}, Error: {2}",
validationErrors.Entry.Entity.GetType().FullName,
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}
return View();
}
private bool IsValid(string email, string password)
{
var crypto = new SimpleCrypto.PBKDF2();
bool IsValid = false;
using (AppContext db = new AppContext())
{
var user = db.Users.FirstOrDefault(u => u.Email == email);
if (user != null)
{
if (user.Password == crypto.Compute(user.PasswordSalt, password))
{
IsValid = true;
}
}
}
return IsValid;
}
public ActionResult LogOut()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
}
}
Please check the crypto.Compute function parameters. It requires textToHash(which is your password) and salt. You have to interchange the parameters.
you need to modify your IsValid function like this:
private bool IsValid(string email, string password)
{
var crypto = new SimpleCrypto.PBKDF2();
bool IsValid = false;
using (AppContext db = new AppContext())
{
var user = db.Users.FirstOrDefault(u => u.Email == email);
if (user != null)
{
if (user.Password == crypto.Compute(password, user.PasswordSalt))
{
IsValid = true;
}
}
}
return IsValid;
}

MVC EF6 Async delete

In my Controller I have action
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id)
{
clsHost HostDAL = new clsHost();
vw_Host vw_host = await HostDAL.GetByIdAsync(id);
string actionStatus = HostDAL.Delete(vw_host);
TempData["msgHost"] = actionStatus;
return RedirectToAction("Display");
}
Delete method:
public string Delete(vw_Host host)
{
ObjectParameter executionStatus = new ObjectParameter("ExecutionStatus", "");
try
{
using (Entities context = new Entities())
{
string name = HttpContext.Current.User.Identity.Name.ToString();
context.sp_Host_Delete(host.ID, HttpContext.Current.User.Identity.Name.ToString(), executionStatus);
context.SaveChanges();
}
}
catch (Exception ex)
{
using (Entities context = new Entities())
{
context.sp_LogError(this.GetType().Name.ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.Message, HttpContext.Current.User.Identity.Name);
context.SaveChanges();
}
executionStatus.Value = "Error occured. Please contact to Administrator";
}
return executionStatus.Value.ToString();
}
Mi problem is that when I use Async DeleteConfirmed action, in Delete method I got error:
Object reference not set to an instance of an object.
for
HttpContext.Current.User.Identity.Name
On the other hand when I use sync action:
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
clsHost HostDAL = new clsHost();
vw_Host vw_host = HostDAL.GetById(id);
string actionStatus = HostDAL.Delete(vw_host);
TempData["msgHost"] = actionStatus;
return RedirectToAction("Display");
}
Everything is working fine and HttpContext.Current.User.Identity.Name returns no error.
This problem occurs only for Delete action. It works fine for Edit action (even its async).
You could also consider grabbing the user before your async calls and pass it as an argument to the delete method.
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id) {
var name = "Unknown";
try {
name = HttpContext.Current.User.Identity.Name.ToString();
}catch { }
clsHost HostDAL = new clsHost();
vw_Host vw_host = await HostDAL.GetByIdAsync(id);
string actionStatus = HostDAL.Delete(vw_host, name);
TempData["msgHost"] = actionStatus;
return RedirectToAction("Display");
}
Refactored Delete method
public string Delete(vw_Host host, string name) {
ObjectParameter executionStatus = new ObjectParameter("ExecutionStatus", "");
try {
using (Entities context = new Entities()) {
context.sp_Host_Delete(host.ID, name, executionStatus);
context.SaveChanges();
}
} catch (Exception ex) {
using (Entities context = new Entities()) {
context.sp_LogError(this.GetType().Name.ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.Message, name);
context.SaveChanges();
}
executionStatus.Value = "Error occured. Please contact to Administrator";
}
return executionStatus.Value.ToString();
}

C# MVC 5 User.Identity.Name is null after SignInAsync

I am developing an MVC 5 app for my company, and I am stuck on how to customize my login style. Here we go...
public async Task<ActionResult> Login(LoginViewModel model, string userType)
{
bool checkLDAP = AuthenticateUser("corp.mycorp.go.id", model.UserName, model.Password);
if (ModelState.IsValid)
{
try
{
if (userType== "01")
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
var externalUser = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);
if (externalUser==SignInStatus.Success)
{
string idUser = ValidationHelper.GetIdUser(User.Identity.Name);
string idRole = ValidationHelper.GetRoleCode(idUser);
SessionHelper.SetSessionObject("ActiveRole", idRole);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "User not registered.");
return View(model);
}
}
else if (userType== "02" && checkLDAP == true)
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
ApplicationUser internalUser = await UserManager.FindByNameAsync(model.UserName);
if (internalUser != null)
{
await SignInManager.SignInAsync(internalUser, false,
string idUser = ValidationHelper.GetIdUser(User.Identity.Name);
string idRole = ValidationHelper.GetRoleCode(idUser);
SessionHelper.SetSessionObject("ActiveRole", idRole);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "User not registered.");
return View(model);
}
}
else
{
ModelState.AddModelError("", "Login Failed");
return View(model);
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message.Replace(Environment.NewLine, " "));
return View(model);
}
}
else
{
ModelState.AddModelError("", "Login Failed");
return View(model);
}
}
As you can see, I want to get the User Id with parameter User.Identity.Name
string idUser = ValidationHelper.GetIdUser(User.Identity.Name);
But all I get is null. How can I solve this?
Update :
Here my AuthenticateUser for userType 02
public static bool AuthenticateUser(string pDomainName, string pUserID, string pPassword)
{
bool result = false;
string pServerMessage = "";
DirectoryEntry dir = new DirectoryEntry(string.Format("LDAP://{0}", pDomainName), pUserID, pPassword);
try
{
DirectorySearcher search = new DirectorySearcher(dir);
search.Filter = "(SAMAccountName=" + pUserID + ")";
search.PropertiesToLoad.Add("cn");
search.FindOne();
result = true;
}
catch (Exception ex)
{
pServerMessage = ex.Message;
}
return result;
}
For userType 01, I using default RTM authentication.

Resources