Connect to web service in MS Access with VBA - web-services

Is it possible to connect to a web service (for example send a HTTP Request) via VBA in Microsoft Access?
For example, the user clicks a button on a form, then a HTTP Request is sent to a web service that responds with OK.
Has anyone done this before?
Note: VBA, not VB.NET.

This is code I've used quite successfully with Access 2003. It's from the interwebs, copied and re-copied ages ago. It creates a XMLHttpRequest Object, sends an HTTP GET request, and returns the results as a string.
Public Function http_Resp(ByVal sReq As String) As String
Dim byteData() As Byte
Dim XMLHTTP As Object
Set XMLHTTP = CreateObject("MSXML2.XMLHTTP")
XMLHTTP.Open "GET", sReq, False
XMLHTTP.send
byteData = XMLHTTP.responseBody
Set XMLHTTP = Nothing
http_Resp = StrConv(byteData, vbUnicode)
End Function
sReq is the URL; the function returns the response. You may need to make sure ActiveX Data Objects are enabled under your References (in the VBA editor, go to Tools > References).

This is the code , which I used. You need to first reference Microsoft XML V6 for this code to work.
Public Sub GetPerson()
'For API
Dim reader As New XMLHTTP60
reader.Open "GET", "www.exmple.com/users/5428a72c86abcdee98b7e359", False
reader.setRequestHeader "Accept", "application/json"
reader.send
Do Until reader.ReadyState = 4
DoEvents
Loop
If reader.Status = 200 Then
Msgbox (reader.responseText)
Else
MsgBox "Unable to import data."
End If
End Sub

I have used the "Microsoft Office 2003 Web Services Toolkit 2.01" toolkit (available here) on a few projects. It worked pretty well for me, although I also wrote the web services it was talking to, so I had the luxury of being able to fiddle with both ends of the process when getting it to actually work. :)
In fact, I just upgraded one of those apps from Access_2003 to Access_2010 and the SOAP client part of the app continued to work without modification. However, I did encounter one wrinkle during pre-deployment testing:
My app would not compile on a 64-bit machine running 32-bit Office_2010 because it did not like the early binding of the SoapClient30 object. When I switched to using late binding for that object the code would compile, but it did not work. So, for that particular app I had to add a restriction that 64-bit machines needed to be running 64-bit Office.
Also, be aware that Microsoft's official position is that "All SOAP Toolkits have been replaced by the Microsoft .NET Framework." (ref. here).

Related

Open a c++ application installed on computer with a custom url in browser [duplicate]

