Problems with If Statement (ASP.NET) - asp.net

Dim custEmail As String
Dim inputEmail As String
custEmail = dt.Rows(0).Item("email")
inputEmail = email_add.Text
if (custEmail.toString() == inputEmail.toString() ){
label1.Text = custEmail
}
End If
This code is giving an error: Compiler Error Message: BC30201: Expression expected.
I just basically want to check if two values are equal but its saying something about expression expected although i've given the expression to evaluate.

The above is a mix of vb.net and c# syntax. You can use either in .net with success but not both at the same time. Get rid of the { and } to stick with vb.

Looks like you are mixing C# and VB.Net. Assuming you are using VB.Net
Replace the '{' with Begin IF and remove the '}'.

Related

Exploding a string ASP

I have the following which is returned from an api call:
<WORST>0</WORST>
<AVERAGE>93</AVERAGE>
<START>1</START>
I need to parse this to just give me the <AVERAGE></AVERAGE> number, 93.
Here's what I'm trying but get error detected:
res = AjaxGet(url)
myArray = split(res,"AVERAGE>")
myArray2 = split(myArray[1],"</AVERAGE>")
response.write myArray2[0]
I'm brand new to ASP, normally code in PHP
VBScript doesn't recognise square brackets [] when accessing Array elements and will produce a Syntax Error in the VBScript Engine.
Try making the following changes to the code snippet to fix this problem;
res = AjaxGet(url)
myArray = split(res,"AVERAGE>")
myArray2 = split(myArray(1),"</AVERAGE>")
response.write myArray2(0)
On a side Note:
Parsing XML data in this way is really inefficient if the AjaxGet() function returns an XML response you could use the XML DOM / XPath to locate the Node and access the value.

DateTime.TryParse in a conditional is throwing an exception

On both examples I'm giving it a String like the following: 26-03-17
Dim mvarValor As String
Dim dateVarValor As DateTime
This code snippet is throwing an exception on the TryParse:
If Not mvarValor = Nothing AndAlso DateTime.TryParse(mvarValor, dateVarValor) Then
Return Format(dateVarValor, mvarFormat)
Else
Return strNull
End If
The next code snippet is not throwing an exception, but a False like it should:
DateTime.TryParse(mvarValor, dateVarValor)
If dateVarValor = Nothing Then
Return strNull
Else
Return Format(dateVarValor, mvarFormat)
End If
Why is the first code snippet giving me an exception?
Thanks in advance!
DateTime.TryParse throws three types of exceptions
http://msdn.microsoft.com/en-us/library/9h21f14e(v=vs.100).aspx
you must be getting one of those. Here is the proper usage of DateTime.TryParse
var culture = CultureInfo.CreateSpecificCulture("en-US");
string parsedDateTime = null;
if (DateTime.TryParse(parseMe, culture, DateTimeStyles.None, out dateResult))
{
parsedDateTime = dateResult;
}
this snippet will parse the datetime without throwing an exception.
I hope this helps :)
You need to pass in a Y2K compliant date. The parser can't tell the year from 2 digits. If you pass 2003-12-25 it will validate that the date does in fact exist, but 03-12-25 is ambiguous.

Replace part of string

I'm having difficulty with the following.
In VB.Net, I have the following line:
Dim intWidgetID As Integer = CType(Replace(strWidget, "portlet_", ""), Integer)
where strWidget = portlet_n
where n can be any whole number, i.e.
portlet_5
I am trying to convert this code to C#, but I keep getting errors, I currently have this:
intTabID = Convert.ToInt32(Strings.Replace(strTabID, "tab_group_", ""));
which I got using an online converter
But it doesn't like Strings
So my question is, how to I replace part of a string, so intTabID becomes 5 based on this example?
I've done a search for this, and found this link:
C# Replace part of a string
Can this not be done without regular expressions in c#, so basically, I'm trying to produce code as similar as possible to the original vb.net example code.
It should be like this strTabID.Replace("tab_group_", string.Empty);
int intTabID = 0;
string value = strTabID.Replace("tab_group_", string.Empty);
int.TryParse(value, out intTabID);
if (intTabID > 0)
{
}
And in your code i think you need to replace "tab_group_" with "portlet_"
Instead of Strings.Replace(strTabID, "tab_group_", ""), use strTabID.Replace("tab_group_", "").
This should work
int intWidgetID = int.Parse(strTabID.Replace("tab_group_",""));//Can also use TryParse
Their is no Strings class in Vb.Net so please use the string class instead http://msdn.microsoft.com/en-us/library/aa903372(v=vs.71).aspx
you can achieve it by this way
string strWidget = "portlet_n";
int intWidgetID = Convert.ToInt32(strWidget.Split('_')[1]);

