converting code into classic asp - asp-classic

I want to convert the below string into classic asp code can any one help
email has some value but it is not going inside the Loop
Can any one help me.
If (IsEmpty(email) And IsNull(email)) Then
EndIf

The code looks like its VBScript already so there is no "conversion" needed, however the code is faulty. Should be:
If IsEmpty(email) Or IsNull(email) Then
End If
a variable cannot both be empty and contain a Null at the same time hence the orginal conditional expression was always false.

You could always try:
If IsEmpty(email) = True Then
'uninitialized
ElseIf IsNull(email) = True Then
'contains null value
ElseIf email = ""
'contains zero length string
Else
'Response.Write email
'MsgBox email
End If
In most cases I try to code so that the variable is guaranteed to be initialized so you don't need to run the IsEmpty check.
Option Explicit
Dim email
email = ""

Why don't you just check the length of the email variable:
If Len(Trim(email)) > 0 Then
Else
YOUR CODE HERE
End If

Related

Controlling Empty Arrays in Classic ASP

OK I'm a complete newbie to ASP.
I have a client with different content loading depending on what is passed in an array.
select case lcase(arURL(4))
Sometimes though, arURL(4) might be empty, in them cases I'm getting the following error:
Error running function functionName(), the error was:
Subscript out of range
Does anybody know a way to fix this?
Thanks
OK further code as requested. It is horrible code and I don't mean to cause anybody a headache, so please excuse it. Thanks again ........
function GetContent()
dim strURL, arURL, strRetval
select case lcase(request.ServerVariables("URL"))
case "/content.asp"
strURL = ""
arURL = split(request.querystring("url"), "/")
if request("page") = "" then
select case lcase(arURL(2))
case "searches"
select case lcase(arURL(1))
case "looking"
select case lcase(arURL(3))
case "ohai"
strRetval = "Lorem"
case "blahblah"
strRetval = "Lorem Ipsum"
case "edinburgh"
select case lcase(arURL(4))
case "ohai"
strRetval = "Ipsum"
case "ohno"
strRetval = "Lorem"
end select
case "bristol"
select case lcase(arURL(4))
case "some_blahblah"
strRetval = "LOREM"
case "overthere"
strRetval = "LOREM"
case "blahblah"
strRetval = "LOREM"
end select
case "cambridge"
select case lcase(arURL(4))
case "some_rubbish"
strRetval = "Lorem"
end select
case else
strRetval = " "
end select
case else
strRetval = " "
end select
case else
strRetval = " "
end select
end if
end select
strRetval = strRetval & "<style>h2{border: 0px);</style>"
GetContent = strRetval
end function
You are using value passed over the querystring and split it by "/" character - when the value does not contain "enough" slashes, you will get error and the code will crash.
For example, if the querystring parameter url will be only "/something" then even arURL(2) will fail since the array has only two items. (First one is empty string, second is "something")
To avoid all this mess, best way I can advice is writing custom function that will take array and index as its arguments and return either the item in the given index if exists otherwise empty string:
Function GetItemSafe(myArray, desiredIndex, defValue)
If (desiredIndex < LBound(myArray)) Or (desiredIndex > UBound(myArray)) Then
If IsObject(defValue) Then
Set GetItemSafe = defValue
Else
GetItemSafe = defValue
End If
Else
If IsObject(myArray(desiredIndex)) Then
Set GetItemSafe = myArray(desiredIndex)
Else
GetItemSafe = myArray(desiredIndex)
End If
End If
End Function
(ended up with more generic version, letting the calling code decide what is the default value in case index is out of array range)
Having this, change your code to use the function instead of accessing the array directly.
This line for example:
select case lcase(arURL(2))
Should become this instead:
select case lcase(GetItemSafe(arURL, 2, ""))
Change the rest of those lines accordingly and you'll no longer get errors when the given value won't be valid.
What that error is saying at the most basic level is that you're trying to get information from an array element that doesn't exist, eg arURL may have been declared for 3 elements, but accessing the 4th generates the "subscript out of range" error.
If you're keying on the last element in the array, you might look at the UBound() function, which returns the high index element in an array, eg:
select case lcase(arURL(ubound(arURL))
However, there might be something else going on in the code that would change how you determine which element should be used as the target of the "select case," hence the suggestion to post more of the code.

Dealing with Nulls from a DataReader

I have done this in the past, but I cant remember the correct way to deal with DBNULLS.
This is vb.net
The error im getting is Conversion from type 'DBNull' to type 'Integer' is not valid.
Here is the code.
Dim reader As MySqlDataReader = command.ExecuteReader
Do While reader.Read
Dim item As New clsProvider(reader.Item("MasterAccountID"), reader.Item("CompanyName"), reader.Item("Address"), reader.Item("Postcode"), reader.Item("Telephone"), reader.Item("Fax"), reader.Item("Number_of_Companies"), reader.Item("Total_Number_of_employees"), reader.Item("MainContactName"), reader.Item("MainContactPhone"), reader.Item("MainContactEmail"), reader.Item("Fee"), Convert.ToString(reader.Item("Notes")))
list.Add(item)
Loop
reader.Close()
The issue i have is that some of the items may be empty in the DB. I'm sure in the past I have done something like
convert.ToString(reader.item("Something")
But for the life of me i cant remember.
If the column is nullable, then you should check for null:
If (reader.IsDBNull(ordinal))
See IsDBNull
Perhaps
reader.item("Something").ToString()
is what you've done before?
This isn't necessarily correct but it does deal with null strings quite effectively.
Perhaps:
IFF(reader.item("Something") != DBNull.Value, reader.item("Something"), "")
You have to first check if the column value is null (check the incoming value for DBNull). Once you know that you can decide what to do next - assign null or some other default value to your variable.
I am not sure if my VB.Net is still upto the mark but something like this should help:
Dim item As New clsProvider
item.AccountId = TryCast(reader.Item("MasterAccountID"), String)
item.SomeInt= If(TryCast(reader.Item("SomeInt"), System.Nullable(Of Integer)), 0)
Use TryCast to check if cast is possible.

Detecting null/empty input from user

How can I check if the user has input a null or empty string in classic-asp? Right now I am have this code.
If Request.Form("productId") == "" Then
'my code here
End If
But its not working.
Classic ASP/VBScript uses one = to check for equality, not two. Another thing you may want to try is
If Request.Form("productid") = "" Then
Code here
End If
It is a mess. Here's what I have found ...
(1) To look for existence in the QS, use if IsEmpty(x)=false (ie, URL?x)
(2) To look for a value in the QS, look for if x <> "" (ie, URL?x=anything)
Good luck!
If IsEmpty(Request.Form("inputPhoneNo")) = False Then
response.Write"<script language=javaScript>alert('Blank Phone Number');</script>"
response.Write"<script language=javascript>history.back()</script>"
Else
End If

Problem with email validation: Invalid procedure call or argument: 'Mid'

I tried to control email address and reviewer's name with the following code but I received this error.
Microsoft VBScript runtime error '800a0005'
Invalid procedure call or argument: 'Mid'
Cant I compare Mid(REVIEWEREMAIL, InStr(1, REVIEWEREMAIL, "#", 1), 1) to "#"?
If Len(REVIEWERNAME) < 2 Then
with response
.write "Error! Please fill in valid name. <br />"
end with
ElseIf Len(REVIEWEREMAIL) < 3 Then
with response
.write "Error! Please fill in valid email address. <br />"
end with
ElseIf Mid(REVIEWEREMAIL, InStr(1, REVIEWEREMAIL, "#", 1), 1) <> "#" Then
with response
.write "Error! Please fill in valid email address. <br />"
end with
Else
insert...
End If
You can simplify that last ElseIf like this:
ElseIf InStr(REVIEWEREMAIL, "#", vbTextCompare) = 0 Then
Because as written, you're solely checking if there is a # in the email address provided.
If you're concerned about further validating the email addresses you get, there is a great deal written about using regular expressions to validate email addresses. One example: http://www.codetoad.com/asp_email_reg_exp.asp
The likely reason is that REVIEWEREMAIL is null -- in which case your first IF condition isn't going to catch it as intended. Len() of a null doesn't return an integer 0.
The "classic" ASP cheat for that is to change your null variable to an empty string with something like
REVIEWEREMAIL = REVIEWEREMAIL & ""
which will give back LEN = 0
Beyond that, you may want to look for a regular expression online that will check for valid email values.

Best Regular Expression for Email Format Validation with ASP.NET 3.5 Validation

I've used both of the following Regular Expressions for testing for a valid email expression with ASP.NET validation controls. I was wondering which is the better expression from a performance standpoint, or if someone has better one.
- \w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*
- ^([0-9a-zA-Z]([-\.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$
I'm trying avoid the "exponentially slow expression" problem described on the BCL Team Blog.
UPDATE
Based on feedback I ended up creating a function to test if an email is valid:
Public Function IsValidEmail(ByVal emailString As String, Optional ByVal isRequired As Boolean = False) As Boolean
Dim emailSplit As String()
Dim isValid As Boolean = True
Dim localPart As String = String.Empty
Dim domainPart As String = String.Empty
Dim domainSplit As String()
Dim tld As String
If emailString.Length >= 80 Then
isValid = False
ElseIf emailString.Length > 0 And emailString.Length < 6 Then
'Email is too short
isValid = False
ElseIf emailString.Length > 0 Then
'Email is optional, only test value if provided
emailSplit = emailString.Split(CChar("#"))
If emailSplit.Count <> 2 Then
'Only 1 # should exist
isValid = False
Else
localPart = emailSplit(0)
domainPart = emailSplit(1)
End If
If isValid = False OrElse domainPart.Contains(".") = False Then
'Needs at least 1 period after #
isValid = False
Else
'Test Local-Part Length and Characters
If localPart.Length > 64 OrElse ValidateString(localPart, ValidateTests.EmailLocalPartSafeChars) = False OrElse _
localPart.StartsWith(".") OrElse localPart.EndsWith(".") OrElse localPart.Contains("..") Then
isValid = False
End If
'Validate Domain Name Portion of email address
If isValid = False OrElse _
ValidateString(domainPart, ValidateTests.HostNameChars) = False OrElse _
domainPart.StartsWith("-") OrElse domainPart.StartsWith(".") OrElse domainPart.Contains("..") Then
isValid = False
Else
domainSplit = domainPart.Split(CChar("."))
tld = domainSplit(UBound(domainSplit))
' Top Level Domains must be at least two characters
If tld.Length < 2 Then
isValid = False
End If
End If
End If
Else
'If no value is passed review if required
If isRequired = True Then
isValid = False
Else
isValid = True
End If
End If
Return isValid
End Function
Notes:
IsValidEmail is more restrictive about characters allowed then the RFC, but it doesn't test for all possible invalid uses of those characters
If you're wondering why this question is generating so little activity, it's because there are so many other issues that should be dealt with before you start thinking about performance. Foremost among those is whether you should be using regexes to validate email addresses at all--and the consensus is that you should not. It's much trickier than most people expect, and probably pointless anyway.
Another problem is that your two regexes vary hugely in the kinds of strings they can match. For example, the second one is anchored at both ends, but the first isn't; it would match ">>>>foo#bar.com<<<<" because there's something that looks like an email address embedded in it. Maybe the framework forces the regex to match the whole string, but if that's the case, why is the second one anchored?
Another difference is that the first regex uses \w throughout, while the second uses [0-9a-zA-Z] in many places. In most regex flavors, \w matches the underscore in addition to letters and digits, but in some (including .NET) it also matches letters and digits from every writing system known to Unicode.
There are many other differences, but that's academic; neither of those regexes is very good. See here for a good discussion of the topic, and a much better regex.
Getting back to the original question, I don't see a performance problem with either of those regexes. Aside from the nested-quantifiers anti-pattern cited in that BCL blog entry, you should also watch out for situations where two or more adjacent parts of the regex can match the same set of characters--for example,
([A-Za-z]+|\w+)#
There's nothing like that in either of the regexes you posted. Parts that are controlled by quantifiers are always broken up by other parts that aren't quantified. Both regexes will experience some avoidable backtracking, but there are many better reasons than performance to reject them.
EDIT: So the second regex is subject to catastrophic backtracking; I should have tested it thoroughly before shooting my mouth off. Taking a closer look at that regex, I don't see why you need the outer asterisk in the first part:
[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*
All that bit does is make sure the first and last characters are alphanumeric while allowing some additional characters in between. This version does the same thing, but it fails much more quickly when no match is possible:
[0-9a-zA-Z][-.\w]*[0-9a-zA-Z]
That would probably suffice to eliminate the backtracking problem, but you could also make the part after the "#" more efficient by using an atomic group:
(?>(?:[0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+)[a-zA-Z]{2,9}
In other words, if you've matched all you can of substrings that look like domain components with trailing dots, and the next part doesn't look like a TLD, don't bother backtracking. The first character you would have to give up is the final dot, and you know [a-zA-Z]{2,9} won't match that.
We use this RegEx which has been tested in-house against 1.5 million addresses. It correctly identifies better than 98% of ours, but there are some formats that I'm aware of that it would error on.
^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$
We also make sure that there are no EOL characters in the data since an EOL can fake out this RegEx. Our Function:
Public Function IsValidEmail(ByVal strEmail As String) As Boolean
' Check An eMail Address To Ensure That It Is Valid
Const cValidEmail = "^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$" ' 98% Of All Valid eMail Addresses
IsValidEmail = False
' Take Care Of Blanks, Nulls & EOLs
strEmail = Replace(Replace(Trim$(strEmail & " "), vbCr, ""), vbLf, "")
' Blank eMail Is Invalid
If strEmail = "" Then Exit Function
' RegEx Test The eMail Address
Dim regEx As New System.Text.RegularExpressions.Regex(cValidEmail)
IsValidEmail = regEx.IsMatch(strEmail)
End Function
I am a newbie, but I tried the following and it seemed to have limited the ".xxx" to only two occurrences or less, after the symbol '#'.
^([a-zA-Z0-9]+[a-zA-Z0-9._%-]*#(?:[a-zA-Z0-9-])+(\.+[a-zA-Z]{2,4}){1,2})$
Note: I had to substitute single '\' with double '\\' as I am using this reg expr in R.
These don't check for all allowable email addresses according to the email address RFC.
I let MS to do the work for me:
Public Function IsValidEmail(ByVal emailString As String) As Boolean
Dim retval As Boolean = True
Try
Dim address As New System.Net.Mail.MailAddress(emailString)
Catch ex As Exception
retval = False
End Try
Return retval
End Function
For server side validation, I found Phil Haack's solution to be one of the better ones. His attempt was to stick to the RFC:
string pattern = #"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
+ #"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
+ #"#[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
return regex.IsMatch(emailAddress);
Details:
http://blog.degree.no/2013/01/email-validation-finally-a-net-regular-expression-that-works/
Just to contribute, I am using this regex.
^([a-zA-Z0-9]+[a-zA-Z0-9._%-]*#(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,4})$
The thing about it is the specifications are changing with each domain extension that is introduced.
You sit here mod your regex, test, test, test, and more testing. You finally get what you "think" is accurate then the specification changes... You update your regex to account for what the new requirements are..
Then someone enters aa#aa.aa and you've done all that work for what? It walks through your fancy regex.. bummer!
You may as well just check for a single #, and a "." and move on. I assure you, you will not get someones email if they do not want to give it up. You'll get garbage or their hotmail account they never check and couldn't care less about.
I've seen in many cases this goes horribly wrong and a client calls up because their own email address is rejected because of a poorly crafted regex check. Which as mentioned shouldn't have even been attempted.
TextBox :-
<asp:TextBox ID="txtemail" runat="server" CssClass="form-control pantxt" Placeholder="Enter Email Address"></asp:TextBox>
Required Filed validator:
<asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ControlToValidate="txtemail" ErrorMessage="Required"></asp:RequiredFieldValidator>
Regular Expression for email validation :
<asp:RegularExpressionValidator ID="validateemail" runat="server" ControlToValidate="txtemail" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*" ErrorMessage="Invalid Email"></asp:RegularExpressionValidator>
Use this regular expression for email validation in asp.net

Resources