How do i set up a custom protocol handler in chrome? Something like:
myprotocol://testfile
I would need this to send a request to http://example.com?query=testfile, then send the httpresponse to my extension.
The following method registers an application to a URI Scheme. So, you can use mycustproto: in your HTML code to trigger a local application. It works on a Google Chrome Version 51.0.2704.79 m (64-bit).
I mainly used this method for printing document silently without the print dialog popping up. The result is pretty good and is a seamless solution to integrate the external application with the browser.
HTML code (simple):
Click Me
HTML code (alternative):
<input id="DealerName" />
<button id="PrintBtn"></button>
$('#PrintBtn').on('click', function(event){
event.preventDefault();
window.location.href = 'mycustproto:dealer ' + $('#DealerName').val();
});
URI Scheme will look like this:
You can create the URI Scheme manually in registry, or run the "mycustproto.reg" file (see below).
HKEY_CURRENT_USER\Software\Classes
mycustproto
(Default) = "URL:MyCustProto Protocol"
URL Protocol = ""
DefaultIcon
(Default) = "myprogram.exe,1"
shell
open
command
(Default) = "C:\Program Files\MyProgram\myprogram.exe" "%1"
mycustproto.reg example:
Windows Registry Editor Version 5.00
[HKEY_CURRENT_USER\Software\Classes\mycustproto]
"URL Protocol"="\"\""
#="\"URL:MyCustProto Protocol\""
[HKEY_CURRENT_USER\Software\Classes\mycustproto\DefaultIcon]
#="\"mycustproto.exe,1\""
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell]
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell\open]
[HKEY_CURRENT_USER\Software\Classes\mycustproto\shell\open\command]
#="\"C:\\Program Files\\MyProgram\\myprogram.exe\" \"%1\""
C# console application - myprogram.exe:
using System;
using System.Collections.Generic;
using System.Text;
namespace myprogram
{
class Program
{
static string ProcessInput(string s)
{
// TODO Verify and validate the input
// string as appropriate for your application.
return s;
}
static void Main(string[] args)
{
Console.WriteLine("Raw command-line: \n\t" + Environment.CommandLine);
Console.WriteLine("\n\nArguments:\n");
foreach (string s in args)
{
Console.WriteLine("\t" + ProcessInput(s));
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}
Try to run the program first to make sure the program has been placed in the correct path:
cmd> "C:\Program Files\MyProgram\myprogram.exe" "mycustproto:Hello World"
Click the link on your HTML page:
You will see a warning window popup for the first time.
To reset the external protocol handler setting in Chrome:
If you have ever accepted the custom protocol in Chrome and would like to reset the setting, do this (currently, there is no UI in Chrome to change the setting):
Edit "Local State" this file under this path:
C:\Users\Username\AppData\Local\Google\Chrome\User Data\
or Simply go to:
%USERPROFILE%\AppData\Local\Google\Chrome\User Data\
Then, search for this string: protocol_handler
You will see the custom protocol from there.
Note: Please close your Google Chrome before editing the file. Otherwise, the change you have made will be overwritten by Chrome.
Reference:
https://msdn.microsoft.com/en-us/library/aa767914(v=vs.85).aspx
Chrome 13 now supports the navigator.registerProtocolHandler API. For example,
navigator.registerProtocolHandler(
'web+custom', 'http://example.com/rph?q=%s', 'My App');
Note that your protocol name has to start with web+, with a few exceptions for common ones (like mailto, etc). For more details, see: http://updates.html5rocks.com/2011/06/Registering-a-custom-protocol-handler
This question is old now, but there's been a recent update to Chrome (at least where packaged apps are concerned)...
http://developer.chrome.com/apps/manifest/url_handlers
and
https://github.com/GoogleChrome/chrome-extensions-samples/blob/e716678b67fd30a5876a552b9665e9f847d6d84b/apps/samples/url-handler/README.md
It allows you to register a handler for a URL (as long as you own it). Sadly no myprotocol:// but at least you can do http://myprotocol.mysite.com and can create a webpage there that points people to the app in the app store.
This is how I did it. Your app would need to install a few reg keys on installation, then in any browser you can just link to foo:\anythingHere.txt and it will open your app and pass it that value.
This is not my code, just something I found on the web when searching the same question. Just change all "foo" in the text below to the protocol name you want and change the path to your exe as well.
(put this in to a text file as save as foo.reg on your desktop, then double click it to install the keys)
-----Below this line goes into the .reg file (NOT including this line)------
REGEDIT4
[HKEY_CLASSES_ROOT\foo]
#="URL:foo Protocol"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\foo\shell]
[HKEY_CLASSES_ROOT\foo\shell\open]
[HKEY_CLASSES_ROOT\foo\shell\open\command]
#="\"C:\\Program Files (x86)\\Notepad++\\notepad++.exe\" \"%1\""
Not sure whether this is the right place for my answer, but as I found very few helpful threads and this was one of them, I am posting my solution here.
Problem: I wanted Linux Mint 19.2 Cinnamon to open Evolution when clicking on mailto links in Chromium. Gmail was registered as default handler in chrome://settings/handlers and I could not choose any other handler.
Solution:
Use the xdg-settings in the console
xdg-settings set default-url-scheme-handler mailto org.gnome.Evolution.desktop
Solution was found here https://alt.os.linux.ubuntu.narkive.com/U3Gy7inF/kubuntu-mailto-links-in-chrome-doesn-t-open-evolution and adapted for my case.
I've found the solution by Jun Hsieh and MuffinMan generally works when it comes to clicking links on pages in Chrome or pasting into the URL bar, but it doesn't seem to work in a specific case of passing the string on the command line.
For example, both of the following commands open a blank Chrome window which then does nothing.
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "foo://C:/test.txt"
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --new-window "foo://C:/test.txt"
For comparison, feeding Chrome an http or https URL with either of these commands causes the web page to be opened.
This became apparent because one of our customers reported that clicking links for our product from a PDF being displayed within Adobe Reader fails to invoke our product when Chrome is the default browser. (It works fine with MSIE and Firefox as default, but not when either Chrome or Edge are default.)
I'm guessing that instead of just telling Windows to invoke the URL and letting Windows figure things out, the Adobe product is finding the default browser, which is Chrome in this case, and then passing the URL on the command line.
I'd be interested if anyone knows of Chrome security or other settings which might be relevant here so that Chrome will fully handle a protocol handler, even if it's provided via the command line. I've been looking but so far haven't found anything.
I've been testing this against Chrome 88.0.4324.182.
open
C:\Users\<Username>\AppData\Local\Google\Chrome\User Data\Default
open Preferences then search for excluded_schemes you will find it in 'protocol_handler' delete this excluded scheme(s) to reset chrome to open url with default application

WinMo > ASMX WebException - how to get details?

Okay, we've got an application which consists of a website hosting several ASMX webservices, and a handheld application running on WinMo 6.1 which calls the webservices.
Been developing in the office, everything works perfect.
Now we've gone to install it at the client's and we got all the servers set up and the handhelds installed. However the handhelds are now no longer able to connect to the webservice.
I added in extra code in my error handler to specifically trap WebException exceptions and handle them differently in the logging to put out extra information (.Status and .Response).
I am getting out the status, which is returning a [7], or ProtocolError. However when I try to read out the ResponseStream (using WebException.Response.GetResponseStream), it is returning a stream with CanRead set to False, and I thus am unable to get any further details of what is going wrong.
So I guess there are two things I am asking for help with...
a) Any help with trying to get more information out of the WebException?
b) What could be causing a ProtocolError exception?
Things get extra complicated by the fact that the client has a full-blown log-in-enabled proxy setup going on-site. This was stopping all access to the website initially, even from a browser. So we entered in the login details in the network connection for HTTP on the WinMo device. Now it can get to websites fine.
In fact, I can even pull up the webservice fine and call the methods from the browser (PocketIE). So I know the device is able to see the webservices okay via HTTP. But when trying to call them from the .NET app, it throws ProtocolError [7].
Here is my code which is logging the exception and failing to read out the Response from the WebException.
Public Sub LogEx(ByVal ex As Exception)
Try
Dim fn As String = Path.Combine(ini.CorePath, "error.log")
Dim t = File.AppendText(fn)
t.AutoFlush = True
t.WriteLine(<s>===== <%= Format(GetDateTime(), "MM/dd/yyyy HH:mm:ss") %> =====<%= vbCrLf %><%= ex.Message %></s>.Value)
t.WriteLine()
t.WriteLine(ex.ToString)
t.WriteLine()
If TypeOf ex Is WebException Then
With CType(ex, WebException)
t.WriteLine("STATUS: " & .Status.ToString & " (" & Val(.Status) & ")")
t.WriteLine("RESPONSE:" & vbCrLf & StreamToString(.Response.GetResponseStream()))
End With
End If
t.WriteLine("=".Repeat(50))
t.WriteLine()
t.Close()
Catch ix As Exception : Alert(ix) : End Try
End Sub
Private Function StreamToString(ByVal s As IO.Stream) As String
If s Is Nothing Then Return "No response found."
// THIS IS THE CASE BEING EXECUTED
If Not s.CanRead Then Return "Unreadable response found."
Dim rv As String = String.Empty, bytes As Long, buffer(4096) As Byte
Using mem As New MemoryStream()
Do While True
bytes = s.Read(buffer, 0, buffer.Length)
mem.Write(buffer, 0, bytes)
If bytes = 0 Then Exit Do
Loop
mem.Position = 0
ReDim buffer(mem.Length)
mem.Read(buffer, 0, mem.Length)
mem.Seek(0, SeekOrigin.Begin)
rv = New StreamReader(mem).ReadToEnd()
mem.Close()
End Using
Return rv.NullOf("Empty response found.")
End Function
Thanks in advance!
I was not able to get any more information out of the WebException class. For some reason that GetResponseStream always returns an unreadable stream.
I was able to narrow the problem down to proxy authentication though by writing a separate little program which simply tried to request a web page and read the response and put it into a textbox.
This program returned a response of proxy authentication required. I find this really weird though because I put the proxy information into the network connection settings on my device. I would've though this would apply to all network traffic going out on that connection; apparently it only applies to traffic through the browser, not application requests. Odd.

SharePoint Web Services. Using UserPofileService.GetUserProfileByName. After SP upgrade... failing

The below web services code has worked properly for me for over a year. We have updated our SharePoint servers, and now the below code throws an exception (at the bottom line of code) "Object reference not set to an instance of an object"
UserProfileWS.UserProfileService userProfileService = new UserProfileWS.UserProfileService();
userProfileService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
string serviceloc = "/_vti_bin/UserProfileService.asmx";
userProfileService.Url = _webUrl + serviceloc;
UserProfileWS.PropertyData[] info = userProfileService.GetUserProfileByName(null);
EDIT: The service is still there. I browse http:///_vti_bin/UserProfileService.asmx, and the information for the service is still there, including the full description of the GetUserProfileByName call.
EDIT2: This does appear to be due to a change in SharePoint. I loaded a previous version of my software (known to be working), and it exhibits the same erroneous behavior.
try
UserProfileWS.PropertyData[] info = userProfileService.GetUserProfileByName(userName);
as specified http://msdn.microsoft.com/en-us/library/microsoft.office.server.userprofiles.userprofileservice.getuserprofilebyname(v=office.12).aspx
When was the farm updated? Was the WSS updates installed before the MOSS updates? If you believe it to be a problem as a result of infrastructure updates, build a test farm and try the code against pre-updates (go back as far as a year ago to start off).

Trouble Getting Data from a Webservice using Qooxdoo

My capstone team has decided to use Qooxdoo as the front end for our project. We're developing apps for OpenFlow controllers using NOX, so we're using the NOX webservices framework. I'm having trouble getting data from the service; I know the service is running because if I go to the URL using Firefox the right data shows up. Here's the relevant portion of my code:
var req = new qx.io.remote.Request("http://localhost/ws.v1/hello/world",
"GET", "text/plain");
req.addListener("complete", function(e) {
this.debug(e.getContent());
});
var get = new qx.ui.form.Button("get");
get.addListener("execute", function() {
alert("The button has been pressed");
req.send();
}, this);
form.addButton(get);
In the firebug console I get this message after I click through the alert:
008402 qx.io.remote.Exchange: Unknown status code: 0 (4)
And if I press the Get button again I get this error:
027033 qx.io.remote.transport.XmlHttp[56]: Failed with exception: [Exception... "Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIXMLHttpRequest.open]" nsresult: "0x80070057 (NS_ERROR_ILLEGAL_VALUE)" location: "JS frame :: file:///home/user/qooxdoo-1.0-sdk/framework/source/class/qx/io/remote/transport/XmlHttp.js :: anonymous :: line 279" data: no]
I've also looked at the Twitter Client tutorial, however the "dataChange" event I set up in place of the "tweetsChanged" event never fired. Any help is appreciated, thank you.
This sound like a cross domain request issue. qx.io.remote.Request uses XHR for transporting the data which may not work in every case due to the browser restriction. Switching the crossDomain flag on the request to true will change from XHR to a dynamically inserted script tag doesn't have the cross domain restriction (but other restrictions).
req.setCrossDomain(true);
Maybe that solves your problem.
Additionally, you can take a look at the documentation of the remote package to get some further details on cross domain requests:
http://demo.qooxdoo.org/current/apiviewer/#qx.io.remote
Also take care not to use a request object twice. The only work once.

"Class does not support automation" error when i call Request.ServerVariables("remote_host")

I'm in the process of writing a basic cookie for an ecommerce site which is going to store the user's IP among other details.
We'll then record the pages they view in the database and pull out a list of recently viewed pages.
However i'm having an issue with the following code.
dim caller
caller = Response.Cookies("caller")
if caller = "" then
caller = Request.ServerVariables("remote_host")
end if
On running this, i get the following error message.
"Sun ONE ASP VBScript runtime (0x800A01AE)
Class does not support automation"
Any ideas? Google has nothing obvious.
Should be Request.Cookies when checking the value.:
dim caller
caller = Request.Cookies("caller")
if caller = "" then
caller = Request.ServerVariables("remote_host")
end if