Classic ASP (VBScript) replace special character in a string is acting strange - string

In classic ASP (VBScript), when I replace the string, a strange character appears.
<%
myString = "My Ttitle ®"
myString = Replace(myString,"®", "®")
Response.Write(myString)
%>
If I print this out to HTML, the final result is (Which has a strange A in it):
My Ttitle ®

add this at the top of your page <%# language="vbscript" codepage="65001"%>
open your file in a text editor, (notepad will do) select Save As from the file menu and choose utf-8 rather than ANSI encoding
add in your head section <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> (this isn't actually necessary but it doesn't do any harm)
Further information here
http://www.hanselman.com/blog/InternationalizationAndClassicASP.aspx

Change
myString = Replace(myString,"®", "®")
to
myString = Replace(myString,"®", "®")

Your website encoding is most likely wrong. Add this before your myString declaration.
response.write('<meta http-equiv="Content-Type" content="text/html;charset=utf-8">')

Related

Using Classic ASP to bring in spreadsheet content including emojis

I need to write a small script to take the contents of an XLS file and lay them out nicely in a web page. So far, so easy. However, the spreadsheet text will be the content of a series of social media posts which includes emojis within that content. I did a very basic test and found that the emojis turn into question marks when dropped to the page by the script.
I don't particularly like emojis myself but I don't get to choose whether they are included in the text, and they need to appear in the end result.
Here's what a stripped back version of the script looks like, with no formatting etc.
<%# Language=VBScript%>
<html><head></head>
<body>
<%
Dim objConn, objRS
Set objConn = Server.CreateObject("ADODB.Connection")
filepath = "xls/OPG.xls"
objConn.Open "DRIVER={Microsoft Excel Driver (*.xls)}; IMEX=1; HDR=NO; Excel 8.0; DBQ=" & Server.MapPath(filepath) & "; "
strSQL = "SELECT * FROM A1:C400"
Set objRS=objConn.Execute(strSQL)
Set DataList = CreateObject("ADOR.Recordset")
Do Until objRS.EOF
Response.Write objRS.Fields("Post Description").Value & "<br /><br />"
objRS.MoveNext
Loop
objConn.Close
Set objConn=Nothing
%>
</body>
</html>
Here's what the original XLS file looks like...
...and here's how that comes into the web page...
How do I get around this? Any ideas?
Thanks
The Microsoft Access Database Engine is able to read and display emojis from Excel files:
https://www.microsoft.com/en-us/download/details.aspx?id=54920
You will need to set your codepage and charset to UTF-8 though:
<%#LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
response.Charset = "utf-8"
%>
Connection string:
objConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Server.MapPath(filepath) & ";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1"";"
Tested and working.

classic ASP not seeing vbscript

I have to support an old web server developed in classic ASP and VBScript. I am running on Windows 7 with IIS 7.5.
I followed all the instructions on configuring the IIS from this article.
The web page loads, but it looks like the JS doesn't see functions in VBScript.
I have this code:
<%# Language=VBScript %>
<!-- #include file="HebrewMeta_UTF8.jv"-->
<link rel="stylesheet" type="text/css" href="../Class.css">
<html>
<head>
<%
Nm=Request("Nm")
%>
<title>my page</title>
</head>
<script LANGUAGE="javascript">
var Nm = "<%=Nm%>";
function onCheckPro() {
nm = window.navigator.appName;
if ((nm.indexOf("Explorer") == "-1") && (nm.indexOf("Netscape") == "-1")){
alert(" Compatibility שינוי הגדרות ");
window.open("http://www.comax.co.il/InstallTools/compatibility-view.reg");
//alert("ניתן להפעיל באקספלורר בלבד");
//return;
}
document.all.fr.src = "CheckLogInPro.asp?Kod=" + escape(Kod.value) + "&Pass=" + escape(Pass.value) + "&Date=" + vbDate();
}
</script>
<script LANGUAGE="vbscript">
function vbDate()
vbDate=Cstr(Day(Date()))+"/"+Cstr(Month(Date()))+"/"+Cstr(Year(Date()))+" "+Cstr(hour(Now()))+":"+Cstr(Minute(Now()))+":"+Cstr(Second(Now()))
end function
</script>
I keep on getting "'vbDate' is undefined".
The script language of the site ASP is set to VBScript.
Not an answer, but three warnings:
vbDate is a predefined data type constant; using it to name a function is asking for trouble.
The string concatenation in VBScript is &, not +.
Volatile functions like Date() or Now() shouldn't be used more than once in an expression.
Update wrt comment:
People who like to live dangerously should look at:
WScript.Echo vbDate(), checkType(Now())
Function vbDate()
vbDate = "vbDate is a predefined constant: >" & vbDate & "<"
End Function
Function checkType(x)
Select Case VarType(x)
Case vbDate
checkType = x & " is a date"
Case Else
checkType = x & " is an abomination"
End Select
End Function
output:
cscript xvbdate.vbs
vbDate is a predefined constant: >< 11/14/2014 3:48:17 PM is an abomination
output after changing the function's name:
cscript xvbdate.vbs
vbDate is a predefined constant: >7< 11/14/2014 3:56:57 PM is a date
before using any variable you should give a data type to that variable
dim or var
vbDate
vbDate=Cstr(Day(Date()))+"/"+Cstr(Month(Date()))+"/"+Cstr(Year(Date()))+" "+Cstr(hour(Now()))+":"+Cstr(Minute(Now()))+":"+Cstr(Second(Now()))

