Pass POCO around in a Asp.Net MVC application - asp.net-mvc

I am having an Asp.Net MVC 3 app where i need to pass around a Viewmodel to different Views and i am wondering what is the correct approach to accomplish this.
Once the user logs in and gets the user object,i need to use the same user object to Views such as ViewUser, EditUser etc.I am currently passing the User id(Once the user logs in succesfully) in #html.actionlink method as objectroutes and getting the user object from the database every time.
Is this the right approach ? I didnt want to use Session.
Thanks !

Why don't you want to use Session? It's designed for this very scenario... to cache data that will be needed for the duration that a user is logged in.
When a view alters the User object (EditUser), just update the Session at the same time you update the database.

Related

Making sure only one user is editing a form in Rails application

Currently, I have a Rails application whose edit form is on a separate edit page. Is there a way to make sure no two users are accessing the edit page at the same time? Or a user can only access the edit page if no other user is currently on the page?
Or to ask a simpler question, is there a way to get a list of users currently on the page?
I am on Rails 4.
HTTP is a stateless protocol. It was designed to allow idempotent transactions. The server does not store transaction state information about each chain of requests. The session allows you to mitigate this design pattern and allow the server to track where your users have been. In order for you to know if a user is on a page, you will need to store in your database where each user is. Remember, that when a user decides to navigate away from a page, your servers will not know it, only when a request is made to a different page.
I assume you don't need to track anonymous session information, so you probably need to override your controller action that ensures users are logged in to save where the user is at. Before rendering the page, ensure the count of user's current location equal to the rendered page is 0.
You can have AJAX fire on the page, updating the location of your user on these pages so you can ensure that there has been no user in a reasonable timeout. Without the AJAX you would need to consider what the reasonable amount of time a user would be editing information, and consider that a non-reasonable amount of time is likely the actual amount.
There's no 'RAILS' feature that can be turned on to check where a user is located, this would be a roll your own situation.
I think the best way is to use a Redis Store (or anything in memory), or make a temporary sessions table for that.
Then you can authorize the show action to check whatever you want.

ASP.NET MVC4 How to post and retrieve data unique to a specific user

