How to create a random user with cookie without log in - asp.net

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;
}

Related

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

Cookie unset on response.redirect

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

I can't get my account to authorise itself using linqtotwitter

I know this has been asked many times before, but I have used info from the linqtotwitter docs and examples along with other posts on here to get this far. I can get my new app to send a tweet, but only by letting it take me to twitters authorise page and me having to click the authorise button to continue.
The app itself is authorised fine, so I don't need my password each time, it's just the use of the app that it wants permission for.
I know the reason for this is because nowhere in my code is there my access token or access token secret. I have added them in but every time I get a 401 unauthorised (invalid or expired token).
My code is as follows, perhaps you can see where I'm going wrong?
private IOAuthCredentials credentials = new SessionStateCredentials();
private MvcAuthorizer auth;
private TwitterContext twitterCtx;
public ActionResult Index()
{
credentials.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"];
credentials.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"];
credentials.AccessToken = "MYaccessTOKENhere"; // Remove this line and line below and all works fine with manual authorisation every time its called //
credentials.OAuthToken = "MYaccessTOKENsecretHERE";
auth = new MvcAuthorizer
{
Credentials = credentials
};
auth.CompleteAuthorization(Request.Url);
if (!auth.IsAuthorized)
{
Uri specialUri = new Uri(Request.Url.ToString());
return auth.BeginAuthorization(specialUri);
}
twitterCtx = new TwitterContext(auth);
twitterCtx.UpdateStatus("Test Tweet Here"); // This is the line it fails on //
return View();
}
Here's the FAQ that has help on resolving 401 errors: http://linqtotwitter.codeplex.com/wikipage?title=LINQ%20to%20Twitter%20FAQ&referringTitle=Documentation
A couple items that might be helpful too:
You can't tweet the same text twice - so either delete the previous tweet with the same text or change the text. All my test append DateTime.Now.ToString() to avoid this error.
The SessionStateCredentials holds credentials in SessionState. The persistence mode default for Session state is InProc, meaning that your session variables will be null if the process recycles, which will happen unpredictably. You might want to make sure that you are using either StateServer or SQL Server modes.

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.

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.

Resources