If condition for VBScript on LDAP results - vbscript

I'm connecting with LDAP to Active Directory for a corporate phonebook. I'm grabbing the data I want, but I need to do an If...Else statement on some of the data I'm grabbing.
I want to check if the value in AD attribute 'homePhone' begins with "01". If it does, I want to write out its value. If it begins with anything else, I want to either write "" or "Not Valid".
Here's what I've been writing, but isn't working:
Response.Write "<td>"
if objRS("homePhone") = "01*" then
Response.Write objRS("homePhone")
else
Response.Write ""
end if
Response.Write "</td>"
This seems to just go to the Else condition, and the homePhone attribute doesn't get written.

You can't use wildcards in string comparisons and, unfortunately, VBScript doesn't support the Like operator used in VBA/VB. You can use a regular expression but that's overkill for what you need here. Just strip the first two characters and perform your comparison.
If Left(objRS("homePhone"), 2) = "01" Then
If you need to perform case-insensitive string comparisons (not necessary in this situation, but may be helpful in the future), you can convert both strings to upper/lowercase before comparing or use the StrComp() function with the vbTextCompare parameter value.
If StrComp(Left(objRS("homePhone"), 2), "01", vbTextCompare) = 0 Then

Related

Calculator with function Add concatenates result instead of addition [duplicate]

On every site that talks about VBScript, the '&' operator is listed as the string concatenation operator. However, in some code that I have recently inherited, I see the '+' operator being used and I am not seeing any errors as a result of this. Is this an accepted alternative?
The & operator does string concatenation, that is, forces operands to be converted to strings (like calling CStr on them first). +, in its turn, forces addition if one of the expressions is numeric. For example:
1 & 2
gives you 12, whereas
1 + 2
"1" + 2
1 + "2"
give you 3.
So, it is recommended to use & for string concatenation since it eliminates ambiguity.
The + operator is overloaded, whereas the & operator is not. The & operator only does string concatenation. In some circles the & operator is used as a best practice because it is unambiguous, and therefore cannot have any unintended effects as a result of the overloading.
+ operator might backfire when strings can be interpreted as numbers. If you don't want nasty surprises use & to concatenate strings.
In some cases the + will throw an exception; for example the following:
Sub SimpleObject_FloatPropertyChanging(fvalue, cancel)
'fvalue is a floating point number
MsgBox "Received Event: " + fvalue
End Sub
You will get an exception when the COM object source fires the event - you must do either of the following:
MsgBox "Received Event: " & fvalue
or
MsgBox "Received Event: " + CStr(fvalue)
It may be best in either case to use CStr(value); but using & per above comments for string concatenation is almost always best practice.

Classic ASP InStr() Evaluates True on Empty Comparison String