ASP Classic - Type mismatch: 'CInt' - Easy question

Having an issue with type conversion in ASP classic.
heres my code:
Set trainingCost = Server.CreateObject("ADODB.Recordset")
strSQL3 = "SELECT cost1 FROM tblMain WHERE (Booked = 'Booked') AND (Paid IS NULL) AND (PaidDate BETWEEN '01/04/" & startyear & "' AND '31/03/" & endyear & "')"
trainingCost.Open strSQL3, Connection
trainingCost.movefirst
totalTrainCost = 0
do while not trainingCost.eof
trainCost = trainingCost("cost1")
If NOT isNull(trainCost) then
trainCostStr = CStr(trainCost)
trainCostStr = Replace(trainCostStr, "£", "")
trainCostStr = Replace(trainCostStr, ",", "")
totalTrainCost = totalTrainCost + CInt(trainCostStr)
end if
trainingCost.movenext
loop
trainingCost.close
when I run this I get the following error:
Microsoft VBScript runtime (0x800A000D)
Type mismatch: 'CInt'
/systems/RFT/v1.2/Extract.asp, line 43
which is "totalTrainCost = totalTrainCost + CInt(trainCostStr)"
Im guessing that the problem is to do with the String value being uncastable to Int in which case is there any way to catch this error? I havent worked with asp classic much so any help would be usefull
cheers
-EDIT-
the type of column cost1 is String as it may contain a number or a sequence of chars eg £10.00 or TBC
You have a couple of choices. You can be proactive by checking ahead of time whether the value is numeric using the IsNumeric function:
If IsNumeric(trainCostStr) Then
totalTrainCost = totalTrainCost + CInt(trainCostStr)
Else
' Do something appropriate
End If
...or you can be reactive by using error catching; in Classic ASP probably easiest to define a function and use On Error Resume Next:
Function ConvertToInt(val)
On Error Resume Next
ConvertToInt = CInt(val)
If Err.Number <> 0 Then
ConvertToInt = Empty
Err.Clear
End If
End Function
Or return 0 or Null or whatever suits you, then use it in your trainCost code.
Note that CInt expects an integer and will stop at the first non-digit, so "123.45" comes back as 123. Look at the other conversions, CDouble, CCur, etc.
Rather than casting to a string, why not use CCur (Cast as Currency) so that your commas and any currency symbols (I think) are effectively ignored while doing arithmetic operations?
Potentially solving the wrong problem, depends on the type of Cost1 within the database but the code is looping through the records to generate a total.
strSQL3 = "SELECT sum(cost1) FROM tblMain WHERE (Booked = 'Booked') AND (Paid IS NULL) AND (PaidDate BETWEEN '01/04/" & startyear & "' AND '31/03/" & endyear & "')"
trainingCost.Open strSQL3, Connection
etc and just read off the value as a total.
I don't see why the RS is being looped to generate a sum when the database can do that work for you. All the conversion work it has generated just looks artifical.
Heh heh. Classic ASP. You have my pity :) Anyway,
On error resume next
And then on the next line, check that it worked.
Though maybe you want CDouble. Is that a function? I can't remember.

How do you call a method from a variable in ASP Classic?

