Assert.AreEqual failed on two identical MVC ViewModel results? - asp.net-mvc

I got this error on my unit test:
Assert.AreEqual failed. Expected:<ShizoMe.Web.ViewModel.AccountViewModel>. Actual:<ShizoMe.Web.ViewModel.AccountViewModel>.
This is the code for my test:
[TestMethod]
public void Register_Prevents_Duplicate_Users()
{
var controller = GetAccountController();
var model = new AccountViewModel
{
Register = new RegisterModel
{
EmailAddress = "testUser#test.com"
}
};
var result = (ViewResult) controller.Register(model.Register);
Assert.AreEqual("A user with this email address already exists.",
controller.ModelState["UserExists"].Errors[0].ErrorMessage);
Assert.AreEqual(model, result.ViewData.Model);
}
This is my Register method:
[HttpPost]
public virtual ActionResult Register([Bind(Prefix = "Register")]RegisterModel model)
{
var accountModel = new AccountViewModel();
if (ModelState.IsValid)
{
if (_accountRepository.GetUser(model.EmailAddress) != null)
{
ModelState.AddModelError("UserExists", "A user with this email address already exists.");
return View(accountModel);
}
var newUser = new User
{
EmailAddress = model.EmailAddress,
Password = model.Password,
CreatedDate = DateTime.UtcNow
};
if (_accountRepository.RegisterUser(newUser))
{
_formsService.SignIn(newUser);
return RedirectToAction(MVC.Home.Index());
}
}
return View(accountModel);
}
Any idea why the last Assert.AreEqual failed? When I debug, the ViewModels (model and result.ViewData.Model) are the same.
Thank you very much.

Is AccountViewModel IEquatable? If not, C# will just use Object.ReferenceEquals to compare them. That will only be true if they both reference to the exactly same object (have the same property values is not good enough).

Did you override the Equals() and GetHashCode() methods for your AccountViewModel class?
example:
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (Object.ReferenceEquals(this, obj))
{
return true;
}
if (this.GetHashCode() == obj.GetHashCode())
{
return true;
}
return false;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}

Related

ASP.NET Core [FromBody] vs MVC 5 binding

I got an MVC 5 application that i'm porting to asp.net Core.
In the MVC application call to controller we're made using AngularJS $resource (sending JSON) and we we're POSTing data doing :
ressource.save({ entries: vm.entries, projectId: vm.project.id }).$promise...
that will send a JSON body like:
{
entries:
[
{
// lots of fields
}
],
projectId:12
}
the MVC controller looked like this :
[HttpPost]
public JsonResult Save(List<EntryViewModel> entries, int projectId) {
// code here
}
How can I replicate the same behaviour with .NET Core since we can't have multiple [FromBody]
you cannot have multiple parameter with the FromBody attibute in an action method. If that is need, use a complex type such as a class with properties equivalent to the parameter or dynamic type like that
[HttpPost("save/{projectId}")]
public JsonResult Save(int projectId, [FromBody] dynamic entries) {
// code here
}
As pointed out in the comment, one possible solution is to unify the properties you're posting onto a single model class.
Something like the following should do the trick:
public class SaveModel
{
public List<EntryViewModel> Entries{get;set;}
public int ProjectId {get;set;}
}
Don't forget to decorate the model with the [FromBody] attribute:
[HttpPost]
public JsonResult Save([FromBody]SaveViewModel model)
{
// code here
}
Hope this helps!
It's still rough but I made a Filter to mimic the feature.
public class OldMVCFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.Request.Method != "GET")
{
var body = context.HttpContext.Request.Body;
JToken token = null;
var param = context.ActionDescriptor.Parameters;
using (var reader = new StreamReader(body))
using (var jsonReader = new JsonTextReader(reader))
{
jsonReader.CloseInput = false;
token = JToken.Load(jsonReader);
}
if (token != null)
{
var serializer = new JsonSerializer();
serializer.DefaultValueHandling = DefaultValueHandling.Populate;
serializer.FloatFormatHandling = FloatFormatHandling.DefaultValue;
foreach (var item in param)
{
JToken model = token[item.Name];
if (model == null)
{
// try to cast the full body as the current object
model = token.Root;
}
if (model != null)
{
model = this.RemoveEmptyChildren(model, item.ParameterType);
var res = model.ToObject(item.ParameterType, serializer);
context.ActionArguments[item.Name] = res;
}
}
}
}
}
private JToken RemoveEmptyChildren(JToken token, Type type)
{
var HasBaseType = type.GenericTypeArguments.Count() > 0;
List<PropertyInfo> PIList = new List<PropertyInfo>();
if (HasBaseType)
{
PIList.AddRange(type.GenericTypeArguments.FirstOrDefault().GetProperties().ToList());
}
else
{
PIList.AddRange(type.GetTypeInfo().GetProperties().ToList());
}
if (token != null)
{
if (token.Type == JTokenType.Object)
{
JObject copy = new JObject();
foreach (JProperty jProp in token.Children<JProperty>())
{
var pi = PIList.FirstOrDefault(p => p.Name == jProp.Name);
if (pi != null) // If destination type dont have this property we ignore it
{
JToken child = jProp.Value;
if (child.HasValues)
{
child = RemoveEmptyChildren(child, pi.PropertyType);
}
if (!IsEmpty(child))
{
if (child.Type == JTokenType.Object || child.Type == JTokenType.Array)
{
// nested value has been checked, we add the object
copy.Add(jProp.Name, child);
}
else
{
if (!pi.Name.ToLowerInvariant().Contains("string"))
{
// ignore empty value when type is not string
var Val = (string)child;
if (!string.IsNullOrWhiteSpace(Val))
{
// we add the property only if it contain meningfull data
copy.Add(jProp.Name, child);
}
}
}
}
}
}
return copy;
}
else if (token.Type == JTokenType.Array)
{
JArray copy = new JArray();
foreach (JToken item in token.Children())
{
JToken child = item;
if (child.HasValues)
{
child = RemoveEmptyChildren(child, type);
}
if (!IsEmpty(child))
{
copy.Add(child);
}
}
return copy;
}
return token;
}
return null;
}
private bool IsEmpty(JToken token)
{
return (token.Type == JTokenType.Null || token.Type == JTokenType.Undefined);
}
}

