Error declaring a variable in ASP - asp-classic

I'm declaring a string variable this way in classic ASP:
Dim i As String
And getting this error:
Microsoft VBScript compilation error '800a0401'
Expected end of statement
/retencion/Estadisticas/Detail.asp, line 10, column 6
Dim i As String
-----^
Why is that?

Classic ASP is written in VBScript and isn't Visual Basic itself, so you can't declare things as strings. Loosely typed I think is the phrase to describe it. Basically, you have to leave out the "as" and anything after it.
Try:
<%
Dim i
'you can now use the variable as you want.
i = "whatever"
%>

It's actually VBScript. You have to do this:
dim i
i = "some string"

I believe in classic ASP you can't give an explicit type to your variables. They all have to be variants and they have to be declared with no As clause, e.g. "dim i". Here's the MSDN help on variants in VBScript.

you do not need 'as'.
this should work.
<%
Dim myString
myString = "Hello There!"
%>

This has been sufficiently answered I think, but I'll only chime in a bit to say that technically you may not need to explicitly declare the variable at all. If you're using the option explicit, yes you do need to declare it, a la
<%
option explicit
dim str: str = "Hello World"
%>
Otherwise, you can implicitly declare it on first use, php-style.
<%
str = "I don't need no stinkin dim statements!"
%>
I should add that using option explicit is a safer way to go, even if it does require more typing.

Related

How to tell whether a variable in ASP has been declared

Let me start off by saying I'm a PHP developer, not an ASP one. (And I really wish ASP had isset().) And I'm working in a live environment so I don't really have an opportunity to do any testing.
All the resources I've found suggest different ways to test for the existence of a variable.
Here's what I'm trying to do:
On SOME pages, I set a variable which holds a value for a robots <meta> tag:
dim dsep_robots
dsep_robots = "nofollow,noindex"
All pages include header.asp. In my header file, I want to test whether dsep_robots has a value and if so, output that value, otherwise, output nothing.
I think that testing whether dsep_robots has a value might look like this:
if not dsep_robots = "" then
'...
end if
Best practices in PHP state that when you're using a variable that may or may not exist, you should always test if (isset($var)) {...} (not doing so will trigger a Notice if the variable doesn't exist).
Is there such a thing in ASP -- i.e. do I really need to test if it exists, or can I simply test if it has a value?
ust by the way, your question isn't about classic ASP, it is a VBScript question. VBScript can occur in scripts outside of ASP. And compilation isn't done in VBScript, because it is an interpreted language. Nevermind.
I think there's some confusion here -- and your question seems to have more to do with uninitialized variables than undeclared variables. For undeclared variables, see below.
For uninitialized, try the function IsEmpty.
For checking for null, try the function IsNull.
dim x
x = 1
dim t
Response.write isempty(x)
Response.write "<br>"
Response.write isempty(t)
Will display:
False
True
Detecting Undeclared Variables
If you include Option Explicit in your header, use of a non-declared variable will cause an runtime error. If your script is not Option Explicit it will not generate an error, and there is no function that will tell you if the variable has been declared or not. This sounds sloppy, and it is, but it was intentional.
The only way you can escape this is to actually set Option Explicit and then trap the error that you will get when you try to use the undeclared variable. If you trap this particular error you will find that it has Err.Number = 500. So, the following will do what you want:
Option Explicit
dim x
On Error Resume Next
Response.Write dsep_robots
If Err.Number > 0 Then
Response.Write Err.Number
end if
Of course, if you set Option Explicit and your code is rife with undeclared variables then you'll get errors being thrown all over the place, so you'd need to set On Error Resume Next at the top of your code so you can successfully ignore it, and only trap it when you want to.
By the way, here's Microsoft's online reference for VBScript:
http://msdn.microsoft.com/en-us/library/d1wf56tt(v=VS.85).aspx
#Jazzerus: I'd recommend putting the code within header.asp into a Sub, something like
Sub outputHeader(ByRef MyTitle, Byref dsep_robots)
'contents of header.asp
End Sub
...and then in your calling pages include header.asp right at the top and use
outputHeader "Title for this page", "value you want dsep_robots to have for page"
If you don't set dsep_robots on that page, then just leave the second parameter blank ("")
Then just checking if the variable is empty or not within the Sub should suffice:
If dsep_robots <> "" Then
Response.Write dsep_robots
End If
What about:
If NOT IsEmpty(myvariable) Then...
that seems to have been working for me.
I use the VarType function to detect if the variable is defined. If the tested variable is not defined, VarType returns the value vbError (10). Interesting to note that the optional parameter cannot be the last parameter else ASP tosses an error.
function Sample(p1,p2,p3,p4)
if VarType(p3) <> vbError then
'do something with p3
end if
end function
ThisWorks=Sample(1,2,,3)
ThisFails=Sample(1,2,3,)

