Clearing multiple cookies - asp.net

The code below tries to clear the cookies for all domains once a user logs out of the system. For some reason, only the last domain in the array is cleared. Why does this happen? Am I doing something wrong?
For example, if I change the size of the array to 4 and then change the for loop to only go to 3, then it only logs me out of y.xcv.com.
As a sidenote, I have this loop working on a different server that uses a slightly different function to clear the cookies.
Edit: Code updated per suggestions below. Now it fails on the "as HttpCookie" line. Do I need to include some library?
Dim aDomain(12)
Dim ESidCookie, WIdCookie, EBidCookie, TSidAccessCookie, PSidAccessCookie, SSidCookie As HttpCookie
aDomain(0) = ".x.com"
aDomain(1) = "y.x.com"
aDomain(2) = "y.x.com"
aDomain(3) = "y.xcv.com"
aDomain(4) = "x.com"
aDomain(5) = "y.z.a.com"
aDomain(6) = "y.z.a.com"
aDomain(7) = "z.a.com"
aDomain(8) = ""
aDomain(9) = "y.x.com"
aDomain(10) = "y.x.com"
aDomain(11) = "y.x.com"
for count = 0 to 11
strDomain = aDomain(count)
response.Write count & "/" & strDomain
ESidCookie = New HttpCookie("oneCookie")
ESidCookie.Domain = strDomain
ESidCookie.Path = "/"
ESidCookie = ""
ESidCookie.Expires = now() - 100
Response.Cookies.Add(ESidCookie)
WIdCookie = New HttpCookie("twoCookie")
WIdCookie.Domain = strDomain
WIdCookie.Path = "/"
WIdCookie = ""
WIdCookie.Expires = now() - 100
Response.Cookies.Add(WIdCookie)
EBidCookie = New HttpCookie("threeCookie")
EBidCookie.Domain = strDomain
EBidCookie.Path = "/"
EBidCookie = ""
EBidCookie.Expires = now() - 100
Response.Cookies.Add(EBidCookie)
TSidAccessCookie = New HttpCookie("fourCookie")
TSidAccessCookie.Path = "/"
TSidAccessCookie = "LoggedOut"
Response.Cookies.Add(TSidAccessCookie)
PSidAccessCookie = New HttpCookie("fiveCookie")
PSidAccessCookie.Domain = strDomain
PSidAccessCookie.Path = "/"
PSidAccessCookie = ""
PSidAccessCookie.Expires = now() - 100
Response.Cookies.Add(PSidAccessCookie)
SSidCookie = New HttpCookie("sixCookie")
SSidCookie.Domain = strDomain
SSidCookie.Path = "/"
SSidCookie = ""
SSidCookie.Expires = now() - 100
Response.Cookies.Add(SSidCookie)
next
Any help is appreciated. Thanks!

The Response.Cookies collection is keyed off of the cookie name so you are just changing the domain of the same cookie each time you go through your loop. That's why the last one wins.
You could try creating a new cookie object and adding that to the Response.Cookies collection in your loop instead.

If you want to clear all cookies you will should create all new ones with the same name. Here is a basic example that should get you going:
Dim newCookie As HttpCookie
For i As Integer = 0 To 10
' creating a new cookie each time
newCookie = New HttpCookie(cookieNames(i))
' expire the cookie
newCookie.Expires = DateTime.Now.AddDays(-1)
' storing the new cookie each time
Response.Cookies.Add(newCookie)
Next
It doesn't look like your creating all new cookies and adding them to the response properly.

Related

Response.Redirect error

