Writing cookies from include file

B

Brian Burgess

Hi all,

Anyone know if this is possible? If so, on which page would the
cookie be? .. On the page calling a function defined in the include
file?

thanks in advance..

-BB
 
R

Ray at home

Brian Burgess said:
Hi all,

Anyone know if this is possible?

Yes. The include file is part of the calling page, for all intents and
purposes.

If so, on which page would the
cookie be? .. On the page calling a function defined in the include
file?

What do you mean, what page would it be on? The cookie is on the client and
is available from any page in your domain then. Example

page1.asp includes a file called cookie.asp, which writes a cookie.
page2.asp can pull that cookie if you want it to.

Ray at home
 
B

Brian Burgess

Really? cool.

So I can do:
<%
Response.Cookies("cookie1") = "blah"
Response.Cookies("cookie1").Expires=DateAdd("n", 15, Now)
Server.Execute("page2.asp")
...
...
%>

Then in page2.asp I can do something like:
<%
Dim strCookie1
strCookie1 = Request.Cookies("cookie1")
%>

This will work? It has not been for me so far, but maybe I have
other issues going on.

I tried some sample cookie code from CodeProject
('http://www.codeproject.com/asp/cookies.asp'). This is working fine,
my own code similar to this is not writing the cookie. :-(

Thanks,

-BB
 
J

Jacob Yang [MSFT]

Hi Brian,

There should be a server-client round-trip between the code to create a
cookie and the code to retrieve the same cookie.

The cookie is available only in the subsequent requests to the web server.

Best regards,

Jacob Yang
Microsoft Online Partner Support
<MCSD>
Get Secure! ¨C www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
B

Brian Burgess

Of Course.. The page shown will get 'Server.Execute'd in a loop. If a
connection break occurs, the user logs in again, and the cookie tell
us at which loop the break occurred. :)
 
B

Brian Burgess

to go on..
But since it never writes the cookie .. the process as outlined doesnt
work.. :-(
 
R

Ray at

Maybe your cookie issues have to do with your expiration methods. IIRC, you
cannot specify that a cookie expires at a certain hour. You can only
specify the calendar date. You're expiring your cookies by adding hours to
the current time, so if you wind up being on the same calendar date after
adding the hours, your cookie would expire today. Maybe your code will work
in the evening. :]

Ray at work
 
B

Brian Burgess

Well I do have sample code from CodeProject that is working. I
changed that code to look like the way I am expiring and it works
there.. the cookie really only does last 10 minutes, as I specify in
the code. Although the last time I tried this test was at 2PM ;-)
Here is the sample from CodeProject:
*******************************************************************************
<%@ Language=VBScript %>
<%
Option Explicit
On Error Resume Next

' test if the client browser support cookies
dim objBrowserCapabilities
dim blnSupportCookies

set objBrowserCapabilities =
server.CreateObject("MSWC.BrowserType")
if Err.number <> 0 then
Response.Write "Error: Can't create MSWC.BrowserType
object."
Response.End
end if
' get the cookies boolean value
blnSupportCookies = objBrowserCapabilities.cookies
if UCase(blnSupportCookies) <> "TRUE" then
blnSupportCookies = false
end if
set objBrowserCapabilities = nothing

' global declaration
dim index
dim indexKey

' verify if the user wants write a cookie dictionary
dim strWriteCookieDictionary
dim blnWriteCookieDictionary
blnWriteCookieDictionary = false
strWriteCookieDictionary = request("WriteCookieDictionary")

if strWriteCookieDictionary <> "" then
dim intKeysNumber

intKeysNumber = request("NumberOfKeys")
' test if intKeysNumber is a valid number
if intKeysNumber < 0 or not IsNumeric(intKeysNumber)
then
Response.Write "Error: You provided an invalid
value for keys number! (must be integer > 0)"
Response.End
else
blnWriteCookieDictionary = true
Session("sintKeysNumber") = intKeysNumber
end if
end if ' strWriteCookieDictionary <> ""

' verify if the user submited the page
dim strSubmit
strSubmit = request("Submit")

if strSubmit <> "" then
' declare used variables
dim strCookieName
dim strCookieValue
dim astrCookieKeyName()
dim astrCookieKeyValue()
dim strCookieExpires
dim strCookieExpiresDate
dim strCookieExpiresHour

' read the objects values from request
strCookieName = request("CookieName")
strCookieValue = request("CookieValue")
strCookieExpires = request("CookieExpires")
strCookieExpiresDate = request("CookieExpiresDate")
strCookieExpiresHour = request("CookieExpiresHour")

