Retrieving Data Depending on the Username - c#

I am doing Authentication depending on the username.So an unauthorized person can't see any methods which is working fine.
The problem is all of the users are able to each others data.
Person A shouldn't see the records of person B so that he/she can't edit another person's records.Does anyone know how I can write a lambda expression for that?
I have my Edit method pasted below:
// GET: /IcerikDB_/Edit/5
[Authorize(Roles = "Administrator")]
public ActionResult Edit(int id)
{
icerik icerik = db.icerik.Find(id);
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
[HttpPost]
public ActionResult Edit(icerik icerik)
{
if (ModelState.IsValid)
{
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
string userName = User.Identity.Name;
var user = db.Users.First(u => u.UserName == userName);
icerik.Userid = user.UserId;
db.Entry(icerik).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
Here is the code for icerik.cs
namespace KategoriEditor.Icerik_DB
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class icerik
{
public int Id { get; set; }
public Nullable<int> Kategorid { get; set; }
public Nullable<System.Guid> Userid { get; set; }
[DataType(DataType.Date)]
public Nullable<System.DateTime> Baslangic { get; set; }
[DataType(DataType.Date)]
public Nullable<System.DateTime> Bitis { get; set; }
public string tamicerik { get; set; }
public string kisaicerik { get; set; }
public string resimlink { get; set; }
public virtual Kategoriler Kategoriler { get; set; }
public virtual Users Users { get; set; }
}
}

Try this:
public ActionResult Edit(int id)
{
// Get the currently logged in user.
string userName = User.Identity.Name;
var user = db.Users.First(u => u.UserName == userName);
// Determine whether the requested id is the same id as the currently logged in user.
icerik icerik = db.icerik.Find(id);
if (icerik.Userid.HasValue && icerik.Userid.Value == user.UserId)
{
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
// You should not need this SelectList anymore.
//ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
// This redirect the unauthorized user to the homepage. This can be any other page of course.
return RedirectToAction("Index", "Home");
}

Related

restricting access to a dropdownlist in C#

Hello I have a 'RestrictAccessController' That looks like this
public class RestrictAccessController : Controller
{
private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
public ActionResult Index()
{
return View ();
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple=true)]
public class RestrictAccessAttribute : ActionFilterAttribute
{
private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
public AccessRestrictions restriction { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// here's where we check that the current action is allowed by the current user
if (!IGT.canAccess(IGT.userId, restriction, false))
{
string url = IGT.baseUrl+"/Home/NotAllowed";
string msg = "This page requires " + IGT.DisplayEnum(restriction) + " access";
filterContext.Result = new RedirectResult("~/Home/NotAllowed?msg="+HttpUtility.HtmlEncode(msg));
}
}
And a Config model that looks like this
public enum AccessRestrictions
{
[Display(Name = "Disposal Orders")]
ModifyDisposalOrder,
[Display(Name = "Admin")]
Admin
}
public class userAccess
{
[Key]
public int ID { get; set; }
public AccessRestrictions restriction { get; set; }
public bool allow { get; set; }
public int userID { get; set; }
}
public class configDetails
{
public int ID {get; set;}
public string Name {get; set;}
public string Value {get;set;}
public bool deleted {get;set;}
public DateTime updateTime { get; set; }
}
public class Config
{
public int ID { get; set; }
[Display(Name = "Configuration Date")]
public DateTime TargetDate { get; set; }
[Display(Name = "Enable Access Restrictions")]
public bool restrictAccess { get; set; }
}
What I want to do is edit what my 'ChangeStatus' dropdown looks like based on whether they have the Admin access restriction or not. Here is the controller method that I want to edit
[RestrictAccess(restriction = AccessRestrictions.ModifyDisposalOrder)]
public ActionResult ChangeStatus(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DisposalOrder disposalOrder = db.disposalOrders.Find(id);
if (disposalOrder == null)
{
return HttpNotFound();
}
switch (disposalOrder.Status)
{
case DOStatus.Pending:
ViewBag.statusList = new List<Object>
{
new {value = DOStatus.Pending, text = "Pending"},
new {value = DOStatus.Disposed, text = "Disposed" }
};
break;
case DOStatus.Disposed:
// if(restriction = AccessRestrictions.ModifyDisposalOrder)
ViewBag.statusList = new List<Object>
{
new {value = DOStatus.Pending, text = "Pending"},
new {value = DOStatus.Disposed, text = "Disposed" }
};
//else
//{
// new { value = DOStatus.Disposed, text = "Disposed" }
// };
break;
};
return View(disposalOrder);
}
Here is my Startup file
public class LdapAuthentication
{
private string _adUser = ConfigurationManager.AppSettings["ADUserName"];
private string _adPW = ConfigurationManager.AppSettings["ADPassword"];
private string _domain = ConfigurationManager.AppSettings["ADDomain"];
public LdapAuthentication() {
}
public string authenticate(string username, string pwd)
{
using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW)) {
//Username and password for authentication.
if (context.ValidateCredentials(username, pwd)) {
UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
Internal internalUser = new Internal {
UserName = user.SamAccountName,
ContactName = user.DisplayName,
Email = user.UserPrincipalName
};
//Search if the user account already exists in the database
PIC_Program_1_0Context db = new PIC_Program_1_0Context();
Internal existing = db.Internals.Where(x => x.UserName == user.SamAccountName).FirstOrDefault();
// If it does not, create a new user account
if (existing == null) {
// add a new Internal entry for this user
existing = new Internal {
UserName = user.SamAccountName,
ContactName = user.DisplayName,
Email = user.UserPrincipalName
};
db.Internals.Add(existing);
db.SaveChanges();
// If it does exist, but some of the data does not match, update the data
} else if(existing != internalUser) {
existing.ContactName = internalUser.ContactName;
existing.Email = internalUser.Email;
db.SaveChanges();
}
return user.SamAccountName;
} else {
return null;
}
}
}
public UserPrincipal getUserPrincipal(string username)
{
using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW))
{
return UserPrincipal.FindByIdentity(context, username);
}
}
Is it possible for me to accomplish this?
Ok, I think I understand your question now. You need to access the User's claims. MVC Controllers have this, half way, built in.
if (User.HasClaim("ClaimNameHere", "Admin"))
{
}
Solved by adding
if (IGT.canAccess(IGT.userId, AccessRestrictions.Admin, false))

How do i confirm the action delete(POST) in my controller?

I have a ViewModel and I would like to make a fonctionnal delete(GET) and deleteConfirmed(POST) so i can delete what ever data is stored in my DB
I don’t know and would like to know what step to take to complete the deleteConfirmed. There is normally auto-generated code but it’s not what I need.
here is my ViewModel
using System;
using ExploFormsDB.Models;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ExploFormsDB.ViewModels
{
public class WorkShiftDetailViewModel
{
[Key]
public int WorkShiftId { get; set; }
public int? HoleId { get; set; }
public string HoleName { get; set; }
public int SurveyLocationId { get; set; }
public int SupplierId { get; set; }
public int ZoneId { get; set; }
public string SurveyLocation1 { get; set; }
public string SupplierName { get; set; }
public string ZoneName { get; set; }
public DateTime StartDay { get; set; }
public DateTime EndDay { get; set; }
public ICollection<WorkerViewModel> WorkShiftEmployees { get; set; }
}
}
Here is my Controller, i have included the Create to help have a better understanding. GET: Delete seems to be working correctly, i am having trouble with the Post. any help what so ever will do. if the question as been answered already please send me a link. I'm pretty new to c# and core and completly new to ViewModels
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(WorkShiftDetailViewModel workShiftDetailViewModel)
{
if (!ModelState.IsValid)
{
WorkShift ws = new WorkShift();
ws.StartDay = workShiftDetailViewModel.StartDay;
ws.EndDay = workShiftDetailViewModel.EndDay;
ws.SupplierId = workShiftDetailViewModel.SupplierId;
ws.SurveyLocationId = 1;
ws.ZoneId = workShiftDetailViewModel.ZoneId;
ws.HoleId = workShiftDetailViewModel.HoleId;
_context.Add(ws);
await _context.SaveChangesAsync();
foreach (WorkerViewModel member in workShiftDetailViewModel.WorkShiftEmployees)
{
if (member.isDeleted == false) {
WorkShiftTeam emp = new WorkShiftTeam();
emp.EmployeeId = member.EmployeeId;
emp.RoleId = member.RoleId;
emp.WorkShiftId = ws.WorkShiftId;
_context.Add(emp);
}
}
HttpContext.Session.SetInt32("wsId", ws.WorkShiftId);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(CreateSharedView));
}
return View(workShiftDetailViewModel);
}
public IActionResult Delete(int? id)
{
if (id == null)
{
return NotFound();
}
List<WorkerViewModel> Workers = new List<WorkerViewModel>();
WorkShift ws = _context.WorkShift.Include(w => w.WorkShiftTeam).SingleOrDefault(x => x.WorkShiftId == id);
WorkShiftDetailViewModel detail = new WorkShiftDetailViewModel();
detail.HoleName = ws.HoleId == null ? "N/A" : _context.Hole.Find(ws.HoleId).HoleName;
detail.StartDay = ws.StartDay;
detail.EndDay = ws.EndDay;
detail.ZoneName = _context.Zone.Find(ws.ZoneId).ZoneName;
detail.SurveyLocation1 = _context.SurveyLocation.Find(ws.SurveyLocationId).SurveyLocation1;
detail.SupplierName = _context.Supplier.Find(ws.SupplierId).SupplierName;
detail.WorkShiftId = ws.WorkShiftId;
int order = 0;
var rolelist = new SelectList(_context.Role, "RoleId", "Role1");
var empsWithFullName = from e in _context.Employee.Where(a => a.IsActive)
select new
{
ID = e.EmployeeId,
FullName = e.LastName + ", " + e.FirstName
};
var empList = new SelectList(empsWithFullName, "ID", "FullName");
foreach (WorkShiftTeam member in ws.WorkShiftTeam.OrderBy(a => a.EmployeeId))
{
Workers.Add(new WorkerViewModel() { EmployeeId = member.EmployeeId, RoleId = member.RoleId, Index = order, Roles = rolelist, Employees = empList });
order++;
}
detail.WorkShiftEmployees = Workers;
return View(detail);
}
// POST: WorkShiftDetailViewModels/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
//??
} ```
Why you created an extra method for delete action as HttpGet? (that occurred conflict)
change it to:
[HttpGet]
public IActionResult GetById(int? id) { ... }
and just one delete method with this definition
[HttpPost]
public async Task<IActionResult> Delete(int? id) { ... }

In a HTML helper dropdownlist, how to get foreign key data?

I am new to ASP.NET. My form look like this
This code display role in Form
#Html.DropDownList("id", (IEnumerable<SelectListItem>)ViewBag.lis, null, new { #class = "form-control" })
in Controller
public ActionResult register()
{ //
ViewBag.lis = new SelectList(new dbdemoEntities().Roles, "id", "name");
return View();
}
ROLE CLASS
public partial class Role
{
public int Id { get; set; }
public string name { get; set; }
public virtual Register Register { get; set; }
}
Register class
public partial class Register
{
public int Id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string password { get; set; }
public Nullable<int> phone_no { get; set; }
public virtual Role Role { get; set; }
}
The problem is that I can get all data except for Role. The role is null. How do I get the Role ID?
[HttpPost]
public ActionResult register(Register obj)
{
using(var db = new dbdemoEntities())
{
var data = new Register()
{
email = obj.email,
name = obj.name,
password = obj.password,
phone_no = obj.phone_no,
Role = obj.Role
};
db.Registers.Add(data);
db.SaveChanges();
ViewBag.register = "Your account has been registered!";
}
return PartialView();
}
I think the problem is that I should write model => model.role like the example of the name here.
#Html.EditorFor(model => model.name, new { htmlAttributes = new { #class = "form-control" } })
here is what I updated now
ViewBag.lis = new SelectList(new dbdemoEntities().Roles, "Id", "name");
In HTML
Problem after update:
After changing
Role = db.Roles.Single(r => r.Id == obj.Role.Id)
Here is another error
Try this:
Change: ViewBag.lis = new SelectList(new dbdemoEntities().Roles, "id", "name");
to
ViewBag.lis = new SelectList(new dbdemoEntities().Roles, "Id", "name");
and then:
#Html.DropDownList(model => model.Role.Id, (IEnumerable<SelectListItem>)ViewBag.lis, null, new { #class = "form-control" })
and also make a constructor for Register class:
public partial class Register
{
public Register()
{
this.Role = new Role();
}
public int Id { get; set; }
public string name { get; set; }
public string email { get; set; }
public string password { get; set; }
public Nullable<int> phone_no { get; set; }
public virtual Role Role { get; set; }
}
====== Update =======
Change the action like this:
[HttpPost]
public ActionResult register(Register obj)
{
using(var db = new dbdemoEntities())
{
var data = new Register()
{
email = obj.email,
name = obj.name,
password = obj.password,
phone_no = obj.phone_no,
Role = db.Roles.Single(r=> r.Id == obj.Role.Id)
};
db.Registers.Add(data);
db.SaveChanges();
ViewBag.register = "Your account has been registered!";
}
return PartialView();
}
Change to this this if you want to post Register.Id property:
#Html.DropDownListFor(model => model.Id,(SelectList) ViewBag.list,new { #class="form-control"})

MVC The INSERT statement conflicted with the FOREIGN KEY constraint

When I try to create a ticket on my create.cshtml it gives me this error. I think it's because my Category uses a dropdownlist using ViewBags while my User and Administrator dropdown list doesn't.
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_dbo.Ticket_dbo.Category_CategoryID". The conflict occurred in
database "RecreationalServicesTicketingSystem.DAL.IssueContext", table
"dbo.Category", column 'CategoryID'. The statement has been
terminated.
TicketController.cs
public class TicketController : Controller
{
private IssueContext db = new IssueContext();
public ActionResult Create()
{
TicketVM model = new TicketVM();
ConfigureViewModel(model);
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName");
ViewBag.AllUsers = db.Users.ToList().Select(u => new SelectListItem() { Value = u.UserID.ToString(), Text = string.Format("{0} {1}", u.FirstMidName, u.LastName) });
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(TicketVM model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model);
return View(model);
}
Ticket ticket = new Ticket
{
Issue = model.Issue,
IssuedTo = model.IssuedTo
};
if (ModelState.IsValid)
{
db.Tickets.Add(ticket);
ERROR------> db.SaveChanges(); <------ ERROR
return View();
}
ViewBag.CategoryID = new SelectList(db.Categories, "CategoryID", "CategoryName", ticket.CategoryID);
ViewBag.AllUsers = db.Users.ToList().Select(u => new SelectListItem() { Value = u.UserID.ToString(), Text = string.Format("{0} {1}", u.FirstMidName, u.LastName) });
ViewBag.AllAdmins = db.Users.Where(u => u.IsAdministrator).Include(u => u.Tickets);
return View(ticket);
}
private void ConfigureViewModel(TicketVM model)
{
IEnumerable<User> admins = db.Users.Where(u => u.IsAdministrator).OrderBy(u => u.LastName);
model.AdministratorList = admins.Select(a => new SelectListItem
{
Value = a.UserID.ToString(),
Text = string.Format("{0} {1}", a.FirstMidName, a.LastName)
});
}
}
\Views\Ticket\Create.cshtml
#model RecreationalServicesTicketingSystem.ViewModels.TicketVM
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Ticket</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CategoryID, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryID", String.Empty)
#Html.ValidationMessageFor(model => model.CategoryID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserID, "User")
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.UserID, (IEnumerable<SelectListItem>)ViewBag.AllUsers, "Please select")`
#Html.ValidationMessageFor(model => model.UserID)
</div>
<div class="editor-field">
#using (Html.BeginForm())
{
#Html.HiddenFor(m => m.UserID)
<div class="form-group">
#Html.LabelFor(m => m.IssuedTo)
#Html.DropDownListFor(m => m.IssuedTo, Model.AdministratorList, "Please select", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.IssuedTo)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Issue)
#Html.TextBoxFor(m => m.Issue, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Issue)
</div>
}
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Category.cs
public class Category
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
Ticket.cs
public enum Priority
{
Low, Med, High
}
public class Ticket
{
public int? TicketID { get; set; }
[Required(ErrorMessage = "Please enter the description")]
public string Issue { get; set; }
[Display(Name = "Administrator")]
[Required(ErrorMessage = "Please select the Administrator")]
public int IssuedTo { get; set; }
public int Author { get; set; }
[DisplayFormat(NullDisplayText = "No Priority")]
public Priority? Priority { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category { get; set; }
public int CategoryID { get; set; }
public int UserID { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; }
}
ViewModels\TicketVM.cs
public class TicketVM
{
public int? UserID { get; set; }
[Required(ErrorMessage = "Please enter the description")]
public string Issue { get; set; }
[Display(Name = "Administrator")]
[Required(ErrorMessage = "Please select the Administrator")]
public int IssuedTo { get; set; }
public IEnumerable<SelectListItem> AdministratorList { get; set; }
public int CategoryID { get; set; }
}
AccountController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using RecreationalServicesTicketingSystem.Filters;
using RecreationalServicesTicketingSystem.Models;
namespace RecreationalServicesTicketingSystem.Controllers
{
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
WebSecurity.Logout();
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
try
{
WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Home");
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/Disassociate
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Disassociate(string provider, string providerUserId)
{
string ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId);
ManageMessageId? message = null;
// Only disassociate the account if the currently logged in user is the owner
if (ownerAccount == User.Identity.Name)
{
// Use a transaction to prevent the user from deleting their last login credential
using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
{
bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
if (hasLocalAccount || OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1)
{
OAuthWebSecurity.DeleteAccount(provider, providerUserId);
scope.Complete();
message = ManageMessageId.RemoveLoginSuccess;
}
}
}
return RedirectToAction("Manage", new { Message = message });
}
//
// GET: /Account/Manage
public ActionResult Manage(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: "";
ViewBag.HasLocalPassword = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.ReturnUrl = Url.Action("Manage");
return View();
}
//
// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Manage(LocalPasswordModel model)
{
bool hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
ViewBag.HasLocalPassword = hasLocalAccount;
ViewBag.ReturnUrl = Url.Action("Manage");
if (hasLocalAccount)
{
if (ModelState.IsValid)
{
// ChangePassword will throw an exception rather than return false in certain failure scenarios.
bool changePasswordSucceeded;
try
{
changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("Manage", new { Message = ManageMessageId.ChangePasswordSuccess });
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
}
else
{
// User does not have a local password so remove any validation errors caused by a missing
// OldPassword field
ModelState state = ModelState["OldPassword"];
if (state != null)
{
state.Errors.Clear();
}
if (ModelState.IsValid)
{
try
{
WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);
return RedirectToAction("Manage", new { Message = ManageMessageId.SetPasswordSuccess });
}
catch (Exception)
{
ModelState.AddModelError("", String.Format("Unable to create local account. An account with the name \"{0}\" may already exist.", User.Identity.Name));
}
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return RedirectToAction("ExternalLoginFailure");
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return RedirectToLocal(returnUrl);
}
if (User.Identity.IsAuthenticated)
{
// If the current user is logged in add the new account
OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
return RedirectToLocal(returnUrl);
}
else
{
// User is new, ask for their desired membership name
string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLoginConfirmation(RegisterExternalLoginModel model, string returnUrl)
{
string provider = null;
string providerUserId = null;
if (User.Identity.IsAuthenticated || !OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, out provider, out providerUserId))
{
return RedirectToAction("Manage");
}
if (ModelState.IsValid)
{
// Insert a new user into the database
using (UsersContext db = new UsersContext())
{
UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == model.UserName.ToLower());
// Check if user already exists
if (user == null)
{
// Insert name into the profile table
db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
db.SaveChanges();
OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.");
}
}
}
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName;
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
[AllowAnonymous]
[ChildActionOnly]
public ActionResult ExternalLoginsList(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
}
[ChildActionOnly]
public ActionResult RemoveExternalLogins()
{
ICollection<OAuthAccount> accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
List<ExternalLogin> externalLogins = new List<ExternalLogin>();
foreach (OAuthAccount account in accounts)
{
AuthenticationClientData clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider);
externalLogins.Add(new ExternalLogin
{
Provider = account.Provider,
ProviderDisplayName = clientData.DisplayName,
ProviderUserId = account.ProviderUserId,
});
}
ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
return PartialView("_RemoveExternalLoginsPartial", externalLogins);
}
#region Helpers
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
public enum ManageMessageId
{
ChangePasswordSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
}
internal class ExternalLoginResult : ActionResult
{
public ExternalLoginResult(string provider, string returnUrl)
{
Provider = provider;
ReturnUrl = returnUrl;
}
public string Provider { get; private set; }
public string ReturnUrl { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
}
}
private static string ErrorCodeToString(MembershipCreateStatus createStatus)
{
// See http://go.microsoft.com/fwlink/?LinkID=177550 for
// a full list of status codes.
switch (createStatus)
{
case MembershipCreateStatus.DuplicateUserName:
return "User name already exists. Please enter a different user name.";
case MembershipCreateStatus.DuplicateEmail:
return "A user name for that e-mail address already exists. Please enter a different e-mail address.";
case MembershipCreateStatus.InvalidPassword:
return "The password provided is invalid. Please enter a valid password value.";
case MembershipCreateStatus.InvalidEmail:
return "The e-mail address provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidAnswer:
return "The password retrieval answer provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidQuestion:
return "The password retrieval question provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.InvalidUserName:
return "The user name provided is invalid. Please check the value and try again.";
case MembershipCreateStatus.ProviderError:
return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
case MembershipCreateStatus.UserRejected:
return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
default:
return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
}
}
#endregion
}
}
Models\AccountModels.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Security;
namespace RecreationalServicesTicketingSystem.Models
{
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
}
public class RegisterExternalLoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
public string ExternalLoginData { get; set; }
}
public class LocalPasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LoginModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ExternalLogin
{
public string Provider { get; set; }
public string ProviderDisplayName { get; set; }
public string ProviderUserId { get; set; }
}
}