I have form page that collects data. The user clicks SUBMIT, which goes to a "post page. At the end of this page is the redirect code I am using.
response.redirect( "test.asp?ChecklistID=" + ChecklistID )
For some reason, the result is this.
/test.asp?ChecklistID=4784,%204784
Why is this returning in TWO ID's? I only have ONE record in the 'results' table. And it is '4784'.
Adding the code
<%
'Option Explicit
Dim SQLStmt, sql, RS, ChecklistID, Location, ChecklistDate, Driveup,
ConnectString, conn, objconn
Dim weeds, parking_lot, sidewalk, windows, exterior_trash, door_clean
Dim mats_clean, Notes_page1
Location = Request("Location")
ChecklistDate = Request("ChecklistDate")
Driveup = Request("Driveup")
ChecklistID = Request("ChecklistID")
weeds = Request("weeds")
parking_lot = Request("parking_lot")
sidewalk = Request("sidewalk")
windows = Request("windows")
exterior_trash = Request("exterior_trash")
door_clean = Request("door_clean")
mats_clean = Request("mats_clean")
Notes_page1 = Request("Notes_page1")
ConnectString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &
Server.MapPath("../xyz/mydatabase.mdb")
Set conn = Server.CreateObject("ADODB.Connection")
conn.open ConnectString
SQLStmt = "SELECT * FROM Results WHERE ChecklistID =" & ChecklistID & " ; "
Set RS = Server.CreateObject("ADODB.Recordset")
RS.open "Results", conn, 3, 3
RS.Update
RS("ChecklistDate") = ChecklistDate
RS("Driveup") = Driveup
RS("weeds") = weeds
RS("parking_lot") = parking_lot
RS("sidewalk") = sidewalk
RS("windows") = windows
RS("exterior_trash") = exterior_trash
RS("door_clean") = door_clean
RS("mats_clean") = mats_clean
RS("Notes_page1") = Notes_page1
RS.Update
RS.close
set RS = nothing
conn.close
set conn = nothing
response.redirect( "test.asp?ChecklistID=" + ChecklistID )
%>
The browser might be retaining some history with response.redirect. Try using Server.Transfer. Or, if it's the same page, you might not have to re-add the query string.
Solved
I had the same hidden field in there twice causing the issue.

Devexpress Xtragrid TileView