' if CookieValue is empty is possible user write a
dictionary
' looping the form collection to search Key names and
values
if strCookieValue = "" then
dim intKeysCount
intKeysCount = 0
for each index in Request.Form
if Left(index,4) = "KeyN" then
intKeysCount = intKeysCount +
1
redim preserve
astrCookieKeyName(intKeysCount)
redim preserve
astrCookieKeyValue(intKeysCount)

astrCookieKeyName(intKeysCount
- 1) = request("KeyName_" & intKeysCount)

astrCookieKeyValue(intKeysCount - 1) = request("KeyValue_" &
intKeysCount)
end if
next
end if

' if CookieName isn't empty then save the cookie
if Trim(strCookieName) <> "" then
' write the cookies to client browser
if intKeysCount = 0 then
Response.Cookies(strCookieName) =
strCookieValue
else
for index = 0 to intKeysCount - 1

Response.Cookies(strCookieName)(astrCookieKeyName(index)) =
astrCookieKeyValue(index)
next
end if
' test if the cookie has a expiration date and
set it
if strCookieExpires = "FALSE" then

'Response.Cookies(strCookieName).expires = strCookieExpiresDate & " "
& strCookieExpiresHour
'*****************
'my change is here
'*****************

Response.Cookies(strCookieName).expires = DateAdd("n", 10, Now())
end if
end if
end if ' strSubmit <> ""

%>
<html>
<head>
<script language="JavaScript">
<!--
//'*********************************************************************************
//' Description: Set the disabled property to edit objects
//' Assumptions: None
//' Effects: Disabling or enabling edit objects
//' Arguments: {p_strOption] - string value
//' Returns: None
//' Version: [01/31/2000 - Iulian Iuga]
//'*********************************************************************************

function ShowHide(p_strOption)
{
if (p_strOption == 'TRUE')
{
document.WriteCookies.CookieExpiresDate.disabled =
true
document.WriteCookies.CookieExpiresHour.disabled =
true
}
else
{
document.WriteCookies.CookieExpiresDate.disabled =
false
document.WriteCookies.CookieExpiresHour.disabled =
false
}
}
//-->
</script>
</head>
<body>
<center><h2>Read and write cookies to your browser</h2></center>
<hr>
<br>
<% if not blnSupportCookies then
Response.Write "<b>Your browser doesn't support
cookies!</b>"
else
%>
<h3>Read Cookies:</h3>
<%
' looping trough cookies collection
for each index in Request.Cookies
' test if cookie is dictionary
if Request.Cookies(index).HasKeys then
Response.Write "&nbsp;&nbsp;
<b>Cookie</b> <i>" & index & "</i> <b>is dictionary</b>"
Response.Write
"&nbsp;&nbsp;&nbsp;&nbsp; Count = " & Request.Cookies(index).Count &
"<br>"
for each indexKey in
Request.Cookies(index)
Response.Write
"&nbsp;&nbsp;&nbsp;&nbsp; <b>Key</b> <i>" & indexKey & "</i> = <i>" &
Request.Cookies(index)(indexKey) & "</i><br>"
next
else
Response.Write "&nbsp;&nbsp;
<b>Cookie</b> <i>" & index & "</i> = <i>" & Request.Cookies(index) &
"</i><br>"
end if
next
%>
<hr>
<br>
<h3>Write Cookies:</h3>
<form name="WriteCookies" action="default.asp" method="POST">
<input type="Submit" name="WriteCookieDictionary"
value="Write cookie dictionary">&nbsp;&nbsp; <b>with</b>
&nbsp;&nbsp;<input type="text" name="NumberOfKeys" value="0" size="3"
maxlength="3">&nbsp;&nbsp; <b>keys.</b>
<br><br>
<table border="0">
<tr><td>Cookie Name:&nbsp;</td>
<td><input type="text" name="CookieName"
value="" size="20"></td></tr>
<% if not blnWriteCookieDictionary or
intKeysNumber = 0 then %>
<tr><td>Cookie Value:&nbsp;</td>
<td><input type="text" name="CookieValue"
value="" size="20"></td></tr>
<% else
for index = 1 to intKeysNumber
Response.Write
"<tr><td>&nbsp;&nbsp;Key_" & index & " Name:&nbsp;</td>"
Response.Write "<td><input
type='text' name='KeyName_" & index & "' value=''
size='15'></td></tr>"
Response.Write
"<tr><td>&nbsp;&nbsp;Key_" & index & " Value:&nbsp;</td>"
Response.Write "<td><input
type='text' name='KeyValue_" & index & "' value=''
size='15'></td></tr>"
next
end if
%>
</table><br>
<input type="radio" name="CookieExpires" value="TRUE"
onclick="ShowHide('TRUE')" checked> Expires after shut down this
session<br>
<input type="radio" name="CookieExpires" value="FALSE"
onclick="ShowHide('FALSE')"> Don't expires (populate Date and
Hour)<br>
<table border="0">
<tr><td>Date:&nbsp;</td>
<td><input type="text"
name="CookieExpiresDate" value="<%=Date%>" size="10"
disabled>(Month/Day/Year - i.e. 2/1/2000)</td></tr>
<tr><td>Hour:&nbsp;</td>
<td><input type="text"
name="CookieExpiresHour" value="<%=Time%>" size="10"
disabled>(Hour/Minutes/Seconds - i.e. 2:30:25 PM)</td></tr>
</table>
<br>
<hr>
<input type="Submit" name="Submit"
value="Submit">&nbsp;&nbsp;&nbsp;&nbsp;
<button name="Help" value="Help" alt="Help"
onclick="window.showModalDialog('help.asp')">Help</button>
</form>
<% end if %>

