asp.net mvc can't access cookie data in base controller - asp.net-mvc

For every page requested, I need to check a cookie or create it if it's not there.
If the cookie is there, I need to load up some info from the DB based on the contents of that cookie.
To do this I have created a base controller called AppController that my other controllers inherit from.
then I have something like this (so that the CurrentSessionValues object is available to all my controllers):
public MySession CurrentSessionValues;
public ApplicationController()
{
if (Request.Cookies["MySiteCookie"] == null)
{
// create new Record in DB
CurrentSessionValues = CreateMySession();
HttpCookie cookie = new HttpCookie("MySiteCookie");
cookie.Value = CurrentSessionValues.SessionID.ToString;
Response.SetCookie(cookie);
}
else
{
// use the value in MySiteCookie to get values from the DB
// e.g. logged in user id, cart id, etc
}
}
When I run this, I get this error in default.aspx:
An error occurred while creating a
controller of type
'Mvc_Learn.Controllers.HomeController'.
If the controller doesn't have a
controller factory, ensure that it has
a parameterless public constructor.
It breaks on Request.Cookies["MySiteCookie"]
Should I be doing this logic in some other way or another place?

Trick is that you don't have context in the constructor necessarily. Rather, you should override the Initialize method:
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
// DO NOT forget to call the base
base.Initialize(requestContext);
//check request context for cookie and do your thang.
}
PS: for posterity, I should note why there is an error. The key part of the exception info is that an error took place while creating the controller, the parameterless constructor bit is a red herring in this case. The error which took place was a null reference exception to HttpContext.

Check that HomeController has a parameterless public constructor, and check that the parent constructor ApplicationController() is being called.

Related

EntityFramework SaveChanges() throws concurrent transaction error

In my MVC application, I have a page that loads a record from my POLICIES table and then uses it in my View. My View then has the data from this record displayed on the page, however in order to edit the record data the user needs to click the "Edit Policy" button, which launches a jQuery UI dialog with the same record in EDIT mode. I realize I could just allow them to edit it from the main View, however that is not what my client wants.
The trouble I'm having is, when I'm in my jQuery UI Dialog, I get the error below when I try to save the record.
FirebirdSql.Data.FirebirdClient.FbException: lock conflict on no wait
transaction
The Controller method for my dialog executes the following code. The PolicyModel is simply a class which serves as the ViewModel for the dialog, and the Policy property is an object representing the Policy table.
public ActionResult Policy(int policyNo) {
PolicyModel policyModel = new PolicyModel();
policyModel.Policy = dbContext.POLICIES.FirstOrDefault(db => db.POLICY_NO == policyNo);
return View(policyModel);
}
In the "Policy" View, I do a standard form using:
#using (Html.BeingForm("SavePolicy", "MyController", FormMethod.Post)) {
//hidden element for policyNo created with #Html.HiddenFor
//form elements here created using the #Html.TextBoxFor..etc.
}
The dialog button to save simply creates new FormData with var formData = new FormData($('#myformid').get(0)); I then pass that to my save controller method.
The Save method is set up like the following
public ActionResult SavePolicy(PolicyModel policyModel) {
var policy = dbContext.POLICIES.FirstOrDefault(db => db.POLICY_NO == policyModel.POLICY_NO);
if (TryUpdateModel(policy,"Policy", updateFields.ToArray())) {
dbContext.Entry(policy).State = EntityState.Modified;
dbContext.SaveChanges();
}
return Json( new { result = 1, JsonRequestBehavior.AllowGet } );
}
If I change the POLICY_NO manually though to ANY other policy number than the one currently active in the dialog like this...
var policy = dbContext.POLICIES.FirstOrDefault(db => db.POLICY_NO == 12345);
The save will update correctly.
It's like the dialog View is holding onto the resource or something. any ideas?
UPDATE
For reference, the dbContext is scoped to the Controller class in which my SavePolicy method lives as seen below...
public class MainController : Controller {
private DBModel dbContext = new DBModel();
// other methods
public ActionResult SavePolicy(PolicyModel policyModel) {
// method code as see above
}
}
ASP.NET MVC Controllers usually have this:
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
So, if you are declaring your context outside of your action, you should verify if this method is implemented.
Turns out that, at the first execution (a select), your context keeps track of the record at Firebird and it is never disposed. The second execution will try to select the same entry again, which is still tracked by another context that was not disposed properly.
Using the scoped context inside each action is another way to solve, but it is a bit more cumbersome in my standpoint.

Setting Session on Specific Event Calls