I'm using Devexpress Xtragrid TileView module.
Basically I want my code works like this :
user input member ID on the upper left textbox and press load.
If they exists, then a Tile will be appeared.
A tile should contain : Name, Status, member ID and a photo.
If user press load again (either same ID or another ID) a Tile will be added also, and so on. Unless they press Clear & Load, It should be only 1 latest tile left.
So, I'm able to produce up to Step 3.
But I couldn't be able to load the picture.
The picture itself, It's not a byte array. It's a Image path.
e.q : D:/test/1.jpg
So, how do I load the picture?
Protected Overridable Sub InitData()
Try
Dim homesTable = ds.Tables(0)
homesTable.Columns.Add("ImageCol")
For Each row_Renamed As DataRow In homesTable.Rows
Dim img As Image = Image.FromFile(row_Renamed("memberPhoto")) 'I tried this, but didn't work
row_Renamed("ImageCol") = img
Next row_Renamed
GridControl1.DataSource = homesTable
Catch
End Try
End Sub
Private Sub setupTile()
'For i = 0 To j - 1
Try
TileView1.BeginUpdate()
'TileView1.DataSource = ds.Tables(0)
TileView1.OptionsTiles.RowCount = 3
TileView1.OptionsTiles.Padding = New Padding(20)
TileView1.OptionsTiles.ItemPadding = New Padding(10)
TileView1.OptionsTiles.IndentBetweenItems = 20
TileView1.OptionsTiles.ItemSize = New Size(320, 170)
TileView1.Appearance.ItemNormal.ForeColor = Color.White
TileView1.Appearance.ItemNormal.BorderColor = Color.Transparent
'Setup tiles template
Dim leftPanel As New TileViewItemElement()
Dim splitLine As New TileViewItemElement()
Dim nameCaption As New TileViewItemElement()
Dim nameValue As New TileViewItemElement()
Dim statusCaption As New TileViewItemElement()
Dim statusValue As New TileViewItemElement()
Dim RGPCaption As New TileViewItemElement()
Dim RGPvalue As New TileViewItemElement()
Dim imageTile As New TileViewItemElement()
TileView1.TileTemplate.Add(leftPanel)
TileView1.TileTemplate.Add(splitLine)
TileView1.TileTemplate.Add(nameCaption)
TileView1.TileTemplate.Add(nameValue)
TileView1.TileTemplate.Add(statusCaption)
TileView1.TileTemplate.Add(statusValue)
TileView1.TileTemplate.Add(RGPCaption)
TileView1.TileTemplate.Add(RGPvalue)
TileView1.TileTemplate.Add(imageTile)
'
'nameValue.Text = ""
'statusValue.Text = ""
'RGPvalue.Text = ""
'imageTile.Image = Nothing
'
leftPanel.StretchVertical = True
leftPanel.Width = 190
leftPanel.TextLocation = New Point(-10, 0)
leftPanel.Appearance.Normal.BackColor = Color.FromArgb(58, 166, 101)
'
splitLine.StretchVertical = True
splitLine.Width = 3
splitLine.TextAlignment = TileItemContentAlignment.Manual
splitLine.TextLocation = New Point(190, 0)
splitLine.Appearance.Normal.BackColor = Color.White
'
nameCaption.Text = "Name"
nameCaption.TextAlignment = TileItemContentAlignment.TopLeft
nameCaption.Appearance.Normal.FontSizeDelta = -1
'
nameValue.Column = TileView1.Columns("preferredName")
nameValue.AnchorElement = nameCaption
nameValue.AnchorIndent = 2
nameValue.MaxWidth = 200
nameValue.Appearance.Normal.FontStyleDelta = FontStyle.Bold
'nameValue.Text = ds.Tables(0).Rows(i)("preferredName").ToString
'
statusCaption.Text = "Status"
statusCaption.AnchorElement = nameValue
statusCaption.AnchorIndent = 14
statusCaption.Appearance.Normal.FontSizeDelta = -1
'
statusValue.Column = TileView1.Columns("memberStatus")
statusValue.AnchorElement = statusCaption
statusValue.AnchorIndent = 2
statusValue.Appearance.Normal.FontStyleDelta = FontStyle.Bold
'statusValue.Text = ds.Tables(0).Rows(i)("memberStatus").ToString
'
RGPCaption.Text = "RGP"
RGPCaption.AnchorElement = nameValue
RGPCaption.AnchorIndent = 65
'RGPCaption.TextLocation
'RGPCaption.Appearance.Normal.FontSizeDelta = -1
RGPCaption.Appearance.Normal.Font = New Font("Segoe UI Semibold", 12.0F, System.Drawing.FontStyle.Regular)
'
RGPvalue.Column = TileView1.Columns("code")
RGPvalue.AnchorElement = RGPCaption
RGPvalue.AnchorIndent = 1
RGPvalue.TextAlignment = TileItemContentAlignment.BottomLeft
RGPvalue.Appearance.Normal.Font = New Font("Segoe UI Semilight", 25.75F, System.Drawing.FontStyle.Regular)
'RGPvalue.Text = ds.Tables(0).Rows(i)("code").ToString
'
imageTile.Column = TileView1.Columns("ImageCol")
imageTile.ImageSize = New Size(120, 170)
imageTile.ImageAlignment = TileItemContentAlignment.MiddleRight
imageTile.ImageScaleMode = TileItemImageScaleMode.Stretch
imageTile.ImageLocation = New Point(12, 0)
Catch ex As Exception
XtraMessageBox.Show(ex.Message)
Finally
TileView1.EndUpdate()
End Try
'Next
End Sub
Private Sub loadBtn_Click(sender As Object, e As EventArgs) Handles loadBtn.Click
initData()
setupTile()
End Sub
Maybe it's too late but in my case only need to read file from disk and assign to a byte() column.
First of all, table column should be byte array so replace:
homesTable.Columns.Add("ImageCol")
for:
homesTable.Columns.Add(New DataColumn("ImageCol", GetType(Byte)))
Then I'd try to replace:
row_Renamed("ImageCol") = img
for:
row_Renamed("ImageCol") = IO.File.ReadAllBytes(row_Renamed("memberPhoto"))
That would load disk file to byte array and shown in tile. I'd check if file exists to avoid exceptions.
That's what I do to load image from disk.
Hope it helps.

aspx.vb cookie value accessing and updating

