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
Related
I have a reservation page and a reservation table which contains reservationstart column, reservationend column and numofdays column.
I have determined the number of days between the two dates which a client will select but nothing was stored in the table when I update.
The data type of numofdays was datatime but I have changed this to int.
I used this first, to declare the start and end date:
DayPilotScheduler1.Scale = TimeScale.Manual
Dim start As New Date(Date.Today.Year, 1, 1, 12, 0, 0)
Dim [end] As Date = start.AddYears(1)
This is the code for the update:
Protected Sub DayPilotScheduler1_EventMove(ByVal sender As Object, ByVal e As DayPilot.Web.Ui.Events.EventMoveEventArgs)
Dim id_Renamed As String = e.Value
Dim start As Date = e.NewStart
Dim [end] As Date = e.NewEnd
Dim resource As String = e.NewResource
Dim message As String = Nothing
If Not dbIsFree(id_Renamed, start, [end], resource) Then
message = "The reservation cannot overlap with an existing reservation."
ElseIf e.OldEnd <= Date.Today Then
message = "This reservation cannot be changed anymore."
ElseIf e.OldStart < Date.Today Then
If e.OldResource <> e.NewResource Then
message = "The room cannot be changed anymore."
Else
message = "The reservation start cannot be changed anymore."
End If
ElseIf e.NewStart < Date.Today Then
message = "The reservation cannot be moved to the past."
Else
dbUpdateEvent(id_Renamed, start, [end], resource)
'message = "Reservation moved.";
End If
LoadResourcesAndEvents()
DayPilotScheduler1.UpdateWithMessage(message)
End Sub
Private Sub dbUpdateEvent(ByVal id As String, ByVal start As Date, ByVal [end] As Date, ByVal resource As String)
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionStringLocal").ConnectionString)
con.Open()
Dim numOfDay As Integer = CInt(([end] - start).TotalDays())
Dim cmd As New SqlCommand("UPDATE [Reservation] SET ReservationStart = #start, ReservationEnd = #end, RoomId = #resource,numofday=#numofday WHERE ReservationId = #id", con)
cmd.Parameters.AddWithValue("id", id)
cmd.Parameters.AddWithValue("start", start)
cmd.Parameters.AddWithValue("end", [end])
cmd.Parameters.AddWithValue("resource", resource)
cmd.Parameters.Add("numofday", SqlDbType.Int).Value = numOfDay
cmd.ExecuteNonQuery()
End Using
End Sub
Screenshot of database table structure:
Math.floor(Math.abs(new Date(timestringone) - new Date(timestringtwo))/(1000*60*60*24))
Simply subtracting the dates returns the time in Milliseconds inbetween them. If the first time was before the second time the value is negative, so i used Math.abs to make it absolute. Then we divide trough 1000Milliseconds=1second, 60seconds=1minute, 60minutes=1hour, 24hours=1 day, and floor it to whole days. Requires two valid timestrings (timestringone and timestringtwo) to be given.
This is a javascript solution as youve included the js tag...
I am not sure about the VB.Net but you can easily accomplished it in C# using an object of Type "TimeSpan". For example: let's assume that we want to know the number of days between the start and end. values for the DateTime Type and show it in a Console window, then I may write something like:
DateTime start=DateTime.MinValue;
DateTime end=DateTime.MaxValue;
TimeSpan span=end-start;
Console.WriteLine( "There're {0} days between {1} and {2}" , span.TotalDays, start.ToString(), end.ToString() );
OP is having problems using the .Days property on the TimeSpan structure. I think this may help:
Dim numOfDay As Integer = CInt(([end] - start).TotalDays())
The output is:
365
Moving onto the use of your parameters, I think you would benefit from using .Add and specifying the data type:
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
cmd.Parameters.Add("#start", SqlDbType.Date).Value = start
cmd.Parameters.Add("#end", SqlDbType.Date).Value = [end]
cmd.Parameters.Add("#resource", SqlDbType.Int).Value = CInt(resource)
cmd.Parameters.Add("#numofday", SqlDbType.Int).Value = numOfDay
Note that you may have to change the SqlDbType. I've taken an assumption.
I would also implement Using for both the SqlConnection and SqlCommand. This for me is just good practice and the code does read better. I would also use the .Add overload for all parameters.
Using con As New SqlConnection(ConfigurationManager.ConnectionStrings("connectionStringLocal").ConnectionString),
cmd As New SqlCommand("UPDATE [Reservation] SET ReservationStart = #start, ReservationEnd = #end, RoomId = #resource, numofday = #numofday WHERE ReservationId = #id", con)
con.Open()
cmd.Parameters.Add("#id", SqlDbType.Int).Value = id
cmd.Parameters.Add("#start", SqlDbType.Date).Value = start
cmd.Parameters.Add("#end", SqlDbType.Date).Value = [end]
cmd.Parameters.Add("#resource", SqlDbType.Int).Value = CInt(resource)
cmd.Parameters.Add("#numofday", SqlDbType.Int).Value = CInt(([end] - start).TotalDays())
Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
If rowsAffected = 0 Then
'nothing updated
Else
'something updated
End If
End Using
I used to have this working as so....
Dim AnnEnt As Label = FormView1.FindControl("Holiday_RemainingLabel")
txtNoofDays.Text.ToString()
AnnEnt.Text.ToString()
If txtNoofDays.Text >= AnnEnt.Text Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
Else
I've recently change it to this and it no longer works
Dim remain As TextBox = FormView1.FindControl("Holiday_RemainingTextBox")
txtNoofDays.Text.ToString()
remain.Text.ToString()
If txtNoofDays.Text >= remain.Text Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
Else
What is the difference between the textbox in the formview and label in the formview to keep this from working?
i've since tried...
Dim days = txtNoofDays.Text
days.ToString()
AnnEnt.Text.ToString()
remain.Text.ToString()
If remain.Text.ToString < days.ToString Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
If you want to compare strings numerical, cast them to numbers.
For example(asssuming they are ints):
Dim remain As TextBox = FormView1.FindControl("Holiday_RemainingTextBox")
Dim remaining = Int32.Parse(remain.Text)
Dim numOfDays = Int32.Parse(txtNoofDays.Text)
If numOfDays >= remaining Then
lblHolRequestResponse.Text = "Your holiday could not be saved"
End If
Int32.Parse Method
Otherwise you're comparing alphabetically.
String.CompareTo Method
I have searched high and low to no avail, and this is last step before completing my project so please help! Thanks in advance!
The user will select an entry in a gridview, which then redirects them to a form that is populated with the data from the selected row (thus making the gridview editable in a more user friendly way). Null values are accepted by the DB and I would like to show null date values as blank (or " ") in the corresponding text boxes. Instead I get the error:
Conversion from type 'DBNull' to type 'Date' is not valid.
Here is my code:
'preceded by connection code
Dim sqlcmd As String = "SELECT * from Master WHERE RecNum = #recnum"
'Dim sqlCmd As New OleDb.OleDbCommand("SELECT * from Master WHERE RecNum = #recnum", connection)
Dim FileCommand3 As New OleDb.OleDbCommand(sqlcmd, connection)
FileCommand3.Parameters.AddWithValue("#recnum", user)
Dim Reader3 As OleDb.OleDbDataReader = FileCommand3.ExecuteReader()
If Reader3.Read Then
stock = myCStr(Reader3("StockNum"))
make = myCStr(Reader3("Make"))
color = myCStr(Reader3("Color"))
stockin = myCStr(Reader3("Stockin"))
ucistart = myCStr(Reader3("UCIStartDate"))
repairs = Reader3("Repairs")
tires = Reader3("tiresneeded")
onlot = Reader3("onlot")
sold = Reader3("sold")
year = myCStr(Reader3("year"))
model = myCStr(Reader3("model"))
location = Reader3("location")
srvcRO = myCStr(Reader3("svcROnum"))
ucicompldate = myCStr(Reader3("uciestcompletedate"))
collRO = myCStr(Reader3("collisionROnum"))
other = myCStr(Reader3("other"))
offprop = Reader3("offProperty")
detail = (Reader3("detail")
End If
connection.Close()
SoldCheckBX.Checked = sold
DetailTXTbox.Text = detail
'etc, etc
End Sub
I used the function mycstr to fix the dbnull to string error but it does not seem as simple to adapt to "date" data type
Function myCStr(ByVal test As Object) As String
If isdbnull(test) Then
Return ("")
Else
Return CStr(test)
End If
End Function
try this when you read the values from the reader with all your dates, this will first test to see if the date is dbnull, if it is then it will assign a nothing value and you should get your desired empty cell, otherwise it will show the date:
ucistart = IIf(reader3("UCIStartDate") Is DBNull.Value, Nothing, reader3("UCIStartDate"))
Have you tried using the Convert.IsDBNull function?
Here is the official documentation.
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.
I have code that accepts binary data via POST and reads in an array of bytes. For files larger than 200 Kb, the operation fails. I've checked with my sysadmin (we're running IIS 7) to see if there was a limit in our configuration and he says there is none, and suspects it is a problem with the code. Does anybody here see any potential problems? Here is my code:
Public Sub Initialize
If Request.TotalBytes > 0 Then
Dim binData
binData = Request.BinaryRead(Request.TotalBytes) ' This line fails'
getData binData
End If
End Sub
Private Sub getData(rawData)
Dim separator
separator = MidB(rawData, 1, InstrB(1, rawData, ChrB(13)) - 1)
Dim lenSeparator
lenSeparator = LenB(separator)
Dim currentPos
currentPos = 1
Dim inStrByte
inStrByte = 1
Dim value, mValue
Dim tempValue
tempValue = ""
While inStrByte > 0
inStrByte = InStrB(currentPos, rawData, separator)
mValue = inStrByte - currentPos
If mValue > 1 Then
value = MidB(rawData, currentPos, mValue)
Dim begPos, endPos, midValue, nValue
Dim intDict
Set intDict = Server.CreateObject("Scripting.Dictionary")
begPos = 1 + InStrB(1, value, ChrB(34))
endPos = InStrB(begPos + 1, value, ChrB(34))
nValue = endPos
Dim nameN
nameN = MidB(value, begPos, endPos - begPos)
Dim nameValue, isValid
isValid = True
If InStrB(1, value, stringToByte("Content-Type")) > 1 Then
begPos = 1 + InStrB(endPos + 1, value, ChrB(34))
endPos = InStrB(begPos + 1, value, ChrB(34))
If endPos = 0 Then
endPos = begPos + 1
isValid = False
End If
midValue = MidB(value, begPos, endPos - begPos)
intDict.Add "FileName", trim(byteToString(midValue))
begPos = 14 + InStrB(endPos + 1, value, stringToByte("Content-Type:"))
endPos = InStrB(begPos, value, ChrB(13))
midValue = MidB(value, begPos, endPos - begPos)
intDict.Add "ContentType", trim(byteToString(midValue))
begPos = endPos + 4
endPos = LenB(value)
nameValue = MidB(value, begPos, ((endPos - begPos) - 1))
Else
nameValue = trim(byteToString(MidB(value, nValue + 5)))
End If
If isValid = True Then
intDict.Add "Value", nameValue
intDict.Add "Name", nameN
dict.Add byteToString(nameN), intDict
End If
End If
currentPos = lenSeparator + inStrByte
Wend
End Sub
Here is the error that appears in the logs:
Log Name: Application
Source: Active Server Pages
Date: 11/11/2010 2:15:35 PM
Event ID: 5
Task Category: None
Level: Error
Keywords: Classic
User: N/A
Computer: xxxxx.xxxxx.xxx
Description:
Error: File /path-to-file/loader.asp Line 36 Operation not Allowed. .
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
<System>
<Provider Name="Active Server Pages" />
<EventID Qualifiers="49152">5</EventID>
<Level>2</Level>
<Task>0</Task>
<Keywords>0x80000000000000</Keywords>
<TimeCreated SystemTime="2010-11-11T19:15:35.000Z" />
<EventRecordID>19323</EventRecordID>
<Channel>Application</Channel>
<Computer>PHSWEB524.partners.org</Computer>
<Security />
</System>
<EventData>
<Data>File /mghdev/loader.asp Line 36 Operation not Allowed. </Data>
</EventData>
</Event>
By default the limit for the entity size in a POST request is 200K, hence your error.
You can increase that limit open IIS Manager and navigate the tree to your application. Double click the "ASP" icon in the main panel. Expand the "Limits" category. Modify the "Maximum Requesting Entity Body Limit" to a larger value.
If this is for a public web-site be careful as to the limit you set, the purpose of the limit is to prevent malicious POSTs overwhelming the site.
If you read the specifications of the BinaryRead method, you will see that the parameter is actually an out parameter as well. The BinaryRead method is trying to change the value of Request.TotalBytes which it can't do. TotalBytes is read-only.
You can easily fix this by assigning TotalBytes to a variable and passing that in instead. This is what the example code shows in the MSDN documentation.
If the BinaryRead read a different amount of data, the variable will reflect the size of the read.
Two Settings are required in IIS under the "Limit Properties" section
1- Maximum Requesting Entity Body Limit (please not that it is in bytes). You have to set the value according to your maximum file size e-g- 40MB(40000000 bytes).
2)- Script Time-out . Its default value is "00:01:30: which is 90 seconds. Increase it according to the time required by your code to run. I set it to 5 minutes and it solved the problem.