I have an MVC application and a custom class called AuthorisationFilter which has a .NET interface of IAuthorizationFilter, this has an OnAuthorization method which gets called when I click around my site, at that point I go about validating the security access of the user (which works), but I don't want to do this all the time as it is time consuming.
In this I'm trying to use the Session to store a temporary piece of login information (this is an internal application by the way), but I can't get it working as I'd expect. I can't just use an HttpContext so end up constantly creating a new instance of HttpContextBase, which I assume is then clearing out the Session. My code is as follows:
internal void SetSecurityLevel(int token)
{
HttpContextBase _cBase = new HttpContextWrapper(HttpContext.Current);
_cBase.Session["SecurityRights"] = token;
}
internal int GetSecurityLevel()
{
HttpContextBase _cBase = new HttpContextWrapper(HttpContext.Current);
if (_cBase.Session["SecurityRights"] == null)
{
SetSecurityLevel(-1);
}
return (int)_cBase.Session["SecurityRights"];
}
Please note this is only part of the code, SetSecurityLevel is set to the correct value by a separate method call which is not shown
Anyway what I'm really wanting to do is have the session set in this class and have it persisted. I tried a few different ways, including setting the context when the class is initialised, but I end up with a NullReference on the .Session object in GetSecurityLevel
private HttpContextBase _cBase = new HttpContextWrapper(HttpContext.Current);
public AuthorisationFilter()
{
_cBase = new HttpContextWrapper(HttpContext.Current);
}
Is there a way I can do this within the class?
You are right that you can't set in the constructor but you can in OnActionExecuting when the context is available
public override void OnActionExecuting(ActionExecutedContext filterContext)
{
_session = = filterContext.HttpContext.Session;
I would wonder a little why you're setting this security level in the filter and not just doing it directly from where it's needed.

how to unit test for session variable in controller in mvc

I am unit-testing my controller.
In one of my controller methods I am setting Session variables:
public void Index()
{ Session["foo"] = "bar";
return View();
}
How can I unit-test this? The problem is that the Session property is null when testing. Injecting is not possible because the Session property is readonly.
I don't want to use any third-party tool or mocking.
Simply dont use things like Session["foo"] in your controller methods. Best practice is keep action methods unaware of any context-like global objects. Everything your action method needs should be given to her in form of arguments. Note that built-in mechanism of model binding works exactly like that - you dont use Request.Form[], you let "somebody behind the scene" pass it to your action as argument.
Now for the session you can do the same - write you very simple ValueProvider which will know how to recognize arguments you want to fill from session, and you are done. In production your actions will work with session, in test you cant simply pass them any values you want as arguments.
For inspiration look at this http://www.prideparrot.com/blog/archive/2012/7/how_to_create_a_custom_session_value_provider
Injecting is not possible because the Session property is readonly.
This means you cannot use setter injection, but could you use constructor injection, ie add a constructor for your controller that is something like:
MyController(Session session)
{
m_session = session;
// then call your main constructor
}
Session getSession()
{
return m_session;
}
You can then use this separate constructor during testing.
I agree with #rouen. do not directly use Session["foo"]. But I think having ValueProvider ans might not be a practical solution, as we only store very few variables, and these values may be and most likely not ur full model.
So my approach is something similar to what Vic Smith suggests but a much more IOC (and Mock) friendly.
I would create a provider (i.e a service) to retrieve the session variables
public class SessionVariableProvider : ISessionVariableProvider
{
public object GetSessionValue(string key)
{
if (!HttpContext.Current.Session.IsNewSession
&& HttpContext.Current.Session[key] != null)
{
return HttpContext.Current.Session[key];
}
throw new ArgumentNullException(key);
}
public void SetSessionValue(string key, object value)
{
HttpContext.Current.Session[key] = value;
}
}
public interface ISessionVariableProvider
{
object GetSessionValue(string key);
void SetSessionValue(string key, object value);
}
Modify your Controller expect ISessionVariableProvider as a parameter.
public class TestController: Controller
{
protected readonly ISessionVariableProvider _sessionVariableProvider;
protected InowiaControllerBase(ISessionVariableProvider sessionVariableProvider)
{
Guard.ArgumentNotNull(sessionVariableProvider, "sessionVariableProvider");
this._sessionVariableProvider = sessionVariableProvider;
}
public ActionResult Index()
{
_sessionVariableProvider.SetSessionValue("foo", "bar");
var foo2 = (string)_sessionVariableProvider.GetSessionValue("foo2");
return View();
}
}
when testing create your own test implementation of ISessionVariableProvider and pass it to the controller.

ASP MVC 3 Base controller for entity context access

I've implemented a base controller for my MVC 3 project to allow a common way of accessing a user entity from my db context :
public abstract class MyBaseController : Controller
{
protected DBEntitiesContainer db;
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
this.db = new DBEntitiesContainer();
}
public UserDetails GetActiveUserDetails()
{
UserDetails userDetails = GetObjects.GetActiveUserDetails(this.db);
return userDetails;
}
}
This works great and all my controllers have access to this.db.MyEntity and can retrieve a UserDetails object by calling this.GetActiveUserDetails()
However, the problem arises when I try to perform an update on the entity thus :
public class UpdateController : MyBaseController
{
public ActionResult Index()
{
UserDetails userDetails = this.GetActiveUserDetails();
userDetails.LastOnline = DateTime.Now;
UpdateModel(userDetails);
this.db.SaveChanges();
}
}
Any ideas why the UserDetails object is easily retrieved, but when I check my database after calling SaveChanges(), nothing has been updated ? I'm presuming I'm accessing my context in two different ways, but I can't see how I am...!
Edit: Here's the GetObjects.GetActiveUserDetails() method
public static UserDetails GetActiveUserDetails(DBEntitiesContainer db)
{
MembershipUser membershipUser = Membership.GetUser();
UserDetails userDetails;
try
{
if (membershipUser != null)
{
userDetails = (from u in db.UserDetails
where (u.UserId == (System.Guid)membershipUser.ProviderUserKey)
select u).First();
}
else
{
return GetGuestAccount();
}
}
catch
{
return GetGuestAccount();
}
return userDetails;
}
Not the cleanest method I know...
UpdateModel is helper method for Controller base class. it supports updating the properties of an object we pass it using the incoming form parameters during HttpPost action method.
It uses relfection to find out the property names of the object (Model object what we passed) and then automatically converts the assigns values to them based on the input values submitted by the form ( client form).
In your case you when u use update model it has no input value find associated model and it make the model default values as it is in database.
try to comment the updatemodel line and runt he code... it must work.
It's not a good idea to setup data access this way. One reason is that you should dispose of the db context after you use it. This means that using your method, this leaves the database connection open until garbage collection occurs, which could be minutes or hours later. As other web requests come in, new database connections are created, and again those are not disposed of either.. etc.. etc.. it's a pseudo-memory leak (not a true memory leak because it will eventually get collected, but it means resources are being used well after they are needed)