ASP FileObject.Name converting to '?'

I have a script that lists all files in a directory, then for each one it will Response.Write the name and how many downloads it has.
I have everything completed, but when I went for a test, the files that have "odd" characters in the name are replace with a ?
I'm guessing, that since some files have foreign languages as there name, and that some have the iPhone emoji icons in the name, that it doesn't recognize it and puts a ? instead, but this is a serious issue since I can't give the correct file name back to the user, then that incorrect name is fed back into the url to download. (Which doesn't work)
Any suggestions?
Edit:
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fo=fs.GetFolder(Server.MapPath("."))
for each file in fo.files
if fs.GetExtensionName(file.Path) = "plist" then
dim tempList, tempName, ...
tempList = split(file.Name, ".")
'Manipulate name and data ...
Response.write(name)
end if
next
The file names themselves have odd characters, and file.Name returns a ? instead of what is actually there.
18アイコン is one example.
Here's some code which works fine for me:
<%# Language="VBScript" CodePage="65001" %><%
Option Explicit
Response.CodePage = 65001
Response.CharSet = "utf-8"
Dim fs, fo, file
Set fs = Server.CreateObject("Scripting.FileSystemObject")
Set fo = fs.GetFolder(Server.MapPath("."))
For Each file In fo.files
If fs.GetExtensionName(file.Path) = "plist" Then
' Do whatever here...
Response.Write file.Name & "<br>"
End If
Next
%>
If you are using any variables that you didn't dimension beforehand, you'll need to remove the Option Explicit; otherwise, VBScript will complain that you didn't dimension them.
Edit: I copy & pasted the wrong code; this code works.

Difference between two strings in VBScript

