Cookie unset on response.redirect - asp.net

I am trying to create a login page with the ability to persist user login info (User ID/User Name) in cookies (although a session variable is used for immediate storage for the site). I am using the code below:
Session("UserID") = USERS.GetUserID(Request.Form("UserName"))
Session("FullName") = USERS.GetUserFullName(Session("UserID"))
If Request.Form("RememberMe") = "True" Then
Response.Cookies("UserID").Value = Session("UserID").ToString
Response.Cookies("UserID").Expires = Now.AddDays(30)
Response.Cookies("FullName").Value = Session("FullName").ToString
Response.Cookies("FullName").Expires = Now.AddDays(30)
End If
Response.Redirect("~/VetPortal/Default.aspx")
I can track this step by step using Visual Studio and everything works just fine. The session variables are set, and the cookies are created properly. The problem is that when the redirect page is loaded, the cookies no longer are present. Am I missing something in setting the cookies that are preventing them from being retained? As I understand it, they should be retained until the expiration (today + 30 days).

Related

How to create a random user with cookie without log in

Hi I have a shopping web site and I want to create random user per computer with cookie or session But I can not create randomly. Could you guys help me to create a user per computer then add items to basket. I have basket codes Just need to create user per pc without log in...
Here is how do I create random Session ID
>> public void generate(){
>> SessionIDManager Manager = new SessionIDManager();
>> string NewID = Manager.CreateSessionID(Context);
>> userId.Text = NewID.ToString();
>> }
I call this in page load i say if(!ispostback){generate()}
so now when i refresh website id also gets refresh How can I control it if its same pc hold the session Id ?
Try serialising the basket object and placing that into a cookie. When the user performs a checkout then create a user if needed and convert cookie basket to order in db.
You will need to start by trying to write some code though, then come back if you're still stuck.
UPDATE
The sessionId is created for each browser session, if you close the browser then reopen it you'll get a new sessionId, using the sessionId to identify a user is only going to work as long as the user doesn't close the browser. You could store the sessionId in a cookie and check the cookie when a user returns
HttpCookie myCookie = new HttpCookie("UserId");
myCookie["SessionId"] = NewID.ToString();
myCookie.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(myCookie);
But personally I think you should look at this from a different angle.
UPDATE 2
Try this, the sessionId will be the same when you click refresh until you close the browser.
public void generate(){
var sessionId = Session.SessionID;
userId.Text = sessionId;
}

I only seem to be able to set one Cookie - HttpCookie, asp.net

I have a system with a two-stage login.
Stage one is a Company Login which identifies the Company using my system.
Stage two is a Staff Login where a member of staff belonging to the above company logs in.
In both stage an option is offered to save certain login details (Location/Company but not password)
A user should be able, if they wish, to set the Company Login Cookie, but not the Staff Cookie, there is no need to set a Staff Cookie without a Company Cookie, although it doesn't really matter if they do!
Stage one login, amongst database checks etc does this:
If SaveCookie Then
Dim loginCookie As New HttpCookie("LogInCompany")
loginCookie.Values("database") = Database
loginCookie.Values("savedKey") = SavedKey
loginCookie.Values("samCompanyId") = CompanyId
loginCookie.Values("samCompanyName") = Common.htmlDecode(CompanyName)
loginCookie.Expires = Date.Now.AddDays(7)
HttpContext.Current.Response.Cookies.Add(loginCookie)
End If
Then stage two does this:
If SaveCookie Then
Dim loginCookie As New HttpCookie("LogInStaff")
loginCookie.Values("locationId") = locationID
loginCookie.Expires = Date.Now.AddDays(7)
HttpContext.Current.Response.Cookies.Add(loginCookie)
End If
Obviously they are entirely separate functions, so I don't think the variable naming being the same is the issue.
What happens is:
Company Login successful > Company Cookie is Saved, User proceeds to
User Login User Login > User Cookie is Saved, BUT the Company Cookie
is deleted.
This is using Chrome, I haven't checked other browsers but Chrome is the most important to me.
I know that this is definitely what is happening as I have checked in the Chrome Console, the Cookies are added and removed as per description above.
Can someone help point out where I am going wrong here?
EDIT - Nothing wrong with this code!
Argh... after a day of messing about with this, it turns out that the Cookie was being cleared by an unexpected, and caught, error in a different, but related section of code! This question can be closed if required, or left ...?

asp.net multiple users?

