How do I return a value from the sproc and assigned it to a variable so that it can be used on the ASP page?
The stored procedure that returns the value is called sp_Auction_PaymentEwayXMLReceive.
The output variable is called ReturnedMsg.
My current code is:
Dim Connection
Dim sSQL, sConnString
sConnString="DRIVER={SQL Server};SERVER=XXXX;UID=XXXX; PWD=XXXX;DATABASE=XXXX;"
sSQL = "sp_Auction_PaymentEwayXMLReceive '"&eWay.ResultEwayTrxnStatus&"','"&eWay.ResultEwayTrxnNumber&"','"&eWay.ResultEwayTrxnReference&"','"&eWay.ResultEwayTrxnOption1&"','"&eWay.ResultEwayTrxnOption2&"','"&eWay.ResultEwayTrxnOption3&"','"&eWay.ResultEwayAuthCode&"','"&eWay.ResultEwayReturnAmount&"','"&eWay.ResultEwayTrxnError&"' "
Set sConnection = Server.CreateObject("ADODB.Connection")
Set connection = Server.CreateObject("ADODB.Connection")
connection.Open(sConnString)
connection.execute(sSQL)
--EDIT--
#Andomar
Re Response 1: I have also tried this but I get a 500 error.
'set up output parameter
dim outputParameter
set outputParameter = _
cmd.CreateParameter("ReturnedMsg",adVarChar, _
adParamOutput,40)
'open conn
connection.Open(sConnString)
'append OUTPUT
cmd.Parameters.Append outputParameter
'exec sql
connection.execute(sSQL)
-R
After you create the connection, add an output parameter:
dim outputParameter
set outputParameter = _
cmd.CreateParameter("OutputParameterName",adVarChar, _
adParamOutput,40)
cmd.Parameters.Append outputParameter
After you run the SP, you can use the values like:
Response.Write("<TD>" & _
cmd.Parameters("OutputParameterName").Value & "</TD>")
Related
I create a passthru query SELECTINg rows of a Postgres v.11 database table.
Running currentDb.execute generates ODBC error 3146 and "invalid argument" mentioned in DBEngine.errors.
Opening same query in the database explorer generates ODBC error 3146 and a message box with "permission denied ..." which actually reflects the source of error.
My questions is how can I programmatically get hold of latter more informative error message ?
I think the following will provide what you are looking for:
Public Function DbEngineErrors() As String
Dim intErr As Integer
Dim strRet As String
Dim strErr As String
If DBEngine.Errors.Count > 0 Then
strRet = "DbEngineErrors:"
For intErr = 0 To DBEngine.Errors.Count - 1
strErr = DBEngine.Errors(intErr).Number & " / " & DBEngine.Errors(intErr).Description & " / " & DBEngine.Errors(intErr).Source
strRet = strRet & vbCrLf & strErr
Next
End If
DbEngineErrors = strRet
End Function
I'm adding logging functionality to a Classic ASP application and am having difficulty getting Request.QueryString and Request.ServerVariables to display correctly when users submit UNICODE queries.
For example -
Response.write Request.QueryString
strVar1=&strVar2=%E8%A1%8C%E9%9B%B2%E6%B5%81%E6%B0%B4&strVar3=blah1&strVar4=blah2
Response.write Request.ServerVariables("QUERY_STRING")
strVar1=&strVar2=%E8%A1%8C%E9%9B%B2%E6%B5%81%E6%B0%B4&strVar3=blah1&strVar4=blah2
Yet if I specify a UNICODE variable in Request.QueryString it prints correctly:
Response.write Request.QueryString("strVar2")
行雲流水
How can I get Request.QueryString or Request.ServerVariables("QUERY_STRING") to include UNICODE? I do have the following on both my search and results pages and queries execute successfully against the database:
<%
Response.CodePage = 65001
Response.CharSet = "utf-8"
%>
To answer bobince's question, I'm trying to log search terms and pages from which they're submitted - if there's a better way to do this I'm all ears:
'Enable Logging: writes to MyDB.dbo.logging
'---------------------------------------------------------------------------------------------
Set cmd = Server.CreateObject("ADODB.Command")
cmd.CommandType = adCmdText
cmd.ActiveConnection = objConn
strADName = UCase(Request.ServerVariables("AUTH_USER"))
Protocol = Request.ServerVariables("SERVER_PROTOCOL")
Protocol = Left(Protocol,InStr(Request.ServerVariables("SERVER_PROTOCOL"),"/")-1)
if Request.ServerVariables("SERVER_PORT") = "80" then
port = ""
else
port = ":" & Request.ServerVariables("SERVER_PORT")
end if
CurPageURL = lcase(Protocol) & "://" & Request.ServerVariables("SERVER_NAME") &_
port & Request.ServerVariables("SCRIPT_NAME") & "?" & _
Request.ServerVariables("QUERY_STRING")
strSQL = "INSERT INTO MyDB.dbo.Logging([user],URL) SELECT ?, ? "
cmd.Parameters.Append (cmd.CreateParameter("User", adVarWChar, adParamInput, len(strADName), strADName))
cmd.Parameters.Append (cmd.CreateParameter("URL", adVarWChar, adParamInput, len(CurPageURL), CurPageURL))
cmd.CommandText = strSQL
set objRS = cmd.Execute
'-----------------------------------------------------------------------------------------------
This isn't really anything to do with Unicode.
Request.QueryString does two separate things.
If you use it without arguments, it returns the whole query string exactly as submitted by the browser (as above, the same as the QUERY_STRING server variable).
If you use it with an argument like "strVar2", it splits up the query string into parameter parts, finds the one(s) that correspond to the argument name (strVar2=...), and returns the value. In doing so it takes care of URL-decoding the components of the query string including the name and the value, so the %xx sequences in the input are decoded to the byte sequence they represent: 0xE8, 0xA1, 0x8C and so on. When you print that byte string to a page that a browser decodes as UTF-8, they will see 行雲流水.
You can do a URL-decode step yourself on the full query string if you really want. There isn't a built-in for URL-decoding in Classic ASP but you can write such a function yourself (see eg URLDecode from http://www.aspnut.com/reference/encoding.asp), or use
decodeURIComponent(s.replace(/\+/g, ' '))
from JScript.
Note that if you URL-decode a whole URL string together you are kind of breaking it. For example for input query string:
foo=abc%26def&bar=%e6%97%a5%e6%9c%ac%e8%aa%9e
you would get:
foo=abc&def&bar=日本語
which is fine for the Japanese, but the ampersand in the value for foo has broken the whole string so you can no longer tell for sure what the original parameters were. You should generally only decode URL components once you have split them up from the URL they came in. This is what ASP does for you: Request.QueryString("foo") would correctly return abc&def here which is why you should almost always be using that method to retrieve parameters.
What exactly are you trying to do by decoding a whole query string?
In case this can help someone else:
I resolved this by extracting variable names from QUERY_STRING using the split function with & as the delimiter. I then used the variables with Request.QueryString to get the values, including ones with UNICODE. This works unless the user includes & in the query, which will be pretty rare. I do trap for it so at least in that case I can still see the user and page accessed in the logs. Bobince your response was excellent and I will select it as the answer.
'Enable Logging: writes to MyDB.dbo.logging
'---------------------------------------------------------------------------------------------
Set cmd = Server.CreateObject("ADODB.Command")
cmd.CommandType = adCmdText
cmd.ActiveConnection = objConn
cmd.CommandTimeOut = 1200
strADName = UCase(Request.ServerVariables("AUTH_USER"))
Protocol = Request.ServerVariables("SERVER_PROTOCOL")
Protocol = Left(Protocol,InStr(Request.ServerVariables("SERVER_PROTOCOL"),"/")-1)
if Request.ServerVariables("SERVER_PORT") = "80" then
port = ""
else
port = ":" & Request.ServerVariables("SERVER_PORT")
end if
CurPageURL = lcase(Protocol) & "://" & Request.ServerVariables("SERVER_NAME") &_
port & Request.ServerVariables("SCRIPT_NAME") & "?"
On Error Resume Next
a = Request.ServerVariables("QUERY_STRING")
a = split(a,"&")
for each x in a
'response.write(left(x,InStr(x,"=")-1) & "<br />")
CurPageURL = CurPageURL + left(x,InStr(x,"=")-1) + "=" + Request.QueryString(left(x,InStr(x,"=")-1)) & "&"
next
If Err.Number <> 0 Then
CurPageURL = CurPageURL + "Error: Search Term Contained a &"
Err.Clear
Else
CurPageURL = left(CurPageURL,len(CurPageURL)-1)
End If
strSQL = "INSERT INTO MyDB.dbo.Logging([user],URL) SELECT ?, ? "
cmd.Parameters.Append (cmd.CreateParameter("User", adVarWChar, adParamInput, len(strADName), strADName))
cmd.Parameters.Append (cmd.CreateParameter("URL", adVarWChar, adParamInput, len(CurPageURL), CurPageURL))
cmd.CommandText = strSQL
set objRS = cmd.Execute
So, I'm using (after modification) this code, from here: How to set recurring schedule for xlsm file using Windows Task Scheduler
My error: Runtime error: Unknown runtime error.
I've searched far and wide to find an way to close the Excel process, but almost everybody uses .Quit sadly it gives the above error. I've also tried .Close, but that is not recognized
' Create a WshShell to get the current directory
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application")
' Disable Excel UI elements
myExcelWorker.DisplayAlerts = False
myExcelWorker.AskToUpdateLinks = False
myExcelWorker.AlertBeforeOverwriting = False
myExcelWorker.FeatureInstall = msoFeatureInstallNone
' Tell Excel what the current working directory is
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = "C:\Users\hviid00m\Desktop"
myExcelWorker.DefaultFilePath = strPath
' Open the Workbook specified on the command-line
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\Status Report (Boxplots) TEST.xlsm"
Set oWorkBook = myExcelWorker.Workbooks.Open (strWorkerWB, , , , , , True)
' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "Refresh"
on error resume next
myExcelWorker.Run strMacroName
if err.number <> 0 Then
WScript.Echo "Fejl i macro"
End If
err.clear
on error goto 0
oWorkBook.Save
' Clean up and shut down
' Don’t Quit() Excel if there are other Excel instances
' running, Quit() will shut those down also
myExcelWorker.Quit <--- ERROR
Set oWorkBook = Nothing
Set myExcelWorker = Nothing
Set WshShell = Nothing
Found some code on a different side.
The reason why (as far as I understood) is that .Quit and .Close is for VBA not VBS.
' Clean up and shut down
' Don’t Quit() Excel if there are other Excel instances
' running, Quit() will shut those down also
Dim objWMIService, objProcess, colProcess
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = " & "'EXCEL.EXE'")
For Each objProcess in colProcess
objProcess.Terminate()
Next`
Set oWorkBook = Nothing
Set myExcelWorker = Nothing
Set WshShell = Nothing
Why isn't this working!?! Apparently my database can't find the field "" referred to in your expression.? signed, rather frustrated - ps.
Private Sub Command17_Click()
On Error GoTo Err_Command17_Click
Dim rst As DAO.Recordset
Dim strEmailAddress
Set rst = CurrentDb.OpenRecordset([CourseRosterMaterialsEmail_Query])
Do Until rst.EOF
strEmailAddress = strEmailAddress & rst([CourseRosterMaterialsEmail_Query].[Email]) & ";"
rst.MoveNext
Loop
strEmailAddress = Left(strEmailAddress, Len(strEmailAddress) - 1)
DoCmd.SendObject , , acFormatRTF, strEmailAddress, _
, , [CourseTitle], [Forms]![CourseRosterMaterials_Form]![Details], False, False
rst.Close
Set rst = Nothing
Exit_Command17_Click:
Exit Sub
Err_Command17_Click:
MsgBox Err.Description
Resume Exit_Command17_Click
End Sub
Try this:
Private Sub Command17_Click()
On Error GoTo Err_Command17_Click
Dim rst As DAO.Recordset
Dim strEmailAddress
Set rst = CurrentDb.OpenRecordset([CourseRosterMaterialsEmail_Query])
Do Until rst.EOF
strEmailAddress = strEmailAddress & rst("Email") & ";"
rst.MoveNext
Loop
strEmailAddress = Left(strEmailAddress, Len(strEmailAddress) - 1)
DoCmd.SendObject , , acFormatRTF, strEmailAddress, _
, , [CourseTitle], [Forms]![CourseRosterMaterials_Form]![Details], False, False
rst.Close
Set rst = Nothing
Exit_Command17_Click:
Exit Sub
Err_Command17_Click:
MsgBox Err.Description
Resume Exit_Command17_Click
End Sub
Usually to refer to fields in Recordsets you need to do this:
rst("FieldName") 'May be ambiguous
rst("FieldAliasName") 'Only if you use aliases
rst("tablename.fieldname") 'I'm actually not sure if this always works
rst("[field name]") 'Use brackets for tables with spaces, symbols, or reserved words
I want to be able to run a program through command line and I want to start it with VbScript. I also want to get the output of the command line and assign it to a variable and I want all this to be done silently without cmd windows popping up. I have managed two things separately but not together. Here's what I got so far.
Run the command from cmd and get output:
Dim WshShell, oExec
Set WshShell = WScript.CreateObject("WScript.Shell")
Set oExec = WshShell.Exec("C:\snmpget -c public -v 2c 10.1.1.2 .1.3.6.1.4.1.6798.3.1.1.1.5.1")
x = oExec.StdOut.ReadLine
Wscript.Echo x
The above script works and does what I want except that cmd pops up for a brief moment.
Here's a script that will run silently but won't grab the output
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("C:\snmpset -c public -v 2c -t 0 10.1.1.2 .1.3.6.1.4.1.6798.3.1.1.1.7.1 i 1", 0, true)
Is there a way to get these two to work together?
Let me give you a background on why I want do to this. I am basically polling a unit every 5-10 minutes and I am going to get the script to email or throw a message box when a certain condition occurs but I don't want to see cmd line popping up all day long on my computer. Any suggestions?
Thanks
You can redirect output to a file and then read the file:
return = WshShell.Run("cmd /c C:\snmpset -c ... > c:\temp\output.txt", 0, true)
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("c:\temp\output.txt", 1)
text = file.ReadAll
file.Close
I have taken this and various other comments and created a bit more advanced function for running an application and getting the output.
Example to Call Function: Will output the DIR list of C:\ for Directories only. The output will be returned to the variable CommandResults as well as remain in C:\OUTPUT.TXT.
CommandResults = vFn_Sys_Run_CommandOutput("CMD.EXE /C DIR C:\ /AD",1,1,"C:\OUTPUT.TXT",0,1)
Function
Function vFn_Sys_Run_CommandOutput (Command, Wait, Show, OutToFile, DeleteOutput, NoQuotes)
'Run Command similar to the command prompt, for Wait use 1 or 0. Output returned and
'stored in a file.
'Command = The command line instruction you wish to run.
'Wait = 1/0; 1 will wait for the command to finish before continuing.
'Show = 1/0; 1 will show for the command window.
'OutToFile = The file you wish to have the output recorded to.
'DeleteOutput = 1/0; 1 deletes the output file. Output is still returned to variable.
'NoQuotes = 1/0; 1 will skip wrapping the command with quotes, some commands wont work
' if you wrap them in quotes.
'----------------------------------------------------------------------------------------
On Error Resume Next
'On Error Goto 0
Set f_objShell = CreateObject("Wscript.Shell")
Set f_objFso = CreateObject("Scripting.FileSystemObject")
Const ForReading = 1, ForWriting = 2, ForAppending = 8
'VARIABLES
If OutToFile = "" Then OutToFile = "TEMP.TXT"
tCommand = Command
If Left(Command,1)<>"""" And NoQuotes <> 1 Then tCommand = """" & Command & """"
tOutToFile = OutToFile
If Left(OutToFile,1)<>"""" Then tOutToFile = """" & OutToFile & """"
If Wait = 1 Then tWait = True
If Wait <> 1 Then tWait = False
If Show = 1 Then tShow = 1
If Show <> 1 Then tShow = 0
'RUN PROGRAM
f_objShell.Run tCommand & ">" & tOutToFile, tShow, tWait
'READ OUTPUT FOR RETURN
Set f_objFile = f_objFso.OpenTextFile(OutToFile, 1)
tMyOutput = f_objFile.ReadAll
f_objFile.Close
Set f_objFile = Nothing
'DELETE FILE AND FINISH FUNCTION
If DeleteOutput = 1 Then
Set f_objFile = f_objFso.GetFile(OutToFile)
f_objFile.Delete
Set f_objFile = Nothing
End If
vFn_Sys_Run_CommandOutput = tMyOutput
If Err.Number <> 0 Then vFn_Sys_Run_CommandOutput = "<0>"
Err.Clear
On Error Goto 0
Set f_objFile = Nothing
Set f_objShell = Nothing
End Function
I am pretty new to all of this, but I found that if the script is started via CScript.exe (console scripting host) there is no window popping up on exec(): so when running:
cscript myscript.vbs //nologo
any .Exec() calls in the myscript.vbs do not open an extra window, meaning
that you can use the first variant of your original solution (using exec).
(Note that the two forward slashes in the above code are intentional, see cscript /?)
Here I found a solution, which works for me:
set wso = CreateObject("Wscript.Shell")
set exe = wso.Exec("cmd /c dir /s /b d:\temp\*.jpg")
sout = exe.StdOut.ReadAll
Look for assigning the output to Clipboard (in your first script) and then in second script parse Clipboard value.
#Mark Cidade
Thanks Mark! This solved few days of research on wondering how should I call this from the PHP WshShell. So thanks to your code, I figured...
function __exec($tmppath, $cmd)
{
$WshShell = new COM("WScript.Shell");
$tmpf = rand(1000, 9999).".tmp"; // Temp file
$tmpfp = $tmppath.'/'.$tmpf; // Full path to tmp file
$oExec = $WshShell->Run("cmd /c $cmd -c ... > ".$tmpfp, 0, true);
// return $oExec == 0 ? true : false; // Return True False after exec
return $tmpf;
}
This is what worked for me in my case. Feel free to use and modify as per your needs. You can always add functionality within the function to automatically read the tmp file, assign it to a variable and/or return it and then delete the tmp file.
Thanks again #Mark!
Dim path As String = GetFolderPath(SpecialFolder.ApplicationData)
Dim filepath As String = path + "\" + "your.bat"
' Create the file if it does not exist.
If File.Exists(filepath) = False Then
File.Create(filepath)
Else
End If
Dim attributes As FileAttributes
attributes = File.GetAttributes(filepath)
If (attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly Then
' Remove from Readonly the file.
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly)
File.SetAttributes(filepath, attributes)
Console.WriteLine("The {0} file is no longer RO.", filepath)
Else
End If
If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
' Show the file.
attributes = RemoveAttribute(attributes, FileAttributes.Hidden)
File.SetAttributes(filepath, attributes)
Console.WriteLine("The {0} file is no longer Hidden.", filepath)
Else
End If
Dim sr As New StreamReader(filepath)
Dim input As String = sr.ReadToEnd()
sr.Close()
Dim output As String = "#echo off"
Dim output1 As String = vbNewLine + "your 1st cmd code"
Dim output2 As String = vbNewLine + "your 2nd cmd code "
Dim output3 As String = vbNewLine + "exit"
Dim sw As New StreamWriter(filepath)
sw.Write(output)
sw.Write(output1)
sw.Write(output2)
sw.Write(output3)
sw.Close()
If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
Else
' Hide the file.
File.SetAttributes(filepath, File.GetAttributes(filepath) Or FileAttributes.Hidden)
Console.WriteLine("The {0} file is now hidden.", filepath)
End If
Dim procInfo As New ProcessStartInfo(path + "\" + "your.bat")
procInfo.WindowStyle = ProcessWindowStyle.Minimized
procInfo.WindowStyle = ProcessWindowStyle.Hidden
procInfo.CreateNoWindow = True
procInfo.FileName = path + "\" + "your.bat"
procInfo.Verb = "runas"
Process.Start(procInfo)
it saves your .bat file to "Appdata of current user" ,if it does not exist and remove the attributes
and after that set the "hidden" attributes to file after writing your cmd code
and run it silently and capture all output saves it to file
so if u wanna save all output of cmd to file just add your like this
code > C:\Users\Lenovo\Desktop\output.txt
just replace word "code" with your .bat file code or command and after that the directory of output file
I found one code recently after searching alot
if u wanna run .bat file in vb or c# or simply
just add this in the same manner in which i have written