I need to download a CSV file from a website using VBA in Excel. The server also needed to authenticate me since it was data from a survey service.
I found a lot of examples using Internet Explorer controlled with VBA for this. However, it was mostly slow solutions and most were also convoluted.
Update:
After a while I found a nifty solution using Microsoft.XMLHTTP object in Excel. I thought to share the solution below for future reference.
This solution is based from this website:
http://social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save-csv-from-url
It is slightly modified to overwrite existing file and to pass along login credentials.
Sub DownloadFile()
Dim myURL As String
myURL = "https://YourWebSite.com/?your_query_parameters"
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "username", "password"
WinHttpReq.send
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile "C:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite
oStream.Close
End If
End Sub
Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Sub Example()
DownloadFile$ = "someFile.ext" 'here the name with extension
URL$ = "http://some.web.address/" & DownloadFile 'Here is the web address
LocalFilename$ = "C:\Some\Path" & DownloadFile !OR! CurrentProject.Path & "\" & DownloadFile 'here the drive and download directory
MsgBox "Download Status : " & URLDownloadToFile(0, URL, LocalFilename, 0, 0) = 0
End Sub
Source
I found the above when looking for downloading from FTP with username and address in URL. Users supply information and then make the calls.
This was helpful because our organization has Kaspersky AV which blocks active FTP.exe, but not web connections. We were unable to develop in house with ftp.exe and this was our solution. Hope this helps other looking for info!
A modified version of above to make it more dynamic.
Public Function DownloadFileB(ByVal URL As String, ByVal DownloadPath As String, ByRef Username As String, ByRef Password, Optional Overwrite As Boolean = True) As Boolean
On Error GoTo Failed
Dim WinHttpReq As Object: Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", URL, False, Username, Password
WinHttpReq.send
If WinHttpReq.Status = 200 Then
Dim oStream As Object: Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
oStream.SaveToFile DownloadPath, Abs(CInt(Overwrite)) + 1
oStream.Close
DownloadFileB = Len(Dir(DownloadPath)) > 0
Exit Function
End If
Failed:
DownloadFileB = False
End Function
I was struggling for hours on this until I figured out it can be done in one line of powershell:
invoke-webrequest -Uri "http://myserver/Reports/Pages/ReportViewer.aspx?%2fClients%2ftest&rs:Format=PDF&rs:ClearSession=true&CaseCode=12345678" -OutFile "C:\Temp\test.pdf" -UseDefaultCredentials
I looked into doing it purely in VBA but it runs to several pages, so I just call my powershell script from VBA every time I want to download a file.
Simple.
Public Sub Test_DownloadFile()
Dim URLStr As String, DLPath As String, UName As String, PWD As String, DontOverWrite As Boolean
URLStr = "http.."
DLPath = Environ("USERPROFILE") & "\Downloads\TEST.PDF"
UName = ""
PWD = ""
DontOverWrite = False
Call DownloadFile(URLStr, DLPath, UName, PWD, DontOverWrite)
End Sub
Public Sub DownloadFile(ByVal URLStr As String, ByVal DLPath As String, Optional ByVal UName As String, Optional ByVal PWD As String, Optional DontOverWrite As Boolean)
On Error GoTo Failed
Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", URLStr, False, UName, PWD
WinHttpReq.send
If WinHttpReq.status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.responseBody
Dim OWrite As Integer
If DontOverWrite = True Then
OWrite = 1
Else
OWrite = 2
End If
oStream.SaveToFile DLPath, OWrite
oStream.Close
Debug.Print "Downloaded " & URLStr & " To " & DLPath
Exit Sub
End If
Failed:
Debug.Print "Failed to DL " & URLStr
End Sub
A modified version of above solution to make it more dynamic.
Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean
On Error GoTo Failed
DownloadFileA = False
'As directory must exist, this is a check
If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function
Dim returnValue As Long
returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0)
'If return value is 0 and the file exist, then it is considered as downloaded correctly
DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0)
Exit Function
Failed:
End Function
Related
I have this posted under my original post, but thought I would create a new question. I have the below code working that looks at my table in MS Access that has the path + file name and moves it to a new directory; I will also be looking at how to put Folders/Subfolders in the "new" directory based off of the original directory, but am unsure how to accomplish that. It currently works on my test table that has <259 characters in the path, but fails on long path/file names >259. Thoughts how how this can be addressed?
Appreciate the help.
Sub CopyFilesFromTable2()
On Error GoTo ErrorHandler
Dim source As String
Dim destination As String
Dim FSO As New FileSystemObject
Dim SQL As String
Dim RS As DAO.Recordset
Dim db As DAO.Database
'Test Table
SQL = "select * from file_test"
'Prod Table
'SQL = "select * from file"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set db = CurrentDb
Set RS = db.OpenRecordset(SQL)
source = RS!LocalFile
File = VBA.FileSystem.Dir(source)
destination = "D:\Temp\Test\"
With RS
If Not .BOF And Not .EOF Then
.MoveLast
.MoveFirst
While (Not .EOF)
FSO.CopyFile RS!LocalFile, destination
.MoveNext
Wend
End If
.Close
End With
ExitSub:
Set RS = Nothing
'set to nothing
MsgBox "Done!"
Exit Sub
ErrorHandler:
MsgBox Err, vbCritical
Resume ExitSub
End Sub
You've got a problem with long paths here, generally, these are best avoided.
However, with a tiny bit of WinAPI, you can easily avoid the issue.
Implement CopyFileExW:
Public Declare PtrSafe Function CopyFileExW Lib "Kernel32.DLL" (ByVal lpExistingFileName As LongPtr, ByVal lpNewFileName As LongPtr, ByVal lpProgressRoutine As LongPtr, ByVal lpData As LongPtr, ByRef pbCancel As Boolean, ByVal dwCopyFlags As Long) As Boolean
Declare consts:
Const COPY_FILE_FAIL_IF_EXISTS = 1&
Create a function that calls CopyFileExW, and prepends \\?\ to the path to allow for long paths:
Public Function CopyFile(strSource As String, strDestination As String, Optional Overwrite As Boolean = False)
strSource = "\\?\" & strSource
strDestination = "\\?\" & strDestination
Dim flags As Long
If Not Overwrite Then
flags = COPY_FILE_FAIL_IF_EXISTS
End If
Dim res As Boolean
res = CopyFileExW(StrPtr(strSource), StrPtr(strDestination), 0, 0, ByVal 0, flags)
If res = False Then
Err.Raise -5000, Description:="Copy file failed, error code " & Err.LastDllError
End If
End Function
And use that function, instead of RS!LocalFile, destination:
'CopyFile file needs the full path, so we append the filename
CopyFile RS!LocalFile, Destination & Right(RS!LocalFile, InStr(strReverse("RS!LocalFile"), "\") - 1)
I am trying to connect MS Word to Microsoft's QnAMaker using VBA to help answer a wide variety of similar questions I receive.
My idea is select the question and then have vba query the answer and copy it to the clipboard (templates for replies are different, this way I can select where to output the answer).
Any help is appreciated. Thank you.
(I am using this JSON library: https://github.com/VBA-tools/VBA-JSON)
I have already applied the suggested solutions described in the issue section below: https://github.com/VBA-tools/VBA-JSON/issues/68
Sub copyAnswer()
'User Settings
Dim questionWorksheetName As String, questionsColumn As String,
firstQuestionRow As String, kbHost As String, kbId As String, endpointKey
As String
Dim str As String
str = Selection.Text
kbHost = "https://rfp1.azurewebsites.net/********"
kbId = "********-********-*********"
endpointKey = "********-********-********"
'Loop through all non-blank cells
Dim answer, score As String
Dim myArray() As String
Dim obj As New DataObject
answer = GetAnswer(str, kbHost, kbId, endpointKey)
Call ClipBoard_SetData(answer)
End Sub
Function GetAnswer(question, kbHost, kbId, endpointKey) As String
'HTTP Request Settings
Dim qnaUrl As String
qnaUrl = kbHost & "/knowledgebases/" & kbId & "/generateAnswer"
Dim contentType As String
contentType = "application/json"
Dim data As String
data = "{""question"":""" & question & """}"
'Send Request
Dim xmlhttp As New MSXML2.XMLHTTP60
xmlhttp.Open "POST", qnaUrl, False
xmlhttp.setRequestHeader "Content-Type", contentType
xmlhttp.setRequestHeader "Authorization", "EndpointKey " & endpointKey
**xmlhttp.send data**
'Convert response to JSON
Dim json As Scripting.Dictionary
Set json = JsonConverter.ParseJson(xmlhttp.responseText)
Dim answer As Scripting.Dictionary
For Each answer In json("answers")
'Return response
GetAnswer = answer("answer")
Next
End Function
Private Function json_ParseObject(json_String As String, ByRef json_Index As Long) As Scripting.Dictionary
Dim json_Key As String
Dim json_NextChar As String
Set json_ParseObject = New Scripting.Dictionary
json_SkipSpaces json_String, json_Index
...
I am encountering the following error which I am uncertain how to resolve: "This method cannot be called after the send method has been called".
The error occurs on the line: xmlhttp.send data
The GitHub issue you linked kind of had the answer, but it's not complete. Here's what you do (from the VBA Dev Console in Word):
In Modules > JsonConverter
Go to Private Function json_ParseObject
Add Scripting. to Dictionary in two places:
from:
Private Function json_ParseObject(json_String As String, ByRef json_Index As Long) As Dictionary
to:
Private Function json_ParseObject(json_String As String, ByRef json_Index As Long) As Scripting.Dictionary
and from:
Set json_ParseObject = New Dictionary
to:
Set json_ParseObject = New Scripting.Dictionary
In GetAnswer():
Also change from:
Dim json As Dictionary
to:
Dim json As Scripting.Dictionary
and from:
Dim answer As Dictionary
to:
Dim answer As Scripting.Dictionary
Here's my full working code:
In ThisDocument:
Sub copyAnswer()
'User Settings
Dim kbHost As String, kbId As String, endpointKey As String
Dim str As String
str = "test"
kbHost = "https:/*********.azurewebsites.net/qnamaker"
kbId = "***************************"
endpointKey = "*************************"
'Loop through all non-blank cells
Dim answer, score As String
Dim myArray() As String
answer = GetAnswer(str, kbHost, kbId, endpointKey)
End Sub
Function GetAnswer(question, kbHost, kbId, endpointKey) As String
'HTTP Request Settings
Dim qnaUrl As String
qnaUrl = kbHost & "/knowledgebases/" & kbId & "/generateAnswer"
Dim contentType As String
contentType = "application/json"
Dim data As String
data = "{""question"":""" & question & """}"
'Send Request
Dim xmlhttp As New MSXML2.XMLHTTP60
xmlhttp.Open "POST", qnaUrl, False
xmlhttp.setRequestHeader "Content-Type", contentType
xmlhttp.setRequestHeader "Authorization", "EndpointKey " & endpointKey
xmlhttp.send data
'Convert response to JSON
Dim json As Scripting.Dictionary
Set json = JsonConverter.ParseJson(xmlhttp.responseText)
Dim answer As Scripting.Dictionary
For Each answer In json("answers")
'Return response
GetAnswer = answer("answer")
Next
End Function
In Modules > JsonConverter
Private Function json_ParseObject(json_String As String, ByRef json_Index As Long) As Scripting.Dictionary
Dim json_Key As String
Dim json_NextChar As String
Set json_ParseObject = New Scripting.Dictionary
json_SkipSpaces json_String, json_Index
If VBA.Mid$(json_String, json_Index, 1) <> "{" Then
Err.Raise 10001, "JSONConverter", json_ParseErrorMessage(json_String, json_Index, "Expecting '{'")
Else
json_Index = json_Index + 1
Do
json_SkipSpaces json_String, json_Index
If VBA.Mid$(json_String, json_Index, 1) = "}" Then
json_Index = json_Index + 1
Exit Function
ElseIf VBA.Mid$(json_String, json_Index, 1) = "," Then
json_Index = json_Index + 1
json_SkipSpaces json_String, json_Index
End If
json_Key = json_ParseKey(json_String, json_Index)
json_NextChar = json_Peek(json_String, json_Index)
If json_NextChar = "[" Or json_NextChar = "{" Then
Set json_ParseObject.Item(json_Key) = json_ParseValue(json_String, json_Index)
Else
json_ParseObject.Item(json_Key) = json_ParseValue(json_String, json_Index)
End If
Loop
End If
End Function
Ok, I'm writing a VB.Net application, and I'm using the ODBC32 DLL. Why? Because the ODBC interface classes cannot handle all of the field types from Informix databases, noteably the TimeSpan type.
I can successfully connect to ODBC databases, query the user for a DSN, and successfully pull data, so long as I just want the data returned as a string or a number. If, on the other hand, if I try to get some meta data about the columns I'm pulling in order to convert the returned data into specific data types, I get an error.
"vshost32.exe has stopped working" - I can look online for a solution, close the program or wait. There are no options to look at the code itself with live debugging.
When I do not get this error, I get a memory access violation, but I don't have any details there.
So my question is, why does the other stuff work, but this one, really important thing not work? Do I need to write this in something that isn't VB.Net? Will C# work?
Below is the contents of the class file. I apologize as it's a lot of stuff, but I didn't want to leave anything out. Kind of like going to the doctor and not telling them about all the donuts. The actual SQL doesn't seem to matter. "Select {any column} from {any table}" is what I've been using with a table that has 120 records. Without looking at the column meta data it seems to work fine.
Public Class ODBC32Interface
Public Declare Function SQLAllocEnv Lib "odbc32.dll" (ByRef env As Integer) As Short
Public Declare Function SQLAllocConnect Lib "odbc32.dll" (ByVal env As Integer, ByRef lHdbc As Integer) As Short
Public Declare Function SQLAllocHandle Lib "odbc32.dll" (ByVal handleType As Short, ByVal inputHandle As Integer, _
ByRef outputHandle As Integer) As Short
Public Declare Function SQLAllocStmt Lib "odbc32.dll" (ByVal connectionHandle As Integer, ByRef hStmt As Integer) As Short
Public Declare Function SQLDriverConnect Lib "ODBC32.DLL" (ByVal ConnectionHandle As Integer, _
ByVal WindowHandle As Integer, _
ByVal InConnectionString As String, _
ByVal StringLength1 As Short, _
ByVal OutConnectionString As String, _
ByVal BufferLength As Short, _
ByRef StringLength2Ptr As Short, _
ByVal DriverCompletion As Short) As Short
Public Declare Function SQLDisconnect Lib "odbc32.dll" (ByVal lHdbc As Integer) As Short
Public Declare Function SQLFreeConnect Lib "odbc32.dll" (ByVal lHdbc As Integer) As Short
Public Declare Function SQLFreeEnv Lib "odbc32.dll" (ByVal env As Integer) As Short
Public Declare Function SQLFreeStmt Lib "odbc32.dll" (ByVal statementhandle As Integer, ByVal [option] As Short) As Short
Public Declare Function SQLExecDirect Lib "odbc32.dll" (ByVal statementHandle As Integer, ByVal statementText As String, _
ByVal textLength As Short) As Short
Public Declare Function SQLFetch Lib "odbc32.dll" (ByVal statementhandle As Integer) As Short
Public Declare Function SQLGetData Lib "odbc32.dll" (ByVal statementhandle As Integer, ByVal columnnumber As Short, _
ByVal targetType As Short, ByVal targetValue As StringBuilder, _
ByVal bufferLength As Integer, ByRef strLen_or_Ind As Integer) As Short
Public Declare Function SQLRowCount Lib "odbc32.dll" (ByVal statementhandle As Integer, ByRef rowcount As Integer) As Short
'' http://msdn.microsoft.com/en-us/library/ms711683%28v=vs.85%29.aspx
Public Declare Function SQLColumns Lib "odbc32.dll" (ByVal statementhandle As Integer, _
ByVal catalogname As String, _
ByVal namelength1 As Integer, _
ByVal schemaname As String, _
ByVal namelength2 As Integer, _
ByVal tablename As String, _
ByVal namelength3 As Integer, _
ByVal columnname As String, _
ByVal namelength4 As Integer) As Short
'' http://msdn.microsoft.com/en-us/library/ms715393%28v=vs.85%29.aspx
Public Declare Function SQLNumResultCols Lib "odbc32.dll" (ByVal StatementHandle As Integer, _
ByRef ColumnCountPtr As Integer) As Short
'' http://msdn.microsoft.com/en-us/library/ms713558%28v=vs.85%29.aspx
'' see if column 10 for fieldidentifier returns the column name
Public Declare Function SQLColAttribute Lib "odbc32.dll" (ByVal StatementHandle As Integer, _
ByVal ColumnNumber As Integer, _
ByVal FieldIdentifier As Integer, _
ByRef CharacterAttributePtr As String, _
ByVal BufferLength As Integer, _
ByRef StringLengthPtr As Integer, _
ByRef NumericAttributePtr As Integer) As Short
' '' http://msdn.microsoft.com/en-us/library/ms716289%28v=vs.85%29.aspx
' '' this is causing an access violation, may not be usable
'Public Declare Function SQLDescribeCol Lib "odbc32.dll" (ByVal statementhandle As Integer, ByVal columnnumber As Integer, _
' ByRef columnname As String, ByVal bufferlength As Integer, _
' ByRef NameLengthPtr As Integer, ByRef DataTypePtr As Integer, _
' ByRef ColumnSize As Integer, ByRef DecimalDigitsPtr As Integer, _
' ByRef NullablePtr As Integer) As Short
Public Declare Function SQLError Lib "odbc32.dll" (ByVal environmentHandle As Integer, ByVal connectionHandle As Integer, ByVal statementHandle As Integer, _
ByVal sqlState As StringBuilder, ByRef nativeError As Integer, ByVal msgText As StringBuilder, _
ByVal bufferLength As Short, ByRef textLength As Short) As Short
Public ErrorFlag As Boolean = False
Public ErrorMessages As String = ""
'' save connection info/error messages here
'Public InfoMessage As String = ""
'Public ErrorMessage As String = ""
Const SQL_NTS = -3 'Null-terminated string
Const SQL_C_CHAR = 1
Const SQL_NOSCAN = 2
Const SQL_NOSCAN_ON = 1
Const SQL_NULL_HENV = 0
Const SQL_NULL_HDBC = 0
Const SQL_NULL_HSTMT = 0
Const SQL_SUCCESS = 0
Const MAXBUFLEN = 255
Const MAX_DATA_BUFFER = 255
Const SQL_HANDLE_ENV = 1
Const SQL_HANDLE_DBC = 2
Const SQL_HANDLE_STMT = 3
Const SQL_HANDLE_DESC = 4
Const SQL_CLOSE = 0
Const SQL_DROP = 1
Const SQL_UNBIND = 2
Const SQL_RESET_PARAMS = 3
Const SQL_DRIVER_PROMPT = 2
Const SQL_DRIVER_CONNECT = 0
Const SQL_COLUMN_COUNT = 0
Const SQL_COLUMN_NAME = 1
Const SQL_COLUMN_TYPE = 2
'' http://www.ncbi.nlm.nih.gov/IEB/ToolBox/CPP_DOC/lxr/source/include/dbapi/driver/odbc/unix_odbc/sqlext.h#L575
Const SQL_COLUMN_LENGTH = 3
Const COLUMN_PRECISION = 4
Const SQL_COLUMN_SCALE = 5
Const SQL_COLUMN_DISPLAY_SIZE = 6
Const SQL_COLUMN_NULLABLE = 7
Const SQL_COLUMN_UNSIGNED = 8
Const SQL_COLUMN_MONEY = 9
Const SQL_COLUMN_UPDATABLE = 10
Const SQL_COLUMN_AUTO_INCREMENT = 11
Const SQL_COLUMN_CASE_SENSITIVE = 12
Const SQL_COLUMN_SEARCHABLE = 13
Const SQL_COLUMN_TYPE_NAME = 14
Const SQL_COLUMN_TABLE_NAME = 15
Const SQL_COLUMN_OWNER_NAME = 16
Const SQL_COLUMN_QUALIFIER_NAME = 17
Const SQL_COLUMN_LABEL = 18
Const SQL_COLATT_OPT_MAX = SQL_COLUMN_LABEL
Const SQL_COLUMN_DRIVER_START = 1000
Const SQL_DESC_NAME = SQL_COLUMN_NAME
Const SQL_DESC_ARRAY_SIZE = 20
Const SQL_DESC_ARRAY_STATUS_PTR = 21
Const SQL_DESC_AUTO_UNIQUE_VALUE = SQL_COLUMN_AUTO_INCREMENT
Const SQL_DESC_BASE_COLUMN_NAME = 22
Const SQL_DESC_BASE_TABLE_NAME = 23
Const SQL_DESC_BIND_OFFSET_PTR = 24
Const SQL_DESC_BIND_TYPE = 25
Const SQL_DESC_CASE_SENSITIVE = SQL_COLUMN_CASE_SENSITIVE
Const SQL_DESC_CATALOG_NAME = SQL_COLUMN_QUALIFIER_NAME
Const SQL_DESC_CONCISE_TYPE = SQL_COLUMN_TYPE
Const SQL_DESC_DATETIME_INTERVAL_PRECISION = 26
Const SQL_DESC_DISPLAY_SIZE = SQL_COLUMN_DISPLAY_SIZE
Const SQL_DESC_FIXED_PREC_SCALE = SQL_COLUMN_MONEY
Const SQL_DESC_LABEL = SQL_COLUMN_LABEL
Const SQL_DESC_LITERAL_PREFIX = 27
Const SQL_DESC_LITERAL_SUFFIX = 28
Const SQL_DESC_LOCAL_TYPE_NAME = 29
Const SQL_DESC_MAXIMUM_SCALE = 30
Const SQL_DESC_MINIMUM_SCALE = 31
Const SQL_DESC_NUM_PREC_RADIX = 32
Const SQL_DESC_PARAMETER_TYPE = 33
Const SQL_DESC_ROWS_PROCESSED_PTR = 34
Const SQL_DESC_ROWVER = 35
Const SQL_DESC_SCHEMA_NAME = SQL_COLUMN_OWNER_NAME
Const SQL_DESC_SEARCHABLE = SQL_COLUMN_SEARCHABLE
Const SQL_DESC_TYPE_NAME = SQL_COLUMN_TYPE_NAME
Const SQL_DESC_TABLE_NAME = SQL_COLUMN_TABLE_NAME
Const SQL_DESC_UNSIGNED = SQL_COLUMN_UNSIGNED
Const SQL_DESC_UPDATABLE = SQL_COLUMN_UPDATABLE
'' ********************************************************************************
'' ** ODBC32.DLL database functions
'' ********************************************************************************
'' largely copied from http://www.vbexplorer.com/VBExplorer/viewcode.asp?SendText=files/Odbcmthd
'' here's another code sample - http://www.pinvoke.net/default.aspx/odbc32.SQLBindCol
'' with references to pinvoke.net - http://www.pinvoke.net/default.aspx/odbc32.SQLGetDiagField
Public Shared Function ODBC32Dialog(ByRef callingform As Form) As String
Dim Buf As String = New String(" "c, MAX_DATA_BUFFER)
Dim constr As String = ""
Dim outlen As Short
Dim Retcode As Short
Dim hEnv As Integer
Dim hDBC As Integer
If SQLAllocEnv(hEnv) = SQL_SUCCESS Then
If SQLAllocConnect(hEnv, hDBC) = SQL_SUCCESS Then
'' this pops up the ODBC driver window
'' how do we do this to not get the driver window, but rather use a specific driver?
'' SQLDriverConnect(hDBC, Screen.ActiveForm.hWnd, sConnect (connection string), Len(sConnect), _
'' Buf, MAXBUFLEN, iSize, SQL_DRIVER_CONNECT)
If SQLDriverConnect(hDBC, callingform.Handle.ToInt32, constr, Len(constr), Buf, MAX_DATA_BUFFER, outlen, SQL_DRIVER_PROMPT) = SQL_SUCCESS Then
Retcode = SQLDisconnect(hDBC)
End If
Retcode = SQLFreeConnect(hDBC)
End If
Retcode = SQLFreeEnv(hEnv)
Else
'' could not allocate memory for the connection handle
End If
Return Buf
End Function
'' return a connection pointer
Public Shared Function ODBC32SqlExecDirect(ByVal dsn As String, ByRef callingform As Form, ByVal sqlstatement As String) As Object
Dim Buf As String = New String(" "c, MAX_DATA_BUFFER)
Dim dsnlen As Integer = Len(dsn)
Dim constr As String = ""
Dim outlen As Short
Dim hEnv As Integer
Dim hDBC As Integer
Dim hStmt As Integer
'' SQLExecDirect & SQLError
Dim lRet As Integer
Dim sSqlState As StringBuilder = New StringBuilder(MAX_DATA_BUFFER)
Dim sErrorMsg As StringBuilder = New StringBuilder(MAX_DATA_BUFFER)
Dim lErrNo As Integer
Dim iLen As Integer
Dim sMsg As String
'' SQLFetch
Dim bPerform As Integer = 0
Dim iStatus As Integer = 0
Dim sData As StringBuilder = New StringBuilder(MAX_DATA_BUFFER)
Dim sData2 As String = New String(" "c, MAX_DATA_BUFFER)
Dim lOutLen As Integer = 0
Dim iColumn As Integer = 1
Dim iFieldColumn As Integer = 0
Dim numresultcols As Integer = 0
Dim describeresult As Integer = 0
'' I don't know if I should SQLFreeConnect and SQLFreeEnv here or not
'' I get the feeling that they should stick around for awhile, and disconnect all at once
'' Perhaps we should create an object that holds all three values and returns them
'' or just do everything in this one function - connect, pull data, disconnect since it all works with discrete functions
bPerform = SQLAllocEnv(hEnv)
If bPerform = SQL_SUCCESS Then
Debug.Print("* Initialized odbc drivers")
bPerform = SQLAllocConnect(hEnv, hDBC)
If bPerform = SQL_SUCCESS Then
Debug.Print("* Allocated connection handle")
Debug.Print("* DSN: " & dsn)
bPerform = SQLDriverConnect(hDBC, callingform.Handle.ToInt32, dsn, dsnlen, Buf, MAXBUFLEN, outlen, SQL_DRIVER_CONNECT)
If bPerform = SQL_SUCCESS Then
Debug.Print("* Connected to the driver")
If SQLAllocStmt(hDBC, hStmt) = SQL_SUCCESS Then
Debug.Print("* Allocated statement handle")
If SQLExecDirect(hStmt, sqlstatement, Len(sqlstatement)) = SQL_SUCCESS Then
Debug.Print("* Executed sql statement")
'' this is how many columns we have in our result set
SQLNumResultCols(hStmt, numresultcols)
'' go through all the column information and spit it out, let's see what we've got here
Debug.Print("* NumResultCols: " & numresultcols)
'iFieldColumn = CInt(InputBox("enter the ifieldcolumn integer value"))
iFieldColumn = SQL_DESC_LOCAL_TYPE_NAME
Try
'' trying to use SQLColAttribute
For i As Integer = 1 To numresultcols
Dim iStringLength As Integer = 0
Dim iNumericAttribute As Integer = 0
describeresult = SQLColAttribute(hStmt, i, iFieldColumn, sData2, MAX_DATA_BUFFER, iStringLength, iNumericAttribute)
Debug.Print("Column #: " & i & " / Describe Result: " & describeresult)
Debug.Print("** Field Identifier: " & iFieldColumn)
Debug.Print("** String Value: " & sData2)
Debug.Print("** String Length: " & iStringLength)
Debug.Print("** Numeric Attribute: " & iNumericAttribute)
Debug.Print(" ")
Next
Catch ex As Exception
Debug.Print("System Access Violation")
Debug.Print(ex.ToString())
If Not (ex.InnerException Is Nothing) Then
Debug.Print(ex.InnerException.ToString())
End If
End Try
'' this works just fine
'Try
' '' start pulling data from the database
' bPerform = SQLFetch(hStmt)
' Debug.Print("* Initial bPerform: " & bPerform)
' Do While (bPerform = SQL_SUCCESS)
' bPerform = SQLFetch(hStmt)
' Debug.Print("* bPerform: " & bPerform)
' If bPerform = SQL_SUCCESS Then
' '' how many columns exist in the statement results?
' iStatus = SQLGetData(hStmt, iColumn, 1, sData, MAX_DATA_BUFFER, lOutLen)
' Debug.Print("* iStatus: " & iStatus)
' Debug.Print("* sData: " & sData.ToString())
' End If
' Loop
' bPerform = SQLFreeStmt(hStmt, SQL_DROP)
'Catch ex As Exception
' Debug.Print("* " & ex.ToString())
' If Not (ex.InnerException Is Nothing) Then
' Debug.Print("* " & ex.InnerException.ToString())
' End If
'End Try
Else
'' execute query failed - check for error
lRet = SQLError(hEnv, hDBC, hStmt, sSqlState, lErrNo, sErrorMsg, MAX_DATA_BUFFER, iLen)
sMsg = "Error executing SQL statement" & vbCrLf
sMsg &= "ODBC State: " & Trim(Left(sSqlState.ToString(), InStr(sSqlState.ToString(), Chr(0)) - 1)) & vbCrLf
sMsg &= "ODBC Error Message: " & Left(sErrorMsg.ToString(), iLen)
Debug.Print("* " & sMsg)
End If
Else
'' could not allocate statement handle
Debug.Print("* Could not allocate statement handle")
End If
Else
'' unable to connect to the driver
Debug.Print("* Unable to connect to the driver")
Debug.Print("* bPerform: " & bPerform)
lRet = SQLError(hEnv, hDBC, hStmt, sSqlState, lErrNo, sErrorMsg, MAX_DATA_BUFFER, iLen)
sMsg = "Error executing SQL statement" & vbCrLf
'sMsg &= "ODBC State: " & Trim(Left(sSqlState.ToString(), InStr(sSqlState.ToString(), Chr(0)) - 1)) & vbCrLf
sMsg &= "ODBC State: " & Trim(sSqlState.ToString()) & vbCrLf
sMsg &= "ODBC Error Message: " & Left(sErrorMsg.ToString(), iLen)
Debug.Print("* " & sMsg)
End If
'Retcode = SQLDisconnect(hDBC)
Else
'' unable to allocate memory for connection handle
Debug.Print("* Unable to allocate memory for the connection handle")
End If
'Retcode = SQLFreeConnect(hDBC)
Else
'' unable to initialize odbc drivers
Debug.Print("* Unable to initialize the odbc drivers")
End If
'Retcode = SQLFreeEnv(hEnv)
SQLDisconnect(hDBC)
SQLFreeConnect(hDBC)
SQLFreeEnv(hEnv)
Return Nothing
'Return hDBC
End Function
End Class
For some reason, getting "End Class" in the code block is being problematic.
FIrstly, I should say I don't write VB and never have. I have however written a lot of stuff to ODBC and some ODBC drivers. The definition of SQLColAttribute (and probably a number of others) is suspect as SQLColAttribute is:
SQLRETURN SQLColAttribute (
SQLHSTMT StatementHandle,
SQLUSMALLINT ColumnNumber,
SQLUSMALLINT FieldIdentifier,
SQLPOINTER CharacterAttributePtr,
SQLSMALLINT BufferLength,
SQLSMALLINT * StringLengthPtr,
SQLLEN * NumericAttributePtr);
You are passing VB Integer as args for ColumnNumber and FieldIdentifier and BufferLength which might be ok but it contradicts the NumericAttributePointer which is double the size on 32 bit platforms (and 4* the size on 64 bit platforms) of a SQLUSMALLINT or SQLSMALLINT. So, I doubt you can use Integer for all those arguments.
If say VB Integer was 2 bytes then when you call SQLColAttribute the driver will write 4 bytes into the location pointed to by NumericAttributePtr. If VB Integer is 4 bytes then the values passed for the other args is wrong.
I'm trying to convert the sample C# code provided my echosign in VB.net for use within our applications. Specifically the SendDocument method.
Has anyone out there done this already?
The API is throwing back an error message "Fault: java.lang.NullPointerException" when ever i call it.
Here is the converted function:
Public Shared Function SendDocument(ByVal apiKey As String, ByVal file As Byte(), ByVal recipientEmailAddress As String, ByVal fileName As String, ByVal message As String, ByVal expireDays As Int32) As String
Try
Dim ES As EchoSignDocumentService13 = New EchoSignDocumentService13()
ES.Url = "https://secure.echosign.com/services/EchoSignDocumentService13"
Dim recipients(1) As String
recipients(0) = recipientEmailAddress
Dim localSenderInfo As com.echosign.secure.SenderInfo = Nothing
Dim echoFileInfo(1) As com.echosign.secure.FileInfo
echoFileInfo(0) = New com.echosign.secure.FileInfo()
With echoFileInfo(0)
.fileName = fileName
.mimeType = "application/msword"
.file = file
End With
Dim echoDocumentInfo As com.echosign.secure.DocumentCreationInfo = New com.echosign.secure.DocumentCreationInfo()
With echoDocumentInfo
.tos = recipients
.name = fileName
.message = message
.fileInfos = echoFileInfo
.signatureType = SignatureType.ESIGN
.signatureFlow = SignatureFlow.SENDER_SIGNATURE_NOT_REQUIRED
.daysUntilSigningDeadline = expireDays
End With
Dim echoKey() As DocumentKey
echoKey = ES.sendDocument(apiKey, localSenderInfo, echoDocumentInfo)
Return echoKey(0).documentKey.ToString()
Catch ex As Exception
Return "EchoError: " & ex.Message
End Try
End Function
Any help is most welcome
Thanks
Richard
I'm using Visual Basic 6 and want to do an HTTP POST to a server (it runs Java code) by sending a custom input field along with a PDF file. the PDF file would have to be base 64 bit encoded or use the normal way that HTTP POST work over the Internet when uploading a file. Basically, I just want to upload a file from my Visual Basic 6 program.
How do I do this? Any example source code?
Assuming you know how to load the PDF in to a byte array you've got to get it Base64 encoded and then post that to server using MIME multipart encoding.
You can utilise the MSXML libraries ability to perform Base64 encoding. See this link for details.
Once you have the PDF as a Bas64 string you need to package that as MIME multipart. You can use XMLHTTP object from MSXML to perform that posting for you:-
sEntityBody = "----boundary" & vbCrLf
sEntityBody = sEntityBody & "Content-Disposition: form-data; name=fileInputElementName; filename=""" + sFileName + """" & vbCrLf
sEntityBody = sEntityBody & "Content-Transfer-Encoding: base64" & vbCrLf
sEntityBody = sEntityBody & "Content-Type: application/pdf" & vbCrLf & vbCrLf
sEntityBody = sEntityBody & sPDFBase64 & vbCrLf
sEntityBody = sEntityBody & "-----boundary--" & vbCrLf & vbCrLf
Set xhr = New MSXML2.XMLHTTP30
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=-----boundary")
xhr.Open "POST", sUrl, False
xhr.send sEntityBody
Perhaps not elegant or efficient but it should it work.
Here's the code to handle base 64
Private Declare Function CryptBinaryToString Lib "Crypt32.dll" Alias "CryptBinaryToStringW" (ByRef pbBinary As Byte, ByVal cbBinary As Long, ByVal dwFlags As Long, ByVal pszString As Long, ByRef pcchString As Long) As Long
Private Declare Function CryptStringToBinary Lib "Crypt32.dll" Alias "CryptStringToBinaryW" (ByVal pszString As Long, ByVal cchString As Long, ByVal dwFlags As Long, ByVal pbBinary As Long, ByRef pcbBinary As Long, ByRef pdwSkip As Long, ByRef pdwFlags As Long) As Long
Public Function Base64Decode(sBase64Buf As String) As String
Const CRYPT_STRING_BASE64 As Long = 1
Dim bTmp() As Byte, lLen As Long, dwActualUsed As Long
If CryptStringToBinary(StrPtr(sBase64Buf), Len(sBase64Buf), CRYPT_STRING_BASE64, StrPtr(vbNullString), lLen, 0&, dwActualUsed) = 0 Then Exit Function 'Get output buffer length
ReDim bTmp(lLen - 1)
If CryptStringToBinary(StrPtr(sBase64Buf), Len(sBase64Buf), CRYPT_STRING_BASE64, VarPtr(bTmp(0)), lLen, 0&, dwActualUsed) = 0 Then Exit Function 'Convert Base64 to binary.
Base64Decode = StrConv(bTmp, vbUnicode)
End Function
Public Function Base64Encode(Text As String) As String
Const CRYPT_STRING_BASE64 As Long = 1
Dim lLen As Long, m_bData() As Byte, sBase64Buf As String
m_bData = StrConv(Text, vbFromUnicode)
If CryptBinaryToString(m_bData(0), UBound(m_bData) + 1, CRYPT_STRING_BASE64, StrPtr(vbNullString), lLen) = 0 Then Exit Function 'Determine Base64 output String length required.
sBase64Buf = String$(lLen - 1, Chr$(0)) 'Convert binary to Base64.
If CryptBinaryToString(m_bData(0), UBound(m_bData) + 1, CRYPT_STRING_BASE64, StrPtr(sBase64Buf), lLen) = 0 Then Exit Function
Base64Encode = sBase64Buf
End Function