How to create a unique session for a user: ASP.NET

I have been learning ASP.NET and came to point where I realised that my web application is creating only a static session for all the users, that is if one logs out all the users are logged out, and sometimes the session is even swapped (lets say userA logs in and right after userB logs in, when the userA refreshes he is seeing the data of userB).
My SessionManager class is as below
SessionManager.cs
public class SessionManager
{
#region Private Data
private static String USER_KEY = "user";
#endregion
public static Employee CurrentUser
{
get;
set;
}
public static string UserType
{
get;
set;
}
public static Int32 SessionTimeout
{
get
{
return System.Web.HttpContext.Current.Session.Timeout;
}
}
public static String GetUserFullName()
{
if (SessionManager.CurrentUser != null)
return SessionManager.CurrentUser.FirstName;
else
return null;
}
public static Boolean IsUserLoggedIn
{
get
{
if (SessionManager.CurrentUser != null)
return true;
else
return false;
}
}
#region Methods
public static void AbandonSession()
{
for (int i = 0; i < System.Web.HttpContext.Current.Session.Count; i++)
{
System.Web.HttpContext.Current.Session[i] = null;
}
System.Web.HttpContext.Current.Session.Abandon();
}
#endregion
}
Login Controller:
[HttpPost]
public ActionResult Index(String txtUserName, String txtPassword)
if (User.Identity.IsAuthenticated)
{
return View();
}
else
{
if (ModelState.IsValid)
{
Employee obj = (from o in db.Employees
where o.Email == txtUserName && o.Password == txtPassword
select o).FirstOrDefault();
if (obj != null)
{
var dh = db.Departments.Where(x => x.LeadBy == obj.EmployeeId).FirstOrDefault();
var tl = db.Teams.Where(x => x.LeadBy == obj.EmployeeId).FirstOrDefault();
if (dh == null && tl == null)
{
Session["UserType"] = "EMP";
}
else if (dh != null && tl != null)
{
Session["UserType"] = "DH&TL";
}
else if (dh != null)
{
Session["UserType"] = "DH";
}
else if (tl != null)
{
Session["UserType"] = "TL";
}
SessionManager.CurrentUser = obj; //how can I create different obj for different users here?
var currentEnrollID = SessionManager.CurrentUser.EnrollNumber;
var currentEmployeeID = SessionManager.CurrentUser.EmployeeId;
var currentEmpName = SessionManager.CurrentUser.FirstName + " " + SessionManager.CurrentUser.LastName;
I have been using sessions like this in the whole application so a different approach would be hectic to amend the changes.
public ActionResult Logout()
{
if (SessionManager.IsUserLoggedIn)
{
SessionManager.CurrentUser.EmployeeId = 0;
SessionManager.AbandonSession();
Session.Clear();
Session.Abandon();
Session.RemoveAll();
}
return RedirectToAction("Index","Login");
}
This is not related to ASP.NET, but it is more on how static members work.
The real issue is your SessionsManager, which contains static methods that you store values every time the user logs-in. This means the same instance is shared across different session in the application.
I have an update SessionManager you can see below. I have stored the SessionManager object in the session object so that as long the session is alive. It will return the same instance by session when you call it using SessionManager.Current.
public class SessionManager {
#region Private Data
private static String USER_KEY = "user";
#endregion
public static SessionManager Current {
get{
if (HttpContext.Current.Session[USER_KEY] != null) {
return (SessionManager) HttpContext.Current.Session[USER_KEY];
} else {
var sess = new SessionManager ();
HttpContext.Current.Session[USER_KEY] = sess;
return sess;
}
}
}
public Employee CurrentUser {
get;
set;
}
public string UserType {
get;
set;
}
public Int32 SessionTimeout {
get {
return System.Web.HttpContext.Current.Session.Timeout;
}
}
public String GetUserFullName () {
if (SessionManager.Current.CurrentUser != null)
return SessionManager.Current.CurrentUser.FirstName;
else
return null;
}
public Boolean IsUserLoggedIn {
get {
if (SessionManager.Current.CurrentUser != null)
return true;
else
return false;
}
}
#region Methods
public void AbandonSession () {
for (int i = 0; i < System.Web.HttpContext.Current.Session.Count; i++) {
System.Web.HttpContext.Current.Session[i] = null;
}
System.Web.HttpContext.Current.Session.Abandon ();
}
#endregion
}

Get custom attribute for parameter when model binding

I've seen a lot of similar posts on this, but haven't found the answer specific to controller parameters.
I've written a custom attribute called AliasAttribute that allows me to define aliases for parameters during model binding. So for example if I have: public JsonResult EmailCheck(string email) on the server and I want the email parameter to be bound to fields named PrimaryEmail or SomeCrazyEmail I can "map" this using the aliasattribute like this: public JsonResult EmailCheck([Alias(Suffix = "Email")]string email).
The problem: In my custom model binder I can't get a hold of the AliasAttribute class applied to the email parameter. It always returns null.
I've seen what the DefaultModelBinder class is doing to get the BindAttribute in reflector and its the same but doesn't work for me.
Question: How do I get this attribute during binding?
AliasModelBinder:
public class AliasModelBinder : DefaultModelBinder
{
public static ICustomTypeDescriptor GetTypeDescriptor(Type type)
{
return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
}
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = base.BindModel(controllerContext, bindingContext);
var descriptor = GetTypeDescriptor(bindingContext.ModelType);
/*************************/
// this next statement returns null!
/*************************/
AliasAttribute attr = (AliasAttribute)descriptor.GetAttributes()[typeof(AliasAttribute)];
if (attr == null)
return null;
HttpRequestBase request = controllerContext.HttpContext.Request;
foreach (var key in request.Form.AllKeys)
{
if (string.IsNullOrEmpty(attr.Prefix) == false)
{
if (key.StartsWith(attr.Prefix, StringComparison.InvariantCultureIgnoreCase))
{
if (string.IsNullOrEmpty(attr.Suffix) == false)
{
if (key.EndsWith(attr.Suffix, StringComparison.InvariantCultureIgnoreCase))
{
return request.Form.Get(key);
}
}
return request.Form.Get(key);
}
}
else if (string.IsNullOrEmpty(attr.Suffix) == false)
{
if (key.EndsWith(attr.Suffix, StringComparison.InvariantCultureIgnoreCase))
{
return request.Form.Get(key);
}
}
if (attr.HasIncludes)
{
foreach (var include in attr.InlcludeSplit)
{
if (key.Equals(include, StringComparison.InvariantCultureIgnoreCase))
{
return request.Form.Get(include);
}
}
}
}
return null;
}
}
AliasAttribute:
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class AliasAttribute : Attribute
{
private string _include;
private string[] _inlcludeSplit = new string[0];
public string Prefix { get; set; }
public string Suffix { get; set; }
public string Include
{
get
{
return _include;
}
set
{
_include = value;
_inlcludeSplit = SplitString(_include);
}
}
public string[] InlcludeSplit
{
get
{
return _inlcludeSplit;
}
}
public bool HasIncludes { get { return InlcludeSplit.Length > 0; } }
internal static string[] SplitString(string original)
{
if (string.IsNullOrEmpty(original))
{
return new string[0];
}
return (from piece in original.Split(new char[] { ',' })
let trimmed = piece.Trim()
where !string.IsNullOrEmpty(trimmed)
select trimmed).ToArray<string>();
}
}
Usage:
public JsonResult EmailCheck([ModelBinder(typeof(AliasModelBinder)), Alias(Suffix = "Email")]string email)
{
// email will be assigned to any field suffixed with "Email". e.g. PrimaryEmail, SecondaryEmail and so on
}
Gave up on this and then stumbled across the Action Parameter Alias code base that will probably allow me to do this. It's not as flexible as what I started out to write but probably can be modified to allow wild cards.
what I did was make my attribute subclass System.Web.Mvc.CustomModelBinderAttribute which then allows you to return a version of your custom model binder modified with the aliases.
example:
public class AliasAttribute : System.Web.Mvc.CustomModelBinderAttribute
{
public AliasAttribute()
{
}
public AliasAttribute( string alias )
{
Alias = alias;
}
public string Alias { get; set; }
public override IModelBinder GetBinder()
{
var binder = new AliasModelBinder();
if ( !string.IsNullOrEmpty( Alias ) )
binder.Alias = Alias;
return binder;
}
}
which then allows this usage:
public ActionResult Edit( [Alias( "somethingElse" )] string email )
{
// ...
}

asp.net mvc 3 dependency injection ninject

I want to ask something about asp.net mvc 3 dependency injection ninject.
Here is my Interface,
public interface IRegistration<T>
{
bool Registration(T Entity);
}
This is ClsMembers class.
public class ClsMembers:IRegistration<Member>
{
private SmileWorkDbEntities db;
public ClsMembers()
{
db = new SmileWorkDbEntities();
}
public bool Registration(Member member)
{
db.Members.Add(member);
if (db.SaveChanges() != 0)
{
return true;
}
else
{
return false;
}
}
public int GetMemberId(string username, string pwd)
{
var Mem = (from m in db.Members where m.Member_username == username && m.Member_password == pwd select m).FirstOrDefault();
return Mem.Member_id;
}
}
here is my controller,
public class MembersRegistrationController : Controller
{
IRegistration<Member> ireg1;
public MembersRegistrationController(IRegistration<Member> _ireg1)
{
ireg1 = _ireg1;
}
public ActionResult MemberRegistration()
{
return View();
}
[HttpPost]
public ActionResult MemberRegistration(Member m)
{
if(ireg1.Registration(m))
{
return RedirectToAction("MemberProfileRegistration", new {mId = i });
}
else
{
return View();
}
}
}
Everything is ok... but i cannot access GetMemberId() method.. pls tell me how can i access GetMemberId() from my controller...
Regard,
MinThitTun
Modify your IRegistration interface by adding int GetMemberId(string username, string pwd) method:
public interface IRegistration<T>
{
bool Registration(T Entity);
int GetMemberId(string username, string pwd);
}
After all, I thing you should read Interfaces (C# Programming Guide)
UPDATE:
public interface IMembersRepository
{
int GetMemberId(string username, string password);
// Other stuff related to members...
}
public class MembersRepository : IMembersRepository
{
private SmileWorkDbEntities db = new SmileWorkDbEntities();
public int GetMemberId(string username, string password)
{
var Mem = (from m in db.Members where m.Member_username == username && m.Member_password == pwd select m).FirstOrDefault();
return Mem.Member_id;
}
// Other stuff related to members...
}
public class MembersRegistrationController : Controller
{
IRegistration<Member> ireg1;
IMembersRepository membersRepository;
public MembersRegistrationController(IRegistration<Member> _ireg1, IMembersRepository memRepository)
{
ireg1 = _ireg1;
membersRepository = memRepository;
}
// ...
}

Authorize Attribute Not Working with Roles MVC C#

I'm modifying a system written in c# MVC at the moment.
I've just built in an extra bit of functionality in the Administrator area that allows the administrator create a user account that has limited administrator functionality. I've put the following over each of the controllers for the new functionality:
[Authorize(Roles = "Administrator")]
However, if I log in using limited administrator account, and navigate to this page, it lets me through.
I'm stumped because I appear to be doing this the right way but I'm also fairly new to MVC, is there anything else I can check? I haven't changed anything in the web.config file so that should be ok.
I know there's limited information above, not looking for a ready-made solution, more advice on what I can check to correct the issue.
thanks
EDIT:
This is how the new role/account was created. Go easy too, this is a first ditch attempt, there's not much validation.
[Authorize(Roles = "Administrator")]
[HttpPost]
public ActionResult AddSalesManager(App.Web.Areas.Administrator.Models.SalesManager model, FormCollection formValues)
{
if (formValues["Cancel"] != null)
{
return RedirectToAction("Index");
}
if (!string.Equals(model.password, model.confirmpassword))
{
ModelState.AddModelError("password", "Password and Confirmation must match");
}
if (ModelState.IsValid)
{
using (ModelContainer ctn = new ModelContainer())
{
// First, create the user account inside the ASP.Net membership system.
//
Membership.ApplicationName = "App";
Roles.ApplicationName = "App";
if (!Roles.RoleExists("LimitedAdmin"))
Roles.CreateRole("LimitedAdmin");
// MembershipCreateStatus createStatus = MembershipService.CreateUser(model.email, model.password, model.email);
if (Membership.GetUser(model.email) == null)
{
Membership.CreateUser(model.email, model.password);
Roles.AddUserToRole(model.email, "LimitedAdmin");
}
}
}
return RedirectToAction("Index");
}
Role attribute
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class PermissionsAttribute : ActionFilterAttribute
{
private readonly PermissionsType required;
public PermissionsAttribute()
{
}
public PermissionsAttribute(PermissionsType required)
{
this.required = required;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Log("OnActionExecuting", filterContext.RouteData);
HttpSessionStateBase session = filterContext.HttpContext.Session;
Controller controller = filterContext.Controller as Controller;
//This is uesd to redirect to same controller but differnect action
// controller.HttpContext.Response.Redirect("./Login");
var rjasthan = filterContext;
var URK = filterContext.HttpContext.Request.RawUrl;
if (session["UserPermissions"] != null)
{
if (!CheckPermissions((UserPermission)session["UserPermissions"]))
{
// this is used to signout from sesssion
// filterContext.HttpContext.GetOwinContext().Authentication.SignOut();
filterContext.Controller.TempData["AuthenticationMessages"] = "You are not authorized to access";
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary{
{ "controller", "Home" },{ "action", "UnAuthorizeAccess" }});
}
}
base.OnActionExecuting(filterContext);
}
protected bool CheckPermissions(UserPermission model)
{
bool result = false;
if (this.required == (PermissionsType.Add))
{
if (model.AddRight)
result = true;
}
else if (this.required == (PermissionsType.View))
{
if (model.ViewRight)
result = true;
}
else if (this.required == (PermissionsType.Edit))
{
if (model.EditRight)
result = true;
}
else if (this.required == (PermissionsType.Delete))
{
if (model.DeleteRight)
result = true;
}
else if (this.required == (PermissionsType.View | PermissionsType.Edit))
{
if (model.ViewRight && model.EditRight)
{
result = true;
}
}
else if (this.required == (PermissionsType.Add | PermissionsType.Edit))
{
if (model.AddRight && model.EditRight)
{
result = true;
}
}
return result;
}
private void Log(string methodName, RouteData routeData)
{
var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
}
}
[Flags]
public enum PermissionsType
{
View = (1 << 0),
Add = (1 << 1),
Edit = (1 << 2),
Delete = (1 << 3),
Admin = (View | Add | Edit | Delete)
}
[Permissions(PermissionsType.Add)]
public ActionResult Register()
{
return this.AjaxableView();
}
What do you expect from this code?
With this attribute you gain all users in the administrator role the right to execute this controller action no matter how limited the account is.

Resources