I ran into an issue with the Classic ASP VbScript InStr() function. As shown below, the second call to InStr() returns 1 when searching for an empty string in a non empty string. I'm curious why this is happening.
' InStr Test
Dim someText : someText = "So say we all"
Dim emptyString : emptyString = ""
'' I expect this to be true
If inStr(1,someText,"so",1) > 0 Then
Response.write ( "I found ""so""<br />" )
End If
'' I expect this to be false
If inStr(1, someText, emptyString, 1) > 0 Then
Response.Write( "I found an empty string<br />" )
End If
EDIT:
Some additional clarification: The reason for the question came up when debugging legacy code and running into a situation like this:
Function Go(value)
If InStr(1, "Option1|Option2|Option3", value, 1) > 0 Then
' Do some stuff
End If
End Function
In some cases function Go() can get called with an empty string. The original developer's intent was not to check whether value was empty, but rather, whether or not value was equal to one of the piped delimited values (Option1,Option2, etc.).
Thinking about this further it makes sense that every string is created from an empty string, and I can understand why a programming language would assume a string with all characters removed still contains the empty string.
What doesn't make sense to me is why programming languages are implementing this. Consider these 2 statements:
InStr("so say we all", "s") '' evaluates to 1
InStr("so say we all", "") '' evaluates to 1
The InStr() function will return the position of the first occurrence of one string within another. In both of the above cases, the result is 1. However, position 1 always contains the character "s", not an empty string. Furthermore, using another string function like Len() or LenB() on an empty string alone will result in 0, indicating a character length of 0.
It seems that there is some inconsistency here. The empty string contained in all strings is not actually a character, but the InStr() function is treating it as one when other string functions are not. I find this to be un-intuitive and un-necessary.
The Empty String is the Identity Element for Strings:
The identity element I (also denoted E, e, or 1) of a group or related
mathematical structure S is the unique element such that Ia=aI=a for
every element a in S. The symbol "E" derives from the German word for
unity, "Einheit." An identity element is also called a unit element.
If you add 0 to a number n the result is n; if you add/concatenate "" to a string s the result is s:
>> WScript.Echo CStr(1 = 1 + 0)
>> WScript.Echo CStr("a" = "a" & "")
>>
True
True
So every String and SubString contains at least one "":
>> s = "abc"
>> For p = 1 To Len(s)
>> WScript.Echo InStr(p, s, "")
>> Next
>>
1
2
3
and Instr() reports that faithfully. The docs even state:
InStr([start, ]string1, string2[, compare])
...
The InStr function returns the following values:
...
string2 is zero-length start
WRT your
However, position 1 always contains the character "s", not an empty
string.
==>
Position 1 always contains the character "s", and therefore an empty
string too.
I'm puzzled why you think this behavior is incorrect. To the extent that asking Does 'abc' contain ''? even makes sense, the answer has to be "yes": All strings contain the empty string as a trivial case. So the answer to your "why is this happening" question is because it's the only sane thing to do.
It is s correct imho. At least it is what I expect that empty string is part of any other string. But maybe this is a philosophical question. ASP does it so, so live with it. Practically speaking, if you need a different behavior write your own Method, InStrNotEmpty or something, which returns false on empty search string.

VBScript to combine rs values, loop and add to duplicate(s)

I've written a lot of IF statements in VBScript, but haven't gone much beyond that so apologize for my lack of experience. I hope what I'm asking is simple to do.
I want to output item identifiers created by three combined recordset field values and add "B" "C" "D" etc., to any duplicates. Duplicates are rare, but do happen occasionally. I want to do this for meaningful item identification which autonumbers do not provide.
The following example works to combine fields, but then I need to include script to loop and find the duplicates and add the appropriate alpha character.
FYI: a = alpha character, b = alpha character, c = reformatted date
<% Dim idCode
a = (rs_table.Fields.Item("CodeA").Value)
b = (rs_table.Fields.Item("CodeB").Value)
c = (fixedDate(rs_table.Fields.Item("Date").Value))
idCode = (a) & (b) & (c)
Response.write idCode
%>
example output: LC032414
example dupe output: LC032414B
Thanks, I'm almost afraid to ask and may find this more pain than what it's worth!
I would probably use a Dictionary to store the ID's, since you can add each as a key (which must be unique) and test the Dictionary for its existence. Something like this:
' Early on... create a dictionary...
Set d = CreateObject("Scripting.Dictionary")
' Loop through your records...
Do Until rs_table.EOF
' Determine your ID...
idCode = rs_table("CodeA") & rs_table("CodeB") & fixedDate(rs_table("Date"))
' Check for existence in the dictionary...
If d.Exists(idCode) Then
' ID already exists. Keep testing suffixes until we find an availability...
strLetter = "B"
Do While d.Exists(idCode & strLetter)
strLetter = Chr(Asc(strLetter) + 1)
Loop
d.Add idCode & strLetter, "" ' Add the ID/key. The value is unimportant.
Else
' This ID doesn't exist yet. Just add it.
d.Add idCode, "" ' Add the ID/key. The value is unimportant.
End If
rs_table.MoveNext
Loop
When it comes time to print your ID's, you can just iterate the dictionary's Keys collection:
For Each k In d.Keys
Response.Write k
Next

Need to find character within apostrophe substring and replace it, any ideas?

