asp.net multiple users? - asp.net

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.

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 ...?

Best way to persist data locally for a user on a webpage?

I have a search box on the page (webservice-fed results) and I'd like to save the search TERMS for the user in a UL\LI list on the page. So the next time they come back to the page, the results are still there....but if they clear their cache then it gets reset.
What's the best way to go about that?...I can persist between postbacks easily, but this is a new one for me.
Thanks,
Steve
Probably use a cookie, but remember you're limited to 4kb of data.
Otherwise, store the session in a database. Then save that records ID to a cookie. That way you can load the data from the database based on the ID in the cookie. Then just flush any entries in DB older than say, 30 days or something.
Due to lack of sleep, I have given you an answer in PHP. Sorry about that, I'll leave it because the information is still correct, just the syntax will be slightly different in asp.net
You have two options for data-persistence in php; cookies and sessions.
Sessions are server-side, and last as long as the browser window stays open.
Cookies are client-side, and last until the user clears their cache.
So it sounds like you want a cookie option. So in your search query processor, add the line
setcookie('search_' . time(), $_POST['search_query'], (time() + 10368000));
This will create a cookie on the client machine, with the name search_xxxx where xxxx is a timestamp (each cookie has to have a unique name otherwise they will overwrite eachother).
The weird looking calculation at the end is an expire time, which is set to 120 days in the future.
Then in your php document that displays your search page, you need to spit out all these cookie values.
foreach($_COOKIES as $k => $v) {
if(substr($k, 0, 7) == 'search_') echo($v . '<br />');
}
This will spit out each of the search terms found on the clients machine. The if statement is to make sure it only displays search term cookies, and no others.
Use a cookie. Assuming you start with a List<string> of search terms called terms, do:
var sb = new StringBuilder();
foreach (var t in terms) sb.Append(t).Append(";")
var c = new HttpCookie("terms");
c.Value = sb.ToString().TrimEnd(';');
c.Expires = DateTime.Now.AddDays(30);
Response.Cookies.Add(aCookie);
Then when you need to access those terms again (to databind to a Repeater, or process in some other way for display on your page):
if (Request.Cookies["terms"] != null) {
var terms = new List<string>();
foreach (var t in Request.Cookies["terms"].Value.Split(';')) list.Add(t);
}
A Cookie is probably your solution for today, but HTML5 localStorage will eventually be the best bet. Only supported by modern browser versions right now, depends on your users.

presence control in asp.net web applications

I've managed to implement the Name.NameCtrl.1 active x used in sharepoint in my own custom built apps for presence. All is working fine and I'm updating presence status correctly based on a users status on Office Comunication Server. However I'm not getting any other details on the user propulated in the presence control like it does in SharePoint. All I get is the sip address in the email field (rather than the real default email address in AD) and a link to schedule a meeting.
Can anyone tell me how to get the control to populate with details from AD (dept, email, phone etc) like it does in sharepoint?? Also I don't get an organization tab in the control like sharepoint.
Any ideas?
Thanks,
Keeney
NameCtrl gets the majority of its data from the running instance of Communicator (or Lync, if you're using that) on the client machine. No data is directly pulled back from SharePoint. To have NameCtrl work properly on your web pages, you need to make sure that:
Communicator (or Lync) is running on the client, and signed in
The web page you are calling NameCtrl from is in the Intranet or Trusted Sites zone in your browser
The recommended pattern is to call PresenceEnabled on the NameCtrl object before calling any other methods - if this returns false, then one (or both) of the above prereqs is false. The code below generally works for me
<script>
var sipUri = "your.contact#your.domain.com";
var nameCtrl = new ActiveXObject('Name.NameCtrl.1');
if (nameCtrl.PresenceEnabled)
{
nameCtrl.OnStatusChange = onStatusChange;
nameCtrl.GetStatus(sipUri, "1");
}
function onStatusChange(name, status, id)
{
// This function is fired when the contacts presence status changes.
// In a real world solution, you would want to update an image to reflect the users presence
alert(name + ", " + status + ", " + id);
}
function ShowOOUI()
{
nameCtrl.ShowOOUI(sipUri, 0, 15, 15);
}
function HideOOUI()
{
nameCtrl.HideOOUI();
}
</script>
<span onmouseover="ShowOOUI()" onmouseout="HideOOUI()" style="border-style:solid">Your Contact</span>
In case you haven't already seen it, there is a good(ish) NameCtrl reference here
I think in SharePoint, the control is populated with data that exists in the user profile service. If you want this in a non-sharepoint ASP.NET web app, then you'd have to build a repository of user profile details from AD (and cache it!) which your control will look to to display that information.

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