I have an asp.net c# web application where a user can log in and see his schedule for the last week, which is stored in a remote database. Logging into the site consists of just an SQL check to see if the username and password matches the uname & pass records in the database. Once logged in, they can manipulate the time entries for the schedule, etc. While debugging, I logged in as two different users. User B had all of user A's stuff on his form. I wrote the program like I was writing a regular c# app, and didn't really give any thought to multiple people using the website at the same time. I guess I thought that instance handling would be automatic? I've only been working with asp.net for a week or so, and don't have much support.
My main question is, if I have multiple users on my site at the same time, how do I keep their sessions separate?
update - after adding Session variables
This is my sql statement to get user information. Now, using session variables:
string sqlquery = "SELECT FirstName, LastName, OperatorID FROM operators WHERE EmpID = '" + sql + "'";
using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["EobrConnectionString"].ConnectionString))
{
conn.Open();
using (MySqlCommand comm = new MySqlCommand(sqlquery, conn))
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(comm))
{
DataTable dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
Session["Fname"] = dr[1].ToString();
Session["Lname"] = dr[2].ToString();
Session["opID"] = dr[3].ToString();
}
}
}
}
In the main menu page I have this:
protected void Page_Load(object sender, EventArgs e)
{
firstname = Session["Fname"].ToString();
lastname = Session["Lname"].ToString();
lblwelcome.Text = "Welcome, " + firstname + " " + lastname + ", make your selection below.";
}
When User A logs in, they see their name "Frank Drebbin". When User B logs in they see their name, "Jake Gaston". But now, if I reload the first users page, they see the name as "Jake Gaston".
You need to use seperate browsers. You're using sessions to identify users, and sessions are matched to a cookie in your browser From your comments above, here's what happens
log in as steve -> session created -> steve stored as username -> cookie returned to browser
in a new window, log in as frank -> session already exists, rename username to frank.
in 1st window refresh. -> session username no frank -> return data based on that username.
New IE windows all share the same context. this means if 1 window gets a cookie, they all do. There are 2 ways around this (actually 3).
Use physically different machines
Use 2 broswers, eg IE & Firefox
In IE press alt to get the menu, then click new session from the file menu. This makes a physically separate window that won't share cookies (although there's nothing to indicate this to you)
Having done the above, try again logging in as Steve & Frank & you should see they don't interfere with each other.
I would guess the problem is that, while the sessions are kept separately (you are storing things in Session, right?), the queries that load data from the database are not taking the username into account.
Have a look at the SQL query that loads tasks and see if you include the username (or a user ID) in that query. Feel free to post the query if you need help looking at it.
So to directly answer your main question, if you store things in Session, they will be properly isolated from other sessions. However, wrong data in, wrong data out.
EDIT:
Use another browser to test this, you can't use the same browser in another tab, or the same browser in another window, it almost will be the same session
If you are using "Session" to save user's data then they are separated, that means you should store any per-user data into "Session" or cookies.
NOTE:
You should maintain concurrency http://msdn.microsoft.com/en-us/library/cs6hb8k4(v=vs.80).aspx
The solution is very simple( USER DIFFERENT BROWSERS SIMONTANIOUSLY) like IE, Firefox, Chrome etc........
You are not using transact SQL so need to bother about concurrency,
but when u login the current browser create a session if you use the same browser it will still has that session,
If you use another browser the browser will have the session but the value wont be the same.
e.g.
Each mobilephones have different browsers now if you have 100 mobile phones that would mean you can store 100 same USER session but all will have different values varies on the data you providing or operation handles.
Hope this help you understand.

Switching to cross domain tracking from previous Google Analytics implementation