How can i get the correct information to display in my listbox?

I have two Listboxes where you can move exercises from an available list of exercises to a list of selected exercises for a specific user. My current problem is that my selected list (aka RegimeItems) shows the exercises for all of the users.
I believe the problem lies in ChosenExercises(at the bottom of controller) i am also getting a null reference exception at:
var regimeIDs = model.SavedRequested.Split(',').Select(x => int.Parse(x));
Controller.cs
[HttpGet]
public ActionResult ExerciseIndex(int? id, UserExerciseViewModel vmodel)
{
User user = db.Users.Find(id);
user.RegimeItems = ChosenExercises();
UserExerciseViewModel model = new UserExerciseViewModel { AvailableExercises = GetAllExercises(), RequestedExercises = ChosenExercises(user, vmodel) };
user.RegimeItems = model.RequestedExercises;
return View(model);
}
[HttpPost]
public ActionResult ExerciseIndex(UserExerciseViewModel model, string add, string remove, string send, int id)
{
User user = db.Users.Find(id);
user.RegimeItems = model.RequestedExercises;;
RestoreSavedState(model);
if (!string.IsNullOrEmpty(add))
AddExercises(model, id);
else if (!string.IsNullOrEmpty(remove))
RemoveExercises(model, id);
SaveState(model);
return View(model);
}
void SaveState(UserExerciseViewModel model)
{
model.SavedRequested = string.Join(",", model.RequestedExercises.Select(p => p.RegimeItemID.ToString()).ToArray());
model.AvailableExercises = GetAllExercises().ToList();
}
void RestoreSavedState(UserExerciseViewModel model)
{
model.RequestedExercises = new List<RegimeItem>();
//get the previously stored items
if (!string.IsNullOrEmpty(model.SavedRequested))
{
string[] exIds = model.SavedRequested.Split(',');
var exercises = GetAllExercises().Where(p => exIds.Contains(p.ExerciseID.ToString()));
model.AvailableExercises.AddRange(exercises);
}
}
private List<Exercise> GetAllExercises()
{
return db.Exercises.ToList();
}
private List<RegimeItem> ChosenExercises(User user, UserExerciseViewModel model)//RegimeItem regimeItem)
{
var regimeIDs = model.SavedRequested.Split(',').Select(x => int.Parse(x));
return db.RegimeItems.Where(e => regimeIDs.Contains(e.RegimeItemID)).ToList();
//return db.Users.Where(r => r.RegimeItems = user.UserID);
//return db.Users.Where(r => r.RegimeItems.RegimeItemID == user.UserID);
}
Models
public class User
{
public int UserID { get; set; }
public ICollection<RegimeItem> RegimeItems { get; set; }
public User()
{
this.RegimeItems = new List<RegimeItem>();
}
}
public class RegimeItem
{
public int RegimeItemID { get; set; }
public Exercise RegimeExercise { get; set; }
}
ViewModel
public class UserExerciseViewModel
{
public List<Exercise> AvailableExercises { get; set; }
public List<RegimeItem> RequestedExercises { get; set; }
public int? SelectedExercise { get; set; }
public int[] AvailableSelected { get; set; }
public int[] RequestedSelected { get; set; }
public string SavedRequested { get; set; }
}
Try changing
return db.Users.Where(r => r.RegimeItems = user.UserID);
to
return db.Users.Where(r => r.RegimeItems.RegimeItemID == user.UserID);
Because the way I read it you're currently trying to match an int with an object.
edit: Another error was resulted which the OP found himself.
"It seems that RegimeItems is a collection of RegimeItem - it does not have a have a single ID. So it needed to be .Where(u => u.UserID == user.UserID) and then to select the regimeItems associated with the user .SelectMany(u => u.RegimeItems).ToList(); Thanks for your help, if you update your answer with that i will mark yours as the correct answer." -Nilmag
Firstly, you're going to want to update the calls to ChosenExercises() in ExcerciseIndex(int? id) to pass in the user like this: ChosenExercises(user).
Secondly, the conversion error is because you are comparing r.RegimeItems to the User ID, which is an int. In order to return a list of regime items for the user you'll need to query the Excercises table, rather than the users table:
private List<RegimeItem> ChosenExercises(User user)//RegimeItem regimeItem)//User user, RegimeItem regimeItem)
{
var regimeIDs = user.SavedRequested.Split(',').Select(x=>int.Parse(x));
return db.RegimeItem.Where(e=> regimeIDs.Contains(e.RegimeItemID)).ToList();
}

Categories