</body>
</html>
********************************************************************************


Maybe your cookie issues have to do with your expiration methods. IIRC, you
cannot specify that a cookie expires at a certain hour. You can only
specify the calendar date. You're expiring your cookies by adding hours to
the current time, so if you wind up being on the same calendar date after
adding the hours, your cookie would expire today. Maybe your code will work
in the evening. :]

Ray at work

Brian Burgess said:
to go on..
But since it never writes the cookie .. the process as outlined doesnt
work.. :-(

rights.
 
J

Jacob Yang [MSFT]

Hi Brian,

I am sorry if there is any misunderstanding.

Cookies are passed among http header and request. Cookies retrieve the
values of the cookies sent in an HTTP request. However, to get the
specified cookie from the http request, the following two conditions should
be matched,

1. We should first set it via the response.cookies collection in a previous
http response.
2. The current http request has already contains the cookie we want to
retrieve. That is, the cookie set in step 1 should have been reached to the
browser side.

In this case, why we cannot get the specified cookie is because the cookie
was just set in the same http response and that response has not reached to
the client. So the cookie is not get.

Does it answer your question? If I have misunderstood your concern, please
feel free to let me know.

Best regards,

Jacob Yang
Microsoft Online Partner Support
<MCSD>
Get Secure! ¨C www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
B

Brian Burgess

Yes there is misunderstanding .. and MY apologies as I should have
made this more clear..

This page will get requested continuously in a loop from another page.
The cookie should NOT be set when checking the request.cookies
collection in the first loop(obviously). But, it should be set in
subsequest loops, it is not. I have my browser (IE60) set to prompt
me when a cookie is to be written. This is not happening. That is
how I know the cookie is not being written for sure.

I have a test page with similar code, but of course not identical and
it is writing cookies. And I do get the prompt from my browser to
write the cookie..

More clear?

Thanks for the help :)

-BB
 
M

Michael D. Kersey

Brian said:
So I can do:
<%
Response.Cookies("cookie1") = "blah"
Response.Cookies("cookie1").Expires=DateAdd("n", 15, Now)

This code builds a cookie in the Response object, but it does not send
the cookie to the browser yet. The cookie (which is an HTTP "Set-Cookie"
header) will be sent to the browser after the script terminates.
Server.Execute("page2.asp")
..
%>

Then in page2.asp I can do something like:
<%
Dim strCookie1
strCookie1 = Request.Cookies("cookie1")
%>

Since the cookie has not yet been sent to the browser, the Request
object will not be able to fetch that cookie. Only after your script
terminates will the cookie be sent.

Good Luck,
Michael D. Kersey
 
B

Brian Burgess

Hi Michael,

So what if then page1.asp Server.Executes page2.asp in a loop. And
the cookies are then set in page2.asp .. should the cookies not then
write?

thanks,

-BB
 
J

Jacob Yang [MSFT]

Hi Brian,

It seems that there is some misunderstanding in this issue.

I have written a simple testing sample based on your code. It works on my
side.

1. Write the WRITECOOKIE.ASP file.
------------------------------
<%@ Language = VBScript %>
<%
Response.Cookies("CookieName")("UserName") = "Jacob Yang"
Response.Cookies("CookieName")("UserAge") = "25"
Response.Cookies("CookieName")("LastVisited") = Now()
Response.Cookies("CookieName").Expires = Date() + 7
Server.Execute("ReadCookie.asp")
%>
<HTML>
<BODY>
</BODY>
</HTML>
----------------------------

2. Write the READCOOKIE.ASP file
------------------------------
<%@ Language = VBScript %>
<%
Dim Name, Age, Last
Name = Request.Cookies("CookieName")("UserName") 'Read the first key
Age = Request.Cookies("CookieName")("UserAge") 'Read the second key
Last = Request.Cookies("CookieName")("LastVisited") 'Read the third key
%>
<HTML>
<BODY>
<P><I><%= Name %></I> Hello!Welcome to ASP/ASP.NET. Your age is <I><%=
Age %></I></P>
Last time you accessed our web site at <I><%= Last %></I>, Now the time
is <I><%= Now() %></I>.
</BODY>
</HTML>
------------------------------

