Get result from chilkatHttp.PostUrlEncodedAsync in VB6 - http

I am using chilkat Http.PostUrlEncodedAsync to send some data to a server and get a JSON response. When the Http_TaskCompleted Event is fired, the task.ResultType returns "object" but there is no task.GetResultObject.
The reply is received correctly (it is present in httpSessionLog.txt) but how do I get it ?

After a different search I have found it:
Private Sub Http_TaskCompleted(ByVal task As Chilkat_v9_5_0.IChilkatTask)
Dim response As New ChilkatHttpResponse
Dim success As Long
success = response.LoadTaskResult(task)
If (success <> 1) Then
Debug.Print response.LastErrorText
Exit Sub
End If
Debug.Print response.BodyStr 'this is the response string
End Sub

Related

Problems With Paypal Express Checkout Integration (WEBREQUEST)

So I was struggling with making head or tail out of the PayPal documentation and always felt that something was not right with my Webrequest.
So I stripped all the code back to basic and simply submitted the request via HTTP and the PLUS side is that I now get a response back from the PayPal sandbox server where ACK=Success and TOKEN=Valid-token-value-here there are some other variables returned too, such as CORRELATIONID and TIMESTAMP.
And hence so I tried some of the webrequest samples and I simply get a blank screen instead of being redirected to Paypal for the (sandbox) customer to complete payment.
So if anyone can post their WebRequest method that would be great.
Here is the code I used for my webrequest, I'm sure its wrong but cannot pinpoint where it is going wrong.
Also, when I run the code on my localhost during debugging, everything works fine and the call is completed with SUCCESS and a TOKEN is received.
When I run it live, I recieve Error Number 5 in the Error exception and also the text `Remote host failed to connect' in the STATUS DESCRIPTION.
THIS IS THE UPDATED CODE
Function MakeWebRequest(ByVal pUseSandbox As Boolean, ByVal pRequestMethod As String, ByVal pReturnUrl As String, ByVal pCancelUrl As String, ByRef pRtnStatus As String, ByRef pRtnStatusId As HttpStatusCode, ByRef pRtnResponseString As String) As Boolean
'
Dim _sxHost As String = Nothing
Dim _sxEndpoint As String = Nothing
Dim _sxNameValCol As System.Collections.Specialized.NameValueCollection = Nothing
Dim _sxResponseCol As System.Collections.Specialized.NameValueCollection = Nothing
Dim _sxCounta As Integer = Nothing
Dim _sxParamsString As String = Nothing
'
'-> Init
_sxParamsString = ""
MakeWebRequest = False
_sxNameValCol = New System.Collections.Specialized.NameValueCollection()
_sxResponseCol = New System.Collections.Specialized.NameValueCollection()
If pUseSandbox Then
_sxHost = "http://www.sandbox.paypal.com"
_sxEndpoint = "https://api-3t.sandbox.paypal.com/nvp"
Else
_sxHost = "http://www.paypal.com"
_sxEndpoint = "https://api-3t.paypal.com/nvp"
End If
'-> Create Request
Try
'-> Key/Value Collection Params
_sxNameValCol.Add("METHOD", "SetExpressCheckout")
_sxNameValCol.Add("USER", _UserName)
_sxNameValCol.Add("PWD", _Password)
_sxNameValCol.Add("SIGNATURE", _Signature)
_sxNameValCol.Add("PAYMENTREQUEST_0_AMT", Format(_Basket.BasketTotalIncDelivery / 100, "0.00"))
_sxNameValCol.Add("PAYMENTREQUEST_0_PAYMENTACTION", "Sale")
_sxNameValCol.Add("PAYMENTREQUEST_0_CURRENCYCODE", "GBP")
_sxNameValCol.Add("RETURNURL", pReturnUrl)
_sxNameValCol.Add("CANCELURL", pCancelUrl)
_sxNameValCol.Add("REQCONFIRMSHIPPING", "0")
_sxNameValCol.Add("NOSHIPPING", "2")
_sxNameValCol.Add("LOCALECODE", "EN")
_sxNameValCol.Add("BUTTONSOURCE", "PP-ECWizard")
_sxNameValCol.Add("VERSION", "93.0")
'-> UrlEncode
For _sxCounta = 0 To _sxNameValCol.Count - 1
If _sxCounta = 0 Then
_sxParamsString = _sxParamsString & _sxNameValCol.Keys(_sxCounta) & "=" & HttpUtility.UrlEncode(_sxNameValCol(_sxCounta))
Else
_sxParamsString = _sxParamsString & "&" & _sxNameValCol.Keys(_sxCounta) & "=" & HttpUtility.UrlEncode(_sxNameValCol(_sxCounta))
End If
Next
'-> Credentials (not used)
'_sxRequest.Credentials = CredentialCache.DefaultCredentials
Try
Dim _sxRequest As WebRequest = DirectCast(System.Net.WebRequest.Create(_sxEndpoint), System.Net.HttpWebRequest)
'-> Convert request to byte-array
Dim _sxByteArray As Byte() = Encoding.UTF8.GetBytes(_sxParamsString)
_sxRequest.Method = "POST" 'Our method is post, otherwise the buffer (_sxParamsString) would be useless
_sxRequest.ContentType = "application/x-www-form-urlencoded" 'We use form contentType, for the postvars
_sxRequest.ContentLength = _sxByteArray.Length 'The length of the buffer (postvars) is used as contentlength
Dim _sxPostDataStream As System.IO.Stream = _sxRequest.GetRequestStream() 'We open a stream for writing the postvars
_sxPostDataStream.Write(_sxByteArray, 0, _sxByteArray.Length) 'Now we write, and afterwards, we close
_sxPostDataStream.Close() 'Closing is always important!
'-> Create Response
Dim _sxResponse As HttpWebResponse = DirectCast(_sxRequest.GetResponse(), HttpWebResponse)
'-> Get Response Status
pRtnStatus = _sxResponse.StatusDescription
pRtnStatusId = _sxResponse.StatusCode
'-> Reponse Stream
Dim _sxResponseStream As Stream = _sxResponse.GetResponseStream() 'Open a stream to the response
'-> Response Stream Reader
Dim _sxStreamReader As New StreamReader(_sxResponseStream) 'Open as reader for the stream
pRtnResponseString = _sxStreamReader.ReadToEnd() 'Read the response string
MakeWebRequest = True
'-> Tidy up
_sxStreamReader.Close()
_sxResponseStream.Close()
_sxResponse.Close()
_sxByteArray = Nothing
_sxPostDataStream = Nothing
_sxRequest = Nothing
_sxResponse = Nothing
_sxResponseStream = Nothing
_sxStreamReader = Nothing
Catch ex As Exception
pRtnStatusId = Err.Number
pRtnStatus = "response(" & ex.Message & ")"
Decode(pRtnResponseString, _sxResponseCol)
pRtnResponseString = Stringify(_sxResponseCol)
End Try
Catch ex As Exception
pRtnStatusId = Err.Number
pRtnStatus = "request(" & ex.Message & ")"
Decode(pRtnResponseString, _sxResponseCol)
pRtnResponseString = Stringify(_sxResponseCol)
End Try
'-> Tidy Up
_sxHost = Nothing
_sxEndpoint = Nothing
_sxNameValCol = Nothing
_sxResponseCol = Nothing
_sxCounta = Nothing
_sxParamsString = Nothing
'
End Function
OK, so it's now clear that you're not getting any response from the server because your server isn't able to connect to PayPal's servers at all. Hence, you got no server-response and the message Unable to connect to the remote server. When I tested, I got a HTTP 200 response with the following body:
TIMESTAMP=2015-07-07T09:07:39Z&CORRELATIONID=7f4d2313c9696&ACK=Failure&VERSION=93.0&BUILD=17276661&L_ERRORCODE0=10002&L_SHORTMESSAGE0=Authentication/Authorization Failed&L_LONGMESSAGE0=You do not have permissions to make this API call&L_SEVERITYCODE0=Error
Obviously that's because I tested with a blank username and password.
So, something is wrong with your server setup that's preventing you from making outside connections, either at the IIS level or due to your firewall configuration.
Without physically being present at your machine, there's not a lot we can do to track down what's blocking it, but you can try opening HTTP requests to other public websites like Google.com and see if those succeed.

Testing if object Is Nothing results in 'Object required' error

I am supporting some classic ASP pages, one of which uses and re-uses an object conn and disposes of it either when the .asp page finishes processing or right before the page redirects to another page.
<%
dim conn
...
set conn = server.CreateObject("adodb.connection")
...
sub cleanUp()
conn.Close
set conn = nothing
end sub
...
sub pageRedirect(url)
call cleanUp()
response.Redirect url : response.End
end sub
...
' very end of file
call cleanUp()%>
I've found that if there is a redirect, I get a server error right at the line conn.Close, Microsoft VBScript runtime error '800a01a8' Object required. I figure there's no reason why that line would execute more than once but to be safe I rewrote the function
sub cleanUp()
if(not (conn Is Nothing)) then
conn.Close
set conn = Nothing
end if
end sub
But I still get that exact error, now at the line if(not (conn Is Nothing))!! I thought the purpose of Is Nothing was to do a test before using the variable name conn precisely to prevent that 'object required' error, but the test is throwing the same error.
What other test can I use to make sure conn isn't referenced if it'd already been set to Nothing?
is nothing is used to test for an object reference, if the variable does not contain such then the test is invalid & raises an error, so conn can only be tested after its been set to something.
You can;
if isobject(conn) then
if not (conn Is Nothing) then set conn = nothing
end if
Use option explicit (each time a script runs without option explicit, a puppie dies out there), you probably would have detected the problem earlier as Nilpo mentioned.
When you dim a variable that you are going to use as an object reference and test it on Nothing, make it a habbit to set it to Nothing at initialization time(*): dim myObject : Set myObject = Nothing.
(*) Not really at initialization, because the dim's are handled before a routine starts, but when you put all your dim's at the top of a routine, it will practically be the same.
Use the IsNothing function. You should also check that it is an object.
sub cleanUp()
if Not IsNothing(conn) then
if IsObject(conn) then
conn.Close
end if
set conn = nothing
end if
end sub
That being said, I would do it like this since setting a variable to nothing does no harm.
sub cleanUp()
if IsObject(conn) then
conn.Close
end if
set conn = nothing
end sub
More importantly though, your problem is that conn is not in scope for your subroutine. You should probably pass it in as a parameter.

Classic asp - response.redirect in a sub - error handling

I wish to do the following ... Provide a page a developer can redirect to provided an error occurs ... like a vb error connection couldn't open or object couldn't be found ... or a database error is raised ... but since I moved the redirect into a sub the page doesn't actually redirect ... Is it possible that I simply can't redirect from a sub? Seems weird.
Run a stored procedure that raises an error
Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = con
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "spReturnDBException"
cmd.Execute
Call a handle errors function that sets up some session parms and redirects if neccessary
HandleErrors con _
, Request.ServerVariables("PATH_INFO") _
, "An error occurred while trying to save sessions." _
, "Actual Error: " + Err.Description + " EmpNo: " + Session("EmpNo") _
+ ". QueryString: " + Request.Querystring _
, 0
This would be the sub called.
sub HandleErrors( connection, WebPagePath, GenericErrorMessage, DebugInfo, Severity)
//Check for vb errors
if Err.Number <> 0 Then
Session("WebPagePath") = WebPagePath
Session("SafeErrorMessage") = GenericErrorMessage 'Session("SafeErrorMessage") + "A connection was dropped while trying to complete sessions."
Session("DebugInfo") = DebugInfo ' Err.Description
Session("LineNo") = Err.Line
Session("StackTrace") = ""
Session("Severity") = Severity
response.redirect("Error.asp")
//error occurs
elseif connection.Errors.count <> 0 then
response.write("a database error occurred.")
// Store safe error message / # in session
Session("WebPagePath") = WebPagePath
Session("SafeErrorMessage") = GenericErrorMessage 'Session("SafeErrorMessage") + "An error has occurred while trying to save sessions."
Session("DebugInfo") = DebugInfo '"Some extra added debug info from the webpage"
Session("LineNo") = 0
Session("StackTrace") = ""
Session("Severity") = Severity
Dim objError
for each objError in connection.Errors
// Store safe error number in session
Session("SafeErrorNumbers") = Session("SafeErrorNumbers") + objError.Description
if connection.Errors.Count > 1 then
Session("SafeErrorNumbers") = Session("SafeErrorNumbers") + "|"
end if
next
response.Redirect("Error.asp")
end if
Err.Clear
end sub
To display the Error line number:
set objError = Server.GetLastError()
strErrorLine = objError.Line
Here are a couple threads on using Err.line:
http://www.daniweb.com/web-development/asp/threads/11615
http://www.sitepoint.com/forums/showthread.php?279612-ASP-Error-Handling.-Err.Line-weird-behavior
I can't explain why you are getting the results you are. I can tell you that if your code reachs a line that contains Response.Redirect that redirect will happen regardless of whether its a in a Sub procdure or not.
I would make this suggestion. Stop using using On Error Resume Next. It is very painful way to deal with exceptions.
Instead change HandleErrors into GenerateConnectionError. Its job would be to compose error source and description strings and deliberately call Err.Raise with a user define error number (I tend to use 1001).
Now your Error.asp should be installed in the root of your application as the handler for the 500.100 http status code. When a script error occurs IIS will look to the current error pages collection for the location to determine what to do. You will have set this to execute a URL and specified your Error.asp as the URL.
When Error.asp is executed it will find details about the page being requested from QueryString. Here you can also use Server.GetLastError to get an ASPError object from which you can get other details about the error.
Using this approach will detail with any script error without requiring the developer to remember to pepper their code with HandleError code. The developer need on remember to call GenerateConnectionError when performing code that is using an ADODB.Connection and even then you could probably abstract that inside an .asp include file.

Auto replacement of subject line in inbound Outlook emails

I need to replace the contents of the subject line of all incoming email (whatever it maybe ) with "EBIT Support" and that same mail then forwarded to the new and correct inbox- an ideas vey welcome!!
I assume you are looking for VBA code. Do you have any code written at all?
I have some stock event code that can be adapted for your purposes:
http://www.codeforexcelandoutlook.com/outlook-vba/stock-event-code/
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' (1) default Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
' (2) only act if it's a MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' (3) do something here
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub

Can't set Response object in ASP Classic

This line:
set Response = nothing
Fails with the error
"Microsoft VBScript runtime error '800a01b6'
Object doesn't support this property or method: 'Response' "
Now, I can think of any number of reasons why the engine might not want to let me do such a seemingly silly thing, but I'm not sure how a missing method could be stopping me.
EDIT: Here is an example of what I'd like to do with this.
class ResponseBufferEphemeron
private real_response_
private buffer_
private sub class_initialize
set real_response_ = Response
end sub
private sub class_terminate
set Response = real_response_
end sub
public function init (buf)
set buffer_ = buf
set init = me
end function
public function write (str)
buffer_.add str
end function
end class
function output_to (buf)
set output_to = (new ResponseBufferEphemeron).init(buf)
end function
dim buf: set buf = Str("Block output: ") ' My string class '
with output_to(buf)
Response.Write "Hello, World!"
end with
Response.Write buf ' => Block output: Hello, World! '
You can't set the Response to nothing.
The ASP Response object is used to send output to the user from the server.
What are you trying to do? If you're trying to end the Response to the user, use
Response.End
Well, I found the answer here: http://blogs.msdn.com/b/ericlippert/archive/2003/10/20/53248.aspx
So we special-cased VBScript so that it detects when it is compiling code that contains a call to Response.Write and there is a named item in the global namespace called Response that implements IResponse::Write. We generate an efficient early-bound call for this situation only.

Resources