I need a way to find the difference between two strings in a Windows application using VBScript. One of the strings is known but the second one is completely unknown during coding. I know there are functions like StrCompare, InStr etc. but these require you to know the second string also during coding.
Explanation:
There is a text box in the screen and there are several buttons in the same screen. As and when the buttons are clicked, the text in the text box changes depending on the button clicked. Is there a way to find the changes made to the text after the button is clicked ? Basically I need to get the text entered due to the button click. Is there a simple way to do this or it requires complex coding ?
Thanks in Advance.
It depends on your application and the format of the new string.
If you need to find the text appended to the original string, you could take the new text and simply replace the first occurrence of the original string with an empty string:
Dim strOld, strNew, strDiff
strOld = "Apple"
strNew = "Apple, Orange"
strDiff = Replace(strNew, strOld, "", 1, 1)
WScript.Echo strDiff
Sample output:
, Orange
Or if you need to get the appended text without the preceding comma, you could use something like this:
strDiff = Replace(strNew, strOld + ", ", "", 1, 1)
To access (read/write) the content of a HTML text input you need to get the HTML element (document.all.<Name/Id> or document.getElementById(<Name/Id>) and its .value; as in this demo:
<html>
<head>
<Title>readtext</Title>
<hta:application id="readtext" scroll = "no">
<script type="text/vbscript">
Function Change()
document.all.txtDemo.value = "Changed Value"
End Function
Function Check()
Dim txtDemo : Set txtDemo = document.getElementById("txtDemo")
Dim sDemo : sDemo = txtDemo.value
Select Case LCase(Trim(sDemo))
Case "initial value"
MsgBox "still: " & sDemo
Case "changed value"
MsgBox "now: " & sDemo
Case Else
MsgBox "surpise: " & sDemo
End Select
End Function
</script>
</head>
<body>
<input type="text" id="txtDemo" value="Initial Value" />
<hr />
<input type="button" value="Change" onclick="Change" />
<input type="button" value="Check" onclick="Check" />
</body>
</html>

Multiline strings in VB.NET

Is there a way to have multiline strings in VB.NET like Python
a = """
multi
line
string
"""
or PHP?
$a = <<<END
multi
line
string
END;
Of course something that is not
"multi" & _
"line
You can use XML Literals to achieve a similar effect:
Imports System.XML
Imports System.XML.Linq
Imports System.Core
Dim s As String = <a>Hello
World</a>.Value
Remember that if you have special characters, you should use a CDATA block:
Dim s As String = <![CDATA[Hello
World & Space]]>.Value
2015 UPDATE:
Multi-line string literals were introduced in Visual Basic 14 (in Visual Studio 2015). The above example can be now written as:
Dim s As String = "Hello
World & Space"
MSDN article isn't updated yet (as of 2015-08-01), so check some answers below for details.
Details are added to the Roslyn New-Language-Features-in-VB-14 Github repository.
VB.Net has no such feature and it will not be coming in Visual Studio 2010. The feature that jirwin is refering is called implicit line continuation. It has to do with removing the _ from a multi-line statement or expression. This does remove the need to terminate a multiline string with _ but there is still no mult-line string literal in VB.
Example for multiline string
Visual Studio 2008
Dim x = "line1" & vbCrlf & _
"line2"
Visual Studio 2010
Dim x = "line1" & vbCrlf &
"line2"
I used this variant:
Dim query As String = <![CDATA[
SELECT
a.QuestionID
FROM
CR_Answers a
INNER JOIN
CR_Class c ON c.ClassID = a.ClassID
INNER JOIN
CR_Questions q ON q.QuestionID = a.QuestionID
WHERE
a.CourseID = 1
AND
c.ActionPlan = 1
AND q.Q_Year = '11/12'
AND q.Q_Term <= (SELECT CurrentTerm FROM CR_Current_Term)
]]>.Value()
it allows < > in the string
Multi-line strings are available since the Visual Studio 2015.
Dim sql As String = "
SELECT ID, Description
FROM inventory
ORDER BY DateAdded
"
You can combine them with string interpolation to maximize usefullness:
Dim primaryKey As String = "ID"
Dim inventoryTable As String = "inventory"
Dim sql As String = $"
SELECT {primaryKey}, Description
FROM {inventoryTable}
ORDER BY DateAdded
"
Note that interpolated strings begin with $ and you need to take care of ", { and } contained inside – convert them into "", {{ or }} respectively.
Here you can see actual syntax highlighting of interpolated parts of the above code example:
If you wonder if their recognition by the Visual Studio editor also works with refactoring (e.g. mass-renaming the variables), then you are right, code refactoring works with these. Not mentioning that they also support IntelliSense, reference counting or code analysis.
Multiline string literals are introduced in Visual Basic 14.0 - https://roslyn.codeplex.com/discussions/571884
You can use then in the VS2015 Preview, out now - http://www.visualstudio.com/en-us/downloads/visual-studio-2015-downloads-vs (note that you can still use VS2015 even when targeting an older version of the .NET framework)
Dim multiline = "multi
line
string"
VB strings are basically now the same as C# verbatim strings - they don't support backslash escape sequences like \n, and they do allow newlines within the string, and you escape the quote symbol with double-quotes ""
this was a really helpful article for me, but nobody mentioned how to concatenate in case you want to send some variables, which is what you need to do 99% of the time.
... <%= variable %> ...
Here's how you do it:
<SQL>
SELECT * FROM MyTable WHERE FirstName='<%= EnteredName %>'
</SQL>.Value
Well, since you seem to be up on your python, may I suggest that you copy your text into python, like:
s="""this is gonna
last quite a
few lines"""
then do a:
for i in s.split('\n'):
print 'mySB.AppendLine("%s")' % i
# mySB.AppendLine("this is gonna")
# mySB.AppendLine("last quite a")
# mySB.AppendLine("few lines")
or
print ' & _ \n'.join(map(lambda s: '"%s"' % s, s.split('\n')))
# "this is gonna" & _
# "last quite a" & _
# "few lines"
then at least you can copy that out and put it in your VB code. Bonus points if you bind a hotkey
(fastest to get with:Autohotkey) to do this for for whatever is in your paste buffer. The same idea works well for a SQL formatter.
Multi-line string literals in vb.net using the XElement class.
Imports System.Xml.Linq
Public Sub Test()
dim sOderBy as string = ""
dim xe as XElement = <SQL>
SELECT * FROM <%= sTableName %>
<ORDER_BY> ORDER BY <%= sOrderBy %></ORDER_BY>
</SQL>
'** conditionally remove a section
if sOrderBy.Length = 0 then xe.<ORDER BY>.Remove
'** convert XElement value to a string
dim sSQL as String = xe.Value
End Sub
To me that is the most annoying thing about VB as a language.
Seriously, i once wrote the string in a file and wrote code something along the lines of:
Dim s as String = file_get_contents("filename.txt")
just so i could test the query directly on SQL server if i need to.
My current method is to use a stored procedure on the SQL Server and just call that so i can pass in parameters to the query, etc
I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.
You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.
Dim script As String = <code><![CDATA[
<script type="text/javascript">
var URL = ']]><%= domain %><![CDATA[/mypage.html';
</script>]]>
</code>.value
You could (should?) put the string in a resource-file (e.g. "My Project"/Resources) and then get it with
Dim a = My.Resources.Whatever_you_chose
Disclaimer: I love python. It's multi-line strings are only one reason.
But I also do VB.Net, so here's my short-cut for more readable long strings.
Dim lines As String() = {
"Line 1",
"Line 2",
"Line 3"
}
Dim s As String = Join(lines, vbCrLf)
you can use XML for this like
dim vrstr as string = <s>
some words
some words
some
words
</s>
in Visual studio 2010 (VB NET)i try the following and works fine
Dim HtmlSample As String = <anything>what ever you want to type here with multiline strings</anything>
dim Test1 as string =<a>onother multiline example</a>
Available in Visual Basic 14 as part of Visual Studio 2015
https://msdn.microsoft.com/en-us/magazine/dn890368.aspx
But not yet supported by R#. The good news is they will be supported soon! Please vote on Youtrack to notify JetBrains you need them also.
If you need an XML literal in VB.Net with an line code variable, this is how you would do it:
<Tag><%= New XCData(T.Property) %></Tag>
Since this is a readability issue, I have used the following code:
MySql = ""
MySql = MySql & "SELECT myTable.id"
MySql = MySql & " FROM myTable"
MySql = MySql & " WHERE myTable.id_equipment = " & lblId.Text
You can also use System.Text.StringBuilder class in this way:
Dim sValue As New System.Text.StringBuilder
sValue.AppendLine("1st Line")
sValue.AppendLine("2nd Line")
sValue.AppendLine("3rd Line")
Then you get the multiline string using:
sValue.ToString()
Use vbCrLf or vbNewLine. It works with MessageBoxes and many other controls I tested.
Dim str As String
str = "First line" & vbCrLf & "Second line"
MsgBox(str)
str = "First line" & vbNewLine & "Second line"
MsgBox(str)
It will show two identical MessageBoxes with 2 lines.
No, VB.NET does not yet have such a feature. It will be available in the next iteration of VB (visual basic 10) however (link)
if it's like C# (I don't have VB.Net installed) you can prefix a string with #
foo = #"Multiline
String"
this is also useful for things like #"C:\Windows\System32\" - it essentially turns off escaping and turns on multiline.

Resources