what is diffrence between Response.write and Response.output.write

what is difference between Response.write and Response.output.write please give me example
Response.Output.Write allows you to format the string before outputting, Response.Write simply writes it out as is.
Response.Write will output exactly what you pass in.
Response.Output exposes the underlying TextWriter, so Response.Output.Write has many more overloads, some with String.Format functionality.
There is no difference. Response.Write is a convenience accessor to Response.Output.Write.
You could have found out this by yourself if you installed reflector and looked up the class HttpResponse (in the assembly System.Web).

asp errors not displayed

I have moved an sql database from one server to a new one (detached/attached)
Now i experience some strange behavior as it does not work but NO error is displayed.
This is the code
<%
const database_dsn="PROVIDER=SQLNCLI10; SERVER=FR-2626\SQLLOP;DATABASE=Lop;Uid=admin-sql;Pwd=xxxx;"
response.write "Step 0//"
set conn=server.CreateObject("ADODB.Connection")
set RS=server.CreateObject("ADODB.Recordset")
conn.Open database_dsn
response.write "Step 1//"
req = "Select count(*) From tblArticleList"
response.write "Step 2//"
set RS = conn.Execute(req)
response.write "Step 3//"
%>
The program stops at Step 2; then nothing, no error is displayed...
I just don t know what to do..How can i get some error?
Thanks
Jonathan
Oh i partially found the answer for the error display.
In the Debug pane of the IIS directory configuration, Enable ASP debugging should NOT be checked...althought i thougth it should...
have you got your browser set to "show friendly http errors" this in conjuction with what you have already identified is the common causes I've had for not seeing an error message.
Shahkaplesh is also right that you can use Server.GetLastError() to get the last error that occurred but you shouldn't need to do this in this example.
When executing a query you don't use the "Set" command. I don't know why its not showing you anything, but your code should look more like this:
<%
const database_dsn="PROVIDER=SQLNCLI10; SERVER=FR-2626\SQLLOP;DATABASE=Lop;Uid=admin-sql;Pwd=xxxx;"
response.write("Step 0//")
set conn=server.CreateObject("ADODB.Connection")
set RS=server.CreateObject("ADODB.Recordset")
conn.Open database_dsn
response.write("Step 1//")
req = "Select count(*) From tblArticleList"
response.write("Step 2//")
RS = conn.Execute(req)
response.write("Step 3//")
%>
Yes, the parentheses on the "Response.Write" are optional. But I'm OCD like that and it makes troubleshooting a little easier.
You need to place error checking code to find out what the actual error might be.
I would suggest that you change you code like so:
<%
const database_dsn="PROVIDER=SQLNCLI10; SERVER=FR-2626\SQLLOP;DATABASE=Lop;Uid=admin- sql;Pwd=xxxx;"
'Its very important to add this line!!! '
On Error Resume Next
'Its very important to add this line!!! '
response.write "Step 0//"
set conn=server.CreateObject("ADODB.Connection")
set RS=server.CreateObject("ADODB.Recordset")
conn.Open database_dsn
if err.number<>0 then
response.write err.description
end if
response.write "Step 1//"
req = "Select count(*) From tblArticleList"
response.write "Step 2//"
set RS = conn.Execute(req)
if err.number<>0 then
response.write err.description
end if
response.write "Step 3//"
%>
And not to kick a dead horse but I'm doing something similar against an Oracle database and I've had two phantom problems I have yet to identify root cause but here's two things that made them go away.
1. Name all columns in a Query and Alias any that are calculated (sum, count, avg, etc.) So your query would become
req = "Select count(*) NumRows From tblArticleList"
2. Wrapping my query string in a call to cstr caused the result.EOF flag to be populated correctly rather than be returned with an empty or null value causing a simple DO WHILE NOT result.EOF Some Action LOOP to create an infinite loop until the web request timed out. So e.g.
response.write "Step 2//"
set RS = conn.Execute(cstr(req))
Nothing major just a couple tips if you get stuck and can't find out why. Follow the debugging advice above though, that's good info.
I think Server has a GetLastError method, which you can check to find out what error occurred while running any statement.
e.g. On error resume next
.... statement that could cause an error....
errorObject = Server.GetLastError()
For ASPError object, refer http://www.w3schools.com/asp/asp_ref_error.asp
Actually don't mean to be disagreeable, but yes you do need a Set there, as you are setting an object type and presumably wanting to use the return value at some point (if this wasn't just a test script which it looks like to me).
Also btw parentheses are not really correct there in Response.Write() as it does not return a value. They only happen to work on single parameter subs because you can put parentheses anywhere you like around expressions.
eg:
a = (b)
Response.Write ((("test"))&(1))