3. Please make sure that the above two files are in the same folder:

\Inetpub\wwwroot\TestCookies

4. Test the http://localhost/TestCookies/WRITECOOKIE.ASP

Please tell me how to reproduce the problem with my testing sample. I
certaily appreciate your time.

Best regards,

Jacob Yang
Microsoft Online Partner Support
<MCSD>
Get Secure! ¨C www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
B

Brian Burgess

Yes, I have a sample page from CodeProject. I have modified this
sample page many times, each change to make it look more and more like
the production page. The sample page continues to work, but the
production page continues to fail. I am at a loss too. :-(

-BB
 
M

Michael D. Kersey

Brian said:
Hi Michael,
So what if then page1.asp Server.Executes page2.asp in a loop. And
the cookies are then set in page2.asp .. should the cookies not then
write?

The cookies aren't available until
- they are sent to the browser as part of a Response AND
- the browser sends a new Request.

Here's an example of how cookies work:
0. Browser and server establish a connection,
1. Browser sends request to server,
2. Server ASP code stores cookie in Response object,
3. Server sends contents of response object to browser,
4. Browser accepts response contents and stores cookie,
5. Browser and server close connection.
Only now is the cookie is available for any *subsequent* HTTP requests.

What you are trying to do (but which won't work):
0. Browser and server establish a connection,
1. Browser sends request to server,
2. Server ASP code stores cookie in *Response* object,
3. Server ASP code tries to read same cookie from *Request* object, but
it isn't there!
....
Writing a cookie to the Response object does not mean that it is
available immediately (in the same script) from the *Request* object.

Also note that Server.Execute does not establish a new connection; it
uses the same connection as the calling script.

If you want to pass variables from one script to the other, then use
Session or Application variables.

Good Luck,
Michael D. Kersey
 
J

Jacob Yang [MSFT]

Hi Brian,

I agree with your current troubleshooting method (starting from a simple
page and building it up to be more and more like your production page). I
suggest that you continue building this new page.

As I have been unable to reproduce your problem, I don't have anything more
to add. Please let me know if you have more information which will allow me
to assist you further.

Best regards,

Jacob Yang
Microsoft Online Partner Support
<MCSD>
Get Secure! ¨C www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
B

Brian Burgess

Well then my understanding of cookies is correct. What I am trying to
do is save some info in case a disconnect occurs at some point during
the loop. This is the reason for cookies, instead of session
variables. But you also mention something about Server.Execute:
This does send a request right? ..requesting a page? .. not
necessarily a new connection. In my test asp I can write without
closing the browser. Do you think explicitly calling Response.End at
the end of the Server.Executed page will work?

thanks..

-BB
 
B

Brian Burgess

Hi Jacob,

Yes I'm not able (so far) to reproduce it anywhere else either.
Funny how these things always only occur in production eh? ;-)


-BB
 
M

Michael D. Kersey

Brian said:
What I am trying to
do is save some info in case a disconnect occurs at some point during
the loop.

Try setting Response.Buffer = FALSE at the top of your page and/or doing
a Response.Flush after each cookie is set.

A cookie is an HTTP header type. HTTP headers are sent as part of an
HTTP request/response, but since they are headers, they must be sent
*before* any other page output is sent.

So if the ASP script is outputting cookies, it cannot output any other
page data (no starting <HTML> tag, no Response.Write's, not even a
single space) until *after* all cookies have been output. With buffering
disabled, the server should send the cookies to the browser as soon as
they are created. I am however unclear as to what is the obligation of
the browser (i.e., whether it should accept or reject cookies associated
with a connection) if a connection is abnormally terminated.

By default, buffering is enabled (Response.Buffer = TRUE) and cookies
would not be sent until either:
- the ASP page completes,
- a Response.Flush is issued or
- a Response.End is issued.
This is the reason for cookies, instead of session
variables.

IMO it would be safer and faster to save the loop counter in a session
variable. Since you are using cookies, Session variables are enabled
anyway, so why not use them?
But you also mention something about Server.Execute:
This does send a request right? ..requesting a page? .. not
necessarily a new connection.

No, it does not send a request. Server.Execute(xxx) is a server-side
function that executes the contents of page xxx inline (it acts like a
"call" to that page's code). IOW it is as if xxx was part of the calling
page.

Good Luck,
Michael D. Kersey
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,139
Latest member
JamaalCald
Top