For example, how can I run me.test below?
myvar = 'test'
me.myvar
ASP looks for the method "myvar" and doesn't find it. In PHP I could simply say $me->$myvar but ASP's syntax doesn't distinguish between variables and methods. Suggestions?
Closely related to this, is there a method_exists function in ASP Classic?
Thanks in advance!
EDIT: I'm writing a validation class and would like to call a list of methods via a pipe delimited string.
So for example, to validate a name field, I'd call:
validate("required|min_length(3)|max_length(100)|alphanumeric")
I like the idea of having a single line that shows all the ways a given field is being validated. And each pipe delimited section of the string is the name of a method.
If you have suggestions for a better setup, I'm all ears!
You can achieve this in VBScript by using the GetRef function:-
Function Test(val)
Test = val & " has been tested"
End Function
Dim myvar : myvar = "Test"
Dim x : Set x = GetRef(myvar)
Response.Write x("Thing")
Will send "Thing has been tested" to the client.
So here is your validate requirement using GetRef:-
validate("Hello World", "min_length(3)|max_length(10)|alphanumeric")
Function required(val)
required = val <> Empty
End Function
Function min_length(val, params)
min_length = Len(val) >= CInt(params(0))
End Function
Function max_length(val, params)
max_length = Len(val) <= CInt(params(0))
End Function
Function alphanumeric(val)
Dim rgx : Set rgx = New RegExp
rgx.Pattern = "^[A-Za-z0-9]+$"
alphanumeric = rgx.Test(val)
End Function
Function validate(val, criterion)
Dim arrCriterion : arrCriterion = Split(criterion, "|")
Dim criteria
validate = True
For Each criteria in arrCriterion
Dim paramListPos : paramListPos = InStr(criteria, "(")
If paramListPos = 0 Then
validate = GetRef(criteria)(val)
Else
Dim paramList
paramList = Split(Mid(criteria, paramListPos + 1, Len(criteria) - paramListPos - 1), ",")
criteria = Left(criteria, paramListPos - 1)
validate = GetRef(criteria)(val, paramList)
End If
If Not validate Then Exit For
Next
End Function
Having provided this I have to say though that if you are familiar with PHP then JScript would be a better choice on the server. In Javascript you can call a method like this:-
function test(val) { return val + " has been tested"; )
var myvar = "test"
Response.Write(this[myvar]("Thing"))
If you are talking about VBScript, it doesn't have that kind of functionality. (at least not to my knowledge) I might attempt it like this :
Select myvar
case "test":
test
case "anotherSub":
anotherSub
else
defaultSub
end select
It's been a while since I wrote VBScript (thank god), so I'm not sure how good my syntax is.
EDIT-Another strategy
Personally, I would do the above, for security reasons. But if you absolutely do not like it, then you may want to try using different languages on your page. I have in the past used both Javascript AND VBScript on my Classic ASP pages (both server side), and was able to call functions declared in the other language from my current language. This came in especially handy when I wanted to do something with Regular Expressions, but was in VBScript.
You can try something like
<script language="vbscript" runat="server">
MyJavascriptEval myvar
</script>
<script language="javascript" runat="server">
function MyJavascriptEval( myExpression)
{
eval(myExpression);
}
/* OR
function MyJavascriptEval( myExpression)
{
var f = new Function(myExpression);
f();
}
*/
</script>
I didn't test this in a classic ASP page, but I think it's close enough that it will work with minor tweaks.
Use the "Execute" statement in ASP/VBScript.
Execute "Response.Write ""hello world"""
PHP's ability to dynamically call or create functions are hacks that lead to poor programming practices. You need to explain what you're trying to accomplish (not how) and learn the correct way to code.
Just because you can do something, doesn't make it right or a good idea.
ASP does not support late binding in this manner. What are you trying to do, in a larger sense? Explain that, and someone can show you how to accomplish it in asp.
Additionally, you might consider "objectifying" the validation functionality. Making classes is possible (though not widely used) in VB Script.
<%
Class User
' declare private class variable
Private m_userName
' declare the property
Public Property Get UserName
UserName = m_userName
End Property
Public Property Let UserName (strUserName)
m_userName = strUserName
End Property
' declare and define the method
Sub DisplayUserName
Response.Write UserName
End Sub
End Class
%>

Resources