We have in place a simple implementation of GA and have had for some time, the only additional methods we use are setVar and setSessionTimeout. Is there a way we can switch to a cross-domain tracking configuration of GA (where certain links are wired via the _link method) without losing existing tracking data on client systems?
I've run a lot of tests and the more issues solved, the more issues that come up. In a nutshell:
Pre-implementation, the client has these cookies: __utm(a, b, c, z, v). The first step was to change the code and add the _setAllowLinker and _setAllowHash methods, but this was throwing a TypeError. I found this could be avoided by deleting the __utmv cookie before calling the pageTracker methods, and then calling _setVar again afterward.
The new code in place seems to be working OK without throwing an error:
document.cookie = '__utmv=; expires=Tue, 22 Jun 2010 11:57:00 GMT;'+
' path=/; domain=XXXXXXX';
var pageTracker=_gat._getTracker(UA-XXXXXXXX);
pageTracker._setAllowLinker(true);
pageTracker._setAllowHash(false);
pageTracker._setSessionTimeout(XXXXX);
pageTracker._setVar(XXXXX);
pageTracker._trackPageview();
The cookies are now updated to not use a hash value, so their values can now be used cross domain, but the problem is that the values in the __utm cookies have been refreshed with new values which means we're losing user history (and new visits will explode).
For example, __utma:
Before - XX-HASHVALUE-XX.1379282990.1277294951.1277294951.1277294951.1
After - 1.26318765.1277294984.1277294984.1277294984.1
If it's not possible to switch to cross-domain GA configuration without losing user history, is there a way to fake it on the link which will click through to the next domain. That is, constructing the link URL from the cookies and replacing all the hashvalue prefixes with a 1?
Thanks!
Unfortunately it seems there is no proper way to do this using the ga.js API. I've gone with this solution:
var pageTracker = _gat._getTracker("UA-123456-7");
if (getCookie('__utma') && getCookie('__utma').substr(0, 2) == '1.') {
// hash value safely removed, flick GA API switch
pageTracker._setAllowHash(false);
}
pageTracker._trackPageview();
if (getCookie('__utmc') != '1') {
// remove hash values from all GA cookies
eraseCookieHash();
}
In the eraseCookieHash function, each cookie is updated manually to replace the hash value with a 1, using the guide at http://code.google.com/apis/analytics/docs/concepts/gaConceptsCookies.html to determine the expires value.

ASP.NET - Log User Session Start/End Times for Audit Trail - Global.ASAX?

My ASP.NET intranet web application uses Windows Authentication, and I would like to record the following details:
1) Windows ID
2) Session Start Time
3) Session Stop Time
4) URL being browsed to (optional)
I've got some basic code setup in "Session_Start" method of the Global.ASAX to log session start times (seen below), but that's it so far. I have the feeling this is a primitive approach and there are "better" ways of doing this. So I really have two questions:
1) Is this the right way to go about doing this? If not what are some other options?
2) If this is the right way, do I just need to drop some code in the "Session_End" method to record the time they exit, and thats a complete solution? Does this method always get called when they close the browser tab they have the site open in, or do they have to close the entire browser (I don't have logout functionality)? Any way users can skip over this session end method (or start for that case)?
Dim connsql As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionstring").ConnectionString)
Dim cmdsql As System.Data.SqlClient.SqlCommand = connsql.CreateCommand
cmdsql.CommandText = "BeginUserSession"
cmdsql.CommandType = Data.CommandType.StoredProcedure
Try
cmdsql.Parameters.Add("#windowsid", System.Data.SqlDbType.VarChar, 30, "windowsid")
cmdsql.Parameters("#windowsid").Value = Session("UserInfo").identity.name
If connsql.State <> System.Data.ConnectionState.Open Then connsql.Open()
cmdsql.ExecuteNonQuery()
connsql.Close()
Catch ex As Exception
Finally
If connsql.State <> Data.ConnectionState.Closed Then connsql.Close()
End Try
'Stored Proc records start time
Session_End is not reliable.
What I would suggest is on Session_Start you create a record that notes the time the Session was created, and in Session_End you update the record with the time it was ended.
To handle the majority of sessions which are passively abandoned, use Application_BeginRequest to update the record to note when the user was "last seen".
You will then need to determine a way of marking sessions that have been passively abandoned. This will be site/app specific. It could be as simple as picking a number of minutes that must pass before the session is considered abandoned - like 10 minutes.
So then you have a query:
SELECT Username,
SessionStart,
SessionEnd,
LastSeenOn,
DATEDIFF(mi, SessionStart, ISNULL(SessionEnd, LastSeenOn)) DurationMinutes
FROM SessionAudit
WHERE SessionEnd IS NOT NULL
OR DATEDIFF(mi, LastSeenOn, getdate()) > 10
Which will bring back your session audit log.
Your approach could be described as simple, but that could be totally fine - it comes down to what the requirements are. If you need to log a full suite of application errors and warnings, look at implementing something like Log4Net. Otherwise I wouldn't say there is anything wrong with what you are doing.
Sessions are ended when there has been no user activity for the amount of time specified in the timeout value, or when you explicitly call Session.Abandon() in your code. Because of the stateless nature of HTTP, there is no way to tell if a user has left your site, closed the browser or otherwise stopped being interactive with their session.
I am not sure you can catch the end of the session accurately because
The user can close their browser and that will not necessarily end the session.
They can then go back to your site and thus may have multiple sessions.
You can try messing with setting in IIS to kill the session very quickly after inactivity but its not a good idea.
Also... If the users are not all on an internal network you will have no control as to whether they have a "Windows ID" or not.

Resources