I have very large website which uses a lot of cookies. There are approx. 14 different cookies are there. I have different cookies for each item. When a user surfs the site they will have 14 cookies in their browser. I do not want this.
I want a single cookie for my site that will have 14 items and I can add,edit and delete them. I tried many ways but I am not able to do this.
I need to put some run time cookies as well save the user name in cookie. After the user logs in I want to save their personal site address in it. Eventually I want both the user name and personal site address both. I want to save user name before and then when user goes to his personal site then i will store personal site name run time.
Does any one have an idea how I could do this?
Matthew beat me to it, but yes, see the ASP.NET Cookies Overview...
To write and read a single cookie with multiple key/values, it would look something like this:
HttpCookie cookie = new HttpCookie("mybigcookie");
cookie.Values.Add("name", name);
cookie.Values.Add("address", address);
//get the values out
string name = Request.Cookies["mybigcookie"]["name"];
string address = Request.Cookies["mybigcookie"]["address"];
There is a section in the ASP.NET Cookies Overview that discusses how to implement multiple name-value pairs (called subkeys) in a single cookie. I think this is what you mean.
The example from that page, in C#:
Response.Cookies["userInfo"]["userName"] = "patrick"; //userInfo is the cookie, userName is the subkey
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString(); //now lastVisit is the subkey
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "patrick";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
EDIT: From the Cookies Overview (emphasis added):
Modifying and Deleting Cookies:
You
cannot directly modify a cookie.
Instead, changing a cookie consists of
creating a new cookie with new values
and then sending the cookie to the
browser to overwrite the old version
on the client.
Modifying and Deleting Cookies: You cannot directly modify a cookie. Instead, changing a cookie consists of creating a new cookie with new values and then sending the cookie to the browser to overwrite the old version on the client.
Related
Imagine that a user in a Java Servlet program signs up with his personal information.
Then if he wants to re-use it he can log in with his username and password submitted before.
I want to know how I am going to check the cookies that were stored in the browser in order to see if a specific username was followed by a specific password. I was wondering if cookies are stored in the same row as they were added or they are stored randomly.
I know I can check them by writing like this:
for(int i = 0; i< cookies.length; i++) {
Cookie thisCookie = cookies[i];
if (thisCookie.getName().equals("usn"))
//...
but there seems to be the problem,as there could be a number of usernames and passwords stored in the browser but the linking between two of them would be specific.
I working on a project where the connString is stored in a session variable. The problem is that the session runs out when the user is not around for a while (makes sense), thereby making the user having to log in again to create a new connection.
The user selects his database from a list of ODBC connection configured on the web server, therefore the different connStrings the user can chose from cannot be stored in the web.config as the user can add new ones as they wish.
I was wondering how to fix this problem. Should I just tell the user not to leave his computer for 20mins+ or can I perhaps store the connString someplace else? Ive seen websites making a pop-up saying "your session will expire in 5 mins, press ok to continue using the site", or something like that.
Furthermore it is not a possbility to make a static varible as the website is shared between many users, so if user1 choses "connString1" and user2 choses "connString2" afterwards, then user1 will unfortunatly be running on "connString2" aswell.
Hope you can help :)
**
Can this be a solution?:
I create a "BasePage" which my pages inherit from. In this basepage i create a hiddenfield and add the connString to the value property on load. Furthermore I will encrypt the connString so the user cannot see the value in the source code.
Then, if the session has a timeout, i will restore the session by using the value in the hiddenfield and the site will not crash.
Can you store the user's connection string preference in their Profile and then persist their profile? http://odetocode.com/articles/440.aspx
You should also be able to do this for anonymous users.
As an aside, I don't know how secure the Profile APIs are, they should be fine, but just in case, you might want to store an Enum value and then map that to a Connection string in your code.
You could use the app.config to get and set config files. Take a look at this to see implementation of storing files. Its just as easy to get settings.
ConfigurationManager doesn't save settings
//Edit: If you don't want the user to be able to see your connectionstring name then you can provice an another in hidden_html or cookie or session cookie. In this example I use a cookie. THis should solve your problem.
To set cookie:
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["ConnectionString"] = "MyCOnnectionValue";
myCookie.Expires = DateTime.Now.AddDays(1d);//For one day.
Response.Cookies.Add(myCookie);//Will store the cookie within the users browser so your code can read from it at every request.
then:
if (Request.Cookies["UserSettings"] != null)
{
string userSettings;
if (Request.Cookies["UserSettings"]["ConString"] != null)
{ userSettings = Request.Cookies["UserSettings"]["ConString"]; }
}
string connectionStringNameToUse;
if(userSettings =="Connection1"){
connectionStringNameToUse = "here you can have your name of connectionsstring";
}etc with ypur other connectionsstrings here.
//Then use your connectionsstring here:
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings[connectionStringNameToUse ].ToString()))
{
cn.Open();
using (SqlCommand command = new SqlCommand
("delete TBL from RatingListObjects TBL where ( TBL.TradeObject1Id = #MY_ID ) or ( TBL.TradeObject2Id = #My_ID ) ", cn))
{
command.Parameters.Add(new SqlParameter("#MY_ID", customerToRemove.TradeObjectId));
command.ExecuteNonQuery();
}
}
On the other hand. I would go for saving the users database of choice in with the other user data in the db. But this is doable if you only want the user to have a chosen connectionsstring a certain time, set by the program. It wont allow them to see the connections string name. Hopes this helps, good luck!
I need to create cookie with e-mail address as value - but when I try to - then I have result:
"someone#example.com"
but I would like to have:
someone#example.com
The cookie should be created without double quoted marks - because other application uses it in such format. How to force java to not to add double quoted? Java adds them because there is special char "at".
I create the cookie that way:
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
Cookie cookie = new Cookie("login", "someone#example.com");
cookie.setMaxAge(2592000);
cookie.setDomain("domain.com");
cookie.setVersion(1);
response.addCookie(cookie);
Thanks for any help.
It's indeed caused by the # sign. This is not allowed in version 0 cookies. The container will implicitly force it to become a version 1 cookie (which breaks in MSIE browsers). You'd like to URL-encode the cookie value on cookie's creation
Cookie cookie = new Cookie("login", URLEncoder.encode("someone#example.com", "UTF-8"));
cookie.setMaxAge(2592000);
cookie.setDomain("domain.com");
response.addCookie(cookie);
and URL-decode it on cookie reading
String value = URLDecoder.decode(cookie.getValue(), "UTF-8");
Note that you should for sure not explicitly set the cookie version to 1.
See also:
Why do cookie values with whitespace arrive at the client side with quotes?
Unrelated to the concrete problem, cookies are visible and manipulatable by the enduser or man-in-the-middle. Carrying the email address around in a cookie is a bad smell. What if the enduser changes it to a different address? Whatever functional requirement (remembering the login?) you thought to solve with carrying the email address around in a cookie should most likely be solved differently.
See also:
How do I keep a user logged into my site for months?
I currently have a page that is populated using a filter, which passes the parameters of the filter via URL.
I'd like to catch those parameters and give the user the opportunity to return to the page with the same filter applied to their view. Essentially, it's a back button. AKA: pass the parameters back into the URL so it repopulates the page.
I hope that made sense. Any help is appreciated! Thank you!
You could store the filter values in a session variable or in a cookie.
Session variable:
Session("MyCustomFilter") = "FilterValue"
Cookie:
Dim cookie As HttpCookie
cookie = New HttpCookie("MyCustomFilter")
cookie.Values.Add("MyCustomFilter", "FilterValue)
While a session variable is easier to use, it will not be saved if you close the browser, while cookies will be saved and can be used later on.
Note: Added a more precise answer, based on my comment.
IE works fine, but FireFox does not.
I am setting a cookie on my default.aspx page:
HttpCookie hc = new HttpCookie("guid", guid.ToString());
hc.Expires = DateTime.Parse("12/12/2010");
Response.Cookies.Add(hc);
My upload control (I'm using SWFUpload) submits to upload.aspx.
On upload.aspx I call:
if (Request.Cookies["guid"] != null)
{
// Do something.
}
...my cookie only contains my ASP.NET session variable. Any ideas?
I have had the same issue when trying to upload files in Firefox through my Flex application. If you're also using Flash, you may want to do what I did; if you're using the HTML controls, this may or may not apply.
What I did to work around the Firefox issue is issue a one-time use token on the server, then post that token when doing the upload (for example, it could be a hidden field in the form). If the token is recognized upon upload, the upload is processed, then the token is expired. So it's basically what you're doing, only without using a cookie.
This is what I used to add/get cookie values. Works for me in both IE and FF
addCookie:
HttpCookie c = new HttpCookie("myCookie");
c.Expires = new DateTime(2050, 1, 1);
c.Values.Add("key", "value");
getCookie:
string value = Request.Cookies["myCookie"]["key"];
Behind the scenes, you are probably setting the same cookie twice. Firefox and IE probably differ on which one they choose to keep. ASP.NET likes to set a "guid" cookie automatically in a lot of web applications. By choosing that name, you are bound to create tension between the automatic logic and your own. The best way to see what is happening is to load the Live HTTP Headers add-on to Firefox. It will allow you to see exactly what cookie commands are being sent over to the end-user. You can also force a similar problem to see it recreated:
HttpCookie hc = new HttpCookie("testcookie", "xyz");
hc.Expires = DateTime.Parse("12/12/2010");
Response.Cookies.Add(hc);
hc = new HttpCookie("testcookie", "abc");
Response.Cookies.Add(hc);
This results in an HTTP header with two Set-Cookie calls:
Set-Cookie: testcookie=xyz; expires=Sun, 12-Dec-2010 07:00:00 GMT; path=/
Set-Cookie: testcookie=abc; expires=Sun, 12-Dec-2010 07:00:00 GMT; path=/
From there, it is up to the browser to decide whether first or last is the final value. If two browsers do it differently, you end up with the situation you describe. Install the Live HTTP Headers add-on and look for something similar. At the very least, you should probably consider "guid" to be a cookie name that you should use in an ASP.NET forms app.
If you absolutely need to have multiple places set the same cookie, try to find it first (create a new one if it doesn't exist). This will ensure you are overriding the value of the existing cookie rather than creating another cookie with the same name.
HttpCookie hc = Response.Cookies["testcookie"];
if (null == hc) {
hc = new HttpCookie("testcookie");
Response.Cookies.Add(hc);
}
hc.Value = "xyz";
First off, there's a type-safe constructor for DateTime, which is new DateTime(2010, 12, 12).
Second, you're using different names for your cookie: guid vs applicationGuid. Use either, not both.