I am coding an ASP application where a users data will be stored in a cookie(that expires in 24 hours) and when the program is run, it is supposed to search that cookie, and add whatever was in the cookie to the current users value, then proceed through the code.
Dim I As Integer ' iterator for cookie search
Dim foundcookie As Boolean = False ' flag if cookie found
Dim stakenow As Integer ' current stake held here
stakenow = stake.Text
Dim currentname As String
currentname = name.Text
For I = 0 To Request.Cookies.Count - 1
If Request.Cookies.Item(I).Name = currentname Then
foundcookie = True
stakenow = stakenow + Request.Cookies.Item(I).Value
currentstake.Text = currentstake.Text + stakenow.ToString
Request.Cookies.Item(I).Value = stakenow.ToString
Request.Cookies.Item(I).Expires = DateTime.Now.AddHours(24)
End If
Next
If Not foundcookie Then
Dim nameCookie As New HttpCookie(currentname)
nameCookie.Value = stakenow.ToString
nameCookie.Expires = DateTime.Now.AddHours(24)
Response.Cookies.Add(nameCookie)
currentstake.Text = currentstake.Text + stakenow.ToString
End If
This code works, the first time, it creates a cookie with a value, say 150. Then the next time the code is run and the users "stake" that they entered was 150 again, the current stake updates to 300. However the 3rd time run, if the user enters 100, we would want the users stake now to be 400, however is is only 250. I see this error is coming from the updated value not being correctly written back to the cookie, thus the addition only coming from the original value when the cookie was created, and the typed value. I have tried using request and response cookies and have had no luck. Any suggestions?
Use the HttpCookieCollection.Set Method so that the updated cookie gets back to the client:
If Request.Cookies.Item(I).Name = currentname Then
foundcookie = True
stakenow = stakenow + Request.Cookies.Item(I).Value
currentstake.Text = currentstake.Text + stakenow.ToString
Dim objCookie As HttpCookie = Request.Cookies.Item(I)
objCookie.Value = stakenow.ToString()
objCookie.Expires = DateTime.Now.AddHours(24)
HttpContext.Current.Response.Cookies.Set(objCookie)
End If

Array list error second array replace the first array

I have a problem.
Dim Maxis As String
'Dim MaxisExtra As String
Dim b As New ArrayList
Dim WS As New WebService1.Service1
Dim cnt As String
Dim MRWS As New MobileReload_WS.MobileReload_WS
cnt = WS.StockCountTelco(1, Session("Maxis"))
If CInt(cnt) >= CInt(DropDownList1.SelectedItem.Text) Then
Dim sLock As String
sLock = MRWS.LockAStock(1, 1, "Online", Session("Maxis"), DropDownList1.SelectedItem.Text)
Session("sLock") = sLock
If sLock = "" Then
PopupMsgBox("Unable to allocate Stock")
Else
Maxis = "Maxis" & ";" & Session("Maxis") & ";" & DropDownList1.SelectedItem.Text & ";" & Session("Cost")
'If MaxisExtra = "" Then
' b.Add(Maxis)
' Elseif
' MaxisExtra = MaxisExtra + Maxis
' b.Add(MaxisExtra)
'End If
End If
Else
PopupMsgBox("Not enough stock")
End If
b.Add(Maxis)
Session("Transaction") = b
End Sub
The first time i enter the string into the arraylist it is okay. But when the user press the button add again the second time, it replace the first string. Can anyone help me how to save the string into the second slot based on my coding?
If you're talking about the b ArrayList, then you're creating a new one each time and storing the new ArrayList in Session("Transaction")
Maybe you mean something like this instead...
Dim b as ArrayList = Session("Transaction")
If b Is Nothing Then
b = new ArrayList
End If
...
Session("Transaction") = b
Although it's difficult to say exactly, because your code is very messy and not clear
You put the array list in a session variable, but you never read it back. You create a new array list each time, so it will always be empty and replace the previous one.
Get the array list from the session variable if there is one:
Dim b As ArrayList = Session("Transaction")
If b Is Nothing Then b = New ArrayList

Last Five Pages Visited Cookie