Best approach to don't request same info over and over

On my controller I have it inherit a MainController and there I override the Initialize and the OnActionExecuting.
Here I see what is the URL and by that I can check what Client is it, but I learned that for every Method called, this is fired up again and again, even a simple redirectToAction will fire the Initialization of the same controller.
Is there a better technique to avoid this repetition of database call? I'm using Entity Framework, so it will take no time to call the DB as it has the result in cache already, but ... just to know if there is a better technique now in MVC3 rather that host the variables in a Session Variable
sample code
public class MyController : MainController
{
public ActionResult Index()
{
return View();
}
}
public class MainController : Controller
{
public OS_Clients currentClient { get; set; }
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
// get URL Info
string url = requestContext.HttpContext.Request.Url.AbsoluteUri;
string action = requestContext.RouteData.GetRequiredString("action");
string controller = requestContext.RouteData.GetRequiredString("controller");
object _clientUrl = requestContext.RouteData.Values["cliurl"];
if (_clientUrl != null && _clientUrl.ToString() != "none")
{
// Fill up variables
this.currrentClient = db.FindClientById(_clientUrl.ToString());
}
base.Initialize(requestContext);
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
// based on client and other variables, redirect to Disable or Login Actions
// ... more code here like:
// filterContext.Result = RedirectToAction("Login", "My");
base.OnActionExecuting(filterContext);
}
}
is it still best to do as:
public OS_Clients currentClient {
get {
OS_Clients _currentClient = null;
if (Session["CurrentClient"] != null)
_currentClient = (OS_Clients)Session["CurrentClient"];
return _currentClient;
}
set {
Session["CurrentClient"] = value;
}
}
It seems that you dealing with application security in that case I would suggest to create Authorization filter, which comes much early into the action. You can put your permission checking code over there and the framework will automatically redirect the user to login page if the permission does not meet AuthorizeCore.
Next, if the user has permission you can use the HttpContext.Items as a request level cache. And then you can create another ActionFilter and in action executing or you can use the base controller to get the user from the Httpcontext.items and assign it to controller property.
If you are using asp.net mvc 3 then you can use the GlobalFilters to register the above mentioned filters instead of decorating each controller.
Hope that helps.
In your base controller, you need to cache the result of the first call in a Session variable.
This makes sure the back-end (DB) is not called unnecessarily, and that the data is bound to the user's Session instead of shared across users, as would be the case with the Application Cache.

Resources