I have been learning how to use ASP.NET MVC4 and have been getting my head around authenticating users and user roles and posting data using the entity framework to SQL.
However I have not been able to find any guides/resources (maybe I don't know the correct term) for posting and retrieving data that is unique to an specific user. For example how would a user only see the entries that they created if it was a site that stored data that is personal to each user.
What patterns/designs does one use when trying to do this?
Creating a sandbox of data for a specific is usually tied to authentication. You can access this many ways through ASP.Net.
First of all, every user gets identified even if they never log in. They get a session identifier. It essentially creates a small place in memory for this user where you can store any user related information. Think of Sessions as walled gardens for each user.
Session["UserFullname"]
This works, but realize Session is limited by time, so it is very volatile. Utilize it, but don't depend on it.
The next method is to authenticate a User. This is done using Cookies, but usually handled transparently for you by ASP.Net Membership or other authentication providers. To access the authenticated User you just need to use a simple line in your Controller actions.
// User is the property
User.Identity.Name
Both these methods can store information about your user that you would use to query data specific to them.
Select * From Orders Where UserId = *User.Identity.Name*
Note that both Session and User are accessible through HttpContext.Current as well, as long as you are in a web environment.
HttpContext.Current.User
HttpContext.Current.Session
You won't need to access them this way unless you are not inside your Controller, or inside of another class that doesn't already give you access to the HttpContext. I don't recommend this way either, since your code could be used outside of a web application where HttpContext is not available.
I hope that makes sense, and please feel free to ask me questions.
This is not so much about mvc, but more about the problem of relating data to a specific user. You have to ask yourself, how would you identify a piece of data to a user.
The way you would do this is to tie the data to the user in the data store somehow.
In a relational database you would do this by having a User table and using the unique key on that table to insert data into another table such as Order. Order would then have a User Id.
When a user logs in, you could store that ID in session and use that to filter out orders based on the id.

Asp MVC, is session lost upon building solution?

I 'm writting an application in ASP.NET MVC. Basically I have some pages which require user authentication. Upon user logon, I keep the user row in a session. So in my controller I can access to the user.ID without making extra queries.
When project is in debug mode I can only change things in the views. Not in the controller.
If I 'm not debugging, I can build the solution, and see the changes I made without running the project (with F5). BUT, it looses all session variables I have.
So basically for every no-matter how small change in the controller, I have to logoff, logon to see my changes.
Are those normal behaviours?
Like Dan stated, this is normal behavior. To make it easier (and slightly more robust) is to change your code slightly. This is of course assuming that you are storing more than just the User ID in session since you can access the User ID via Controller.User.Identity.Name when they are authenticated. So you perform the lookup of the additional data in the session object and if it doesn't return null then use it. If it does return null, then look up the additional information again based on the User ID and store it in the session again. This is the approach I take for storing information from Active Directory and it works great.
Yes, this is a normal behaviour of ASP.NET as a whole not just MVC.
If you need to recompile (e.g a change in controller or business object) you will be in a new session when you run in debug. Like you say, only changes in views or pages (which do not require a recompile) will allow you to see changes in same session.
Kindness,
Dan
Recompiling will clear all the current session data. However it will not clear your authentication ticket, that's stored as a cookie, so there's a few things you can do to avoid this.
If you only need to access the user id then use User.Indentity.Name
If you only need basic user data for display purposes, such as the user's name, then you can store that in a session cookie. Warning: only do this for displaying data unless you encrypt the cookie data, plain text cookie data shouldn't be trusted.
If your user data is more complex than that then access the data through a method that uses caching as suggested by Agent_9191
Add something like this to a base controller or extension method
protected UserData GetUserData() {
UserData user = HttpContext.Session["User"] as UserData;
if (user == null) {
user = UserDataRepository.GetUser(User.Identity.Name);
HttpContext.Session.Add("User", user);
}
return user;
}

ASP MVC - confirm page when adding object to database

I'm making a simple CRUD app with ASP MVC and I want to have a confirm page when creating a new object and inserting it into the database.
The problem is that I'm having trouble passing the object between actions. I tried to save it in the session after it's created and then retrieving it when the user confirms, but I'm getting an InvalidOperationException when I try to insert it into the database ( I'm using Entity Framework )
I'm not even sure if I'm approaching this the right way. Any ideas?
What I like to do if the schema allows for it, is to have an active flag (and timestamp field) on the record. You insert on the first page without setting that flag. The confirm page merely sets the active flag. Another process can clean dead records that were not confirmed within a certain range of their timestamp. And the object or entity never ties up session memory.
edit for clarity: as a result you only pass the id of the created entity to the confirm page
Tim's is the best basic answer to this but if you don't want to include the extra logic you could also consider using hidden fields on the confirm page so confirming actually resubmits the form data (this means less DB trips and means that you don't have old unconfirmed entries sitting in the DB to filter out but means more data to and from the client).
Another alternative that might be preferred from a UI point of view is to have Tim's answer but if JavaScript is enabled make the submit button instead pop up a confirm screen, clicking OK would submit both the form and the confirmation in one go.

Rails w/ ActiveRecord Sessions and Restful-authentication: when does the sessions table get written to?

Warning: some of this may be very wrong-headed, so please let me know if my assumptions are incorrect.
Here's what I'm trying to accomplish:
I'm using restful-authentication for login. However, as I am using flex/ruby_amf for my UI, I have to separately authenticate each connection from flex.
The way I decided to do that was by having the log-in screen redirect to the embedded flash page, inserting the session-id as a flashvar. The flash app sends the session-id with every request, and a before filter on all of the relevant controllers checks to see if the user associated with the session identified by the session-id is logged on.
The way I associate a user with session is by adding a 'user_id' column to the sessions table, and doing an sql "update sessions set user_id...'" type query called from the login function.
However, the user_id only gets updated the 2nd time the user logs in. A little investigating showed that the record in the sessions table does not yet exist during execution of the login function.
So, if everything up to this point makes sense, and conforms to best-practices, etc., then my question is:
At what point in time is the record in the sessions table created? Is there a way to update the session object in the login function and have rails write the user_id to the database for me?
The behavior of sessions in rails is a real mystery to me. I'd appreciate any help.
Thank you.
In Rails 2.3, the session is saved after the Rack application has finished its processing. In traditional Rails applications, this will be after the request is fully processed: before filters, controller action, view rendering, and after filters. Look in actionpack/lib/action_dispatch/vendor/rack-1.1.pre/rack/session/abstract/id.rb.
If you think about it, this makes perfect sense. Writing the session to its store every time you place something in the session would incur a lot of extra overhead.
It's Rails, so if you want to mess with it enough, sure, you can monkeypatch yourself a way to write the session to store anytime you wish. I don't recommend it. You'll end up having to rework the code constantly as Rails evolves.
You are right that for ActiveRecord::SessionStore, one row does map to one session. The data column is an encoded form of every object you put in the session. Each time a request comes in, Rails has to reconstitute the session as it existed by creating new instances of all the objects you previously stored in it.

Resources