Ok, let me preface this question with the fact that I am extremely new to vb script, but I need to make an addition to a script that another developer created and he is away.
Problem. :
I am getting data that is feed into a process. The script I already have handles some things that I won't go into. One thing I found out that it doesn't handle correctly is commas that occur in double quotes.
So I get some data like this. :
Joe, Bill, James, Alex, "Google, Inc", Rose, "Kickstarter, LLC"
What happens is that when this script kicks to the process application it blows up because of these commas in the double quotes. I need to be able to have this script go in and replace those commas in the Google and Kickstarter blocks with something a little more unique.
If you have the answer to this I would appreciate it, but I wouldn't mind some direction either of something that does something like this, etc.
Any answers are greatly appreciated. Again very new to vbascript just started reading syntax on it today.
You left out a few details about the format of the input data and the replacement text. However, the approach you need to take is to use the regular expression capability of VBScript to identify patterns in your input data, then use the "Replace" method to replace them. Here's a short MS article about regular expressions in VBScript.
Here's an example of what it might look like. This example is definitely NOT bullet proof and it makes some assumptions, but I think it will get you started:
Dim re, strstr, newstrstr
Dim inputstrarray(7)
Set re = new regexp
inputstrarray(0) = "Joe"
inputstrarray(1) = "Bill"
inputstrarray(2) = "James"
inputstrarray(3) = "Alex"
inputstrarray(4) = """" & "Google, Inc" & """"
inputstrarray(5) = "Rose"
inputstrarray(6) = """" & "Kickstarter, LLC" & """"
re.pattern = ",\s" 'pattern is a comma followed by a space
For Each strstr In inputstrarray 'loop through each string in the array
newstrstr = re.Replace(strstr, "_") 'replace the pattern with an underscore
If StrComp(strstr,newstrstr) Then
Wscript.Echo "Replace " & strstr & " with " & newstrstr
Else
Wscript.Echo "No Change"
End If
Next
Output looks like the following:
No Change
No Change
No Change
No Change
Replace "Google, Inc" with "Google_Inc"
No Change
Replace "Kickstarter, LLC" with "Kickstarter_LLC"
No Change

vbscript - Replace all spaces

I have 6400+ records which I am looping through. For each of these: I check that the address is valid by testing it against something similar to what the Post Office uses (find address). I need to double check that the postcode I have pulled back matches.
The only problem is that the postcode may have been inputted in a number of different formats for example:
OP6 6YH
OP66YH
OP6 6YH.
If Replace(strPostcode," ","") = Replace(xmlAddress.selectSingleNode("//postcode").text," ","") Then
I want to remove all spaces from the string. If I do the Replace above, it removes the space for the first example but leave one for the third.
I know that I can remove these using a loop statement, but believe this will make the script run really slow as it will have to loop through 6400+ records to remove the spaces.
Is there another way?
I didn't realise you had to add -1 to remove all spaces
Replace(strPostcode," ","",1,-1)
Personally I've just done a loop like this:
Dim sLast
Do
sLast = strPostcode
strPostcode = Replace(strPostcode, " ", "")
If sLast = strPostcode Then Exit Do
Loop
However you may want to use a regular expression replace instead:
Dim re : Set re = New RegExp
re.Global = True
re.Pattern = " +" ' Match one or more spaces
WScript.Echo re.Replace("OP6 6YH.", "")
WScript.Echo re.Replace("OP6 6YH.", "")
WScript.Echo re.Replace("O P 6 6 Y H.", "")
Set re = Nothing
The output of the latter is:
D:\Development>cscript replace.vbs
OP66YH.
OP66YH.
OP66YH.
D:\Development>
This is the syntax Replace(expression, find, replacewith[, start[, count[, compare]]])
it will default to -1 for count and 1 for start. May be some dll is corrupt changing the defaults of Replace function.
String.Join("", YourString.Split({" "}, StringSplitOptions.RemoveEmptyEntries))
Because you get all strings without spaces and you join them with separator "".

Resources