Outputting a GUID in VBScript ignores all text after it

I'm creating a GUID for use in a Classic ASP application, by using TypeLib. However, even a simple test such as writing the GUID out to the screen is giving me problems - it prints the GUID but ignores everything after it (e.g. HTML tags, additional words, anything).
Here's the rudimentary code to test this:
Set typeLib = Server.CreateObject("Scriptlet.TypeLib")
myGuid = typeLib.Guid
Response.Write myGuid & " is the new GUID"
Set typeLib = Nothing
This will display something like {9DDB27D1-F034-41D7-BB88-D0D811DB91CE} and that's it; the rest of the text is ignored and isn't written out. However, if I hard-code that GUID value and reference it from a variable, the rest of the text appears just fine. I've tried explicit conversion to a String value before displaying, but it still happens.
I seem to have solved my own problem.. it was adding something extra to the text, so I had to do:
myGuid = Left(myGuid, Len(myGuid)-2)
and it now outputs fine. Strange.
I use something like this
Function GetGuid()
Set TypeLib = CreateObject("Scriptlet.TypeLib")
GetGuid = Left(CStr(TypeLib.Guid), 38)
Set TypeLib = Nothing
End Function
It adds a vbNullChar or Chr(0) at the end of the GUID. Replace(myGuid, Chr(0), "") will fix it. Better than using Left or Mid functions.
GUID is a struct and not a string, you need to add a ToString() method to output it as a string.
https://msdn.microsoft.com/fr-fr/library/97af8hh4(v=vs.110).aspx
Response.Write myGuid.ToString("D")

check string for nothing and then for certain value in 1 line?

I always seem to see if a string (querystring value usually) has a value but first I have to check that it is not nothing first so I end up with 2 if then statements - am I missing somethign here - there has to be a better way to do this:
If Not String.IsNullOrEmpty(myString) Then
If CBool(myString) Then
//code
End If
End If
In VB.Net, And does not short-circuit, but AndAlso does.
(same for Or and OrElse)
So your code should look something like
If Not String.IsNullOrEmpty(myString) AndAlso CBool(myString) Then
....
End If
The boolean "and" operator in your language of choice? Conditionals generally short-circuit so if the first one fails, the second won't run/error.
AndAlso (as mentioned) is the most general purpose answer. But, you could also use the various TryParse methods, which will make code like this:
Dim b as Boolean
If Boolean.TryParse(myString, b) AndAlso b Then
End If
Bonus, it'll save you from the FormatException when someone sends in "blah" in your querystring.
FYI this type of code fits perfect as an "extension method". In short this means that you can extend string with a method providing your own code.
Look it up :)
Use the following if using .NET 2.0 or greater:
String.IsNullOrEmpty(thestringobject)
Will evaluate to True or False depending.
I usually create another function in a Utility Class that does this check and also checks the trim/length so I know if the string object is null, empty, or a bunch of blanks.

Resources