So, I have a series of product pages and all I'd like to do is store the last 5 products viewed in a cookie so it can be displayed as a site-history. The problem I have isn't adding the five initial items to the cookie, its when they view 6, 7 or 10 items. Does anyone have any really decent suggestions on how to tackle this?
Currently I have this flawed logic (i have replaced the cookie name (xxx) for brevity);
Dim i As Integer = 0
Dim productcount As Integer = 0
If HttpContext.Current.Request.Cookies("xxx") Is Nothing Then
Dim gingernuts As New HttpCookie("xxx")
gingernuts.Values("productcount") = 0
gingernuts.Expires = DateTime.Now.AddDays(365)
HttpContext.Current.Response.Cookies.Add(gingernuts)
End If
productcount = HttpContext.Current.Request.Cookies("xxx")("productcount")
For i = 0 To productcount
If HttpContext.Current.Request.Cookies("xxx")("product" & i & "") = "" Then
HttpContext.Current.Response.Cookies("xxx")("product" & i & "") = Request.QueryString("id")
Else
HttpContext.Current.Response.Cookies("xxx")("product" & i & "") = HttpContext.Current.Request.Cookies("xxx")("product" & i & "")
End If
Next
If productcount = 5 Then
HttpContext.Current.Response.Cookies("xxx")("productcount") = 5
HttpContext.Current.Response.Cookies("xxx")("product0") = ""
Else
HttpContext.Current.Response.Cookies("xxx")("productcount") = productcount + 1
End If
Suggestions and critisism welcomed and appreciated.
Chris
Just use a simple cookie value which is a comma delimited list of the most recently viewed product IDs. (Note my VB.NET is that strong).
MostRecentIDs as String() '' // Instance level variables
Const ListSize = 5
'' // in a method somewhere
context As HttpContext = HttpContext.Current
cookie As HttpCookie = context.Request.Cookies("mri")
mri As Queue(Of String)
If cookie Is Nothing Then
mri = New Queue(Of String)(cookie.Value.Split(",".ToCharArray())
Else
mri = New Queue(Of String)
cookie = New HttpCookie("mri")
End If
If mri.Contains(Request.QueryString("id")) Then
If mri.Count >= ListSize Then mri.Dequeue()
mri.Enqueue(Request.QueryString("id"))
End If
MostRecentIDs = mri.ToArray();
cookie.Value = String.Join(",", MostRecentIDs)
cookie.Expires = DateTime.Now.AddDays(365)
context.Response.Add(cookie)
Now you have access to the most recent product IDs as a simple string array.
This code handles the case where the cookie has not yet been created.
The cookie itself is much smaller.
Managing the size of the list can easily be paramaterised.
Code above based on the tested C# code below that I dropped into an empty ASPX file:-
const int listSize = 8;
string[] _mru;
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["mru"];
Queue<string> mru;
if (cookie != null)
{
mru = new Queue<string>(cookie.Value.Split(','));
}
else
{
mru = new Queue<string>();
cookie = new HttpCookie("mru");
}
if (!mru.Contains(Request.QueryString["id"]))
{
if (mru.Count >= listSize) mru.Dequeue();
mru.Enqueue(Request.QueryString["id"]);
}
_mru = mru.ToArray();
cookie.Value = String.Join(",", _mru);
cookie.Expires = DateTime.Now.AddDays(365);
Response.Cookies.Add(cookie);
}
This is how i will do it, if I am understanding your question right :)
If product count is less than 5 just append the new product. Else replace product0 with product1 till 4 and then add new product at 4
If productcount < 5 Then 'Do the null value check before this
HttpContext.Current.Response.Cookies("xxx")("productcount") = productCount + 1
HttpContext.Current.Response.Cookies("xxx")("product" & productCount + 1) = ""
Else
For i = 0 To productcount - 1
'Replace product 0 with 1, 1 with 2...till 3 with 4
HttpContext.Current.Response.Cookies("xxx")("product" & i & "") = HttpContext.Current.Response.Cookies("xxx")("product" & i + 1& "")
Next
HttpContext.Current.Response.Cookies("xxx")("product" & 4 & "") = Request.QueryString("id")
End If
Anthony answered this question perfectly, but for future reference and for those using VB, this is the code:
Imports System.Collections.Generic
Const listSize As Integer = 5
Private _mru As String()
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim cookie As HttpCookie = Request.Cookies("mru")
Dim mru As Queue(Of String)
If cookie IsNot Nothing Then
mru = New Queue(Of String)(cookie.Value.Split(","c))
Else
mru = New Queue(Of String)()
cookie = New HttpCookie("mru")
End If
If mru.Count >= listSize Then
mru.Dequeue()
End If
mru.Enqueue(Request.QueryString("id"))
_mru = mru.ToArray()
cookie.Value = [String].Join(",", _mru)
cookie.Expires = DateTime.Now.AddDays(365)
Response.Cookies.Add(cookie)
End Sub
Many thanks to all the contributors here also.

Resources