Access Denied when checking file exists on sharepoint from vba - vba

I am trying to check if a file exists in SharePoint 2010 from Excel 2010 VBA. I took this code from another question.
Function checkFile(URLStr As String) As Boolean
Dim oHttpRequest As Object
Set oHttpRequest = New MSXML2.XMLHTTP60
With oHttpRequest
.Open "GET", URLStr, False
.setRequestHeader "Cache-Control", "no-cache"
.setRequestHeader "Pragma", "no-cache"
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
.send
End With
If oHttpRequest.Status = 200 Then
checkFile = True
Else
checkFile = False
End If
End Function
When I do so, vba is throwing an error: 'Access Denied Error for this object'
It fails on the line .send
I figured out that the error code is -2147024891.
I checked the Sharepoint permissions and they should be fine.

My URL with http, but access to sharepoint is granted with https only (at lest at a certain version). Changing the URL solved the access issues.

Function checkFile( URLStr As String) As Boolean
Dim oHttpRequest As Object
Dim GetResult As Integer
Set oHttpRequest = New MSXML2.XMLHTTP60
With oHttpRequest
.Open "GET", URLStr, False
.setRequestHeader "Cache-Control", "no-cache"
.setRequestHeader "Pragma", "no-cache"
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
End With
On Error GoTo HttpError
oHttpRequest.send '!!!!!!here code stops!!!!!!!
HttpError:
GetResult = 00
GetResult = oHttpRequest.Status
If GetResult = 200 Then
checkFile = True
Else
checkFile = False
End If
End Function

You need to define the authentication user info.
oHttp.SetRequestHeader "Authorization", "Basic " + _
Base64Encode(authUser + ":" + authPass)
Here is some info
http://ramblings.mcpher.com/Home/excelquirks/snippets/basicauth
How to pass authentication credentials in VBA

Related

Authorization data saved in xmlhttprequest with VBA

I am calling a Webservice with basic authentication with VBA. The problem I have is that the user/password is stored after the first successful call. That means I can put wrong user/password in the next calls and it works just the same.
Set objRequest = CreateObject("MSXML2.XMLHTTP")
blnAsync = True
With objRequest
.Open "GET", strUrl, blnAsync
.setRequestHeader "Authorization", "Basic " + EncodeBase64(user + ":" + passw)
.Send
'spin wheels whilst waiting for response
While objRequest.readyState <> 4
DoEvents
Wend
strResponse = .responseText
End With
If I call the Webservice from browser it is the same. First time I need to login, next time it works without login. After I delete cache/cookies/history I need to login again.
My questions:
Where is this (cache?) data stored if I call from VBA and how to delete this?
How to prevent VBA from saving the authorization data?
I found the crucial hint to put user/password in the .Open-method here: VBA XMLHTTP disable authentication pop-up
That's how it works for me. The only thing I can't do now is encoding the user & password.
Dim objRequest As MSXML2.XMLHTTP30
Set objRequest = New MSXML2.XMLHTTP30
With objRequest
.Open "GET", strUrl, blnAsync, user, passw
.setRequestHeader "Cache-Control", "no-cache"
.setRequestHeader "Pragma", "no-cache"
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
While objRequest.readyState <> 4
DoEvents
Wend
strResponse = .responseText
End With
To stop the caching, you could try adding:
.setRequestHeader("Cache-Control", "no-cache");
.setRequestHeader("Pragma", "no-cache");
.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
See also VBA XMLHTTP clear authentication? for more information.

Access JIRA API from Excel with VBA-Web

I'm trying to access the JIRA API from Excel. Using the MSXML2.XMLHTTP.6.0 object works fine but using the WinHttp.WinHttpRequest.5.1 from the VBA-Web WebClient does not.
This works fine:
Function getJiraSessionId()
Set JiraAuth = CreateObject("MSXML2.XMLHTTP.6.0")
With JiraAuth
.Open "POST", "https://<our JIRA server>/tracker/rest/auth/1/session", False
.SetRequestHeader "Content-Type", "application/json"
.SetRequestHeader "Accept", "application/json"
.SetRequestHeader "User-Agent", "Jira-Automation"
.Send " {""username"" : ""...."", ""password"" : ""....""} "
sErg = .ResponseText
End With
...
End Function
This does not:
Function JiraLogin()
Dim JiraClient As New WebClient
JiraClient.BaseUrl = "https://<our JIRA server>/tracker/"
JiraClient.Insecure = True
JiraClient.TimeoutMs = 50000
Dim Abruf As New WebRequest
Abruf.Resource = "rest/auth/1/session"
Abruf.Method = WebMethod.HttpPost
Abruf.Format = WebFormat.Json
Abruf.UserAgent = "Jira-Automation"
Set Body = New Dictionary
Body.Add "username", "...."
Body.Add "password", "...."
Set Abruf.Body = Body
Dim Response As WebResponse
Set Response = JiraClient.Execute(Abruf)
...
End Function
The error message is:
ERROR - WebClient.Execute: -2147210493 (11011 / 80042b03), An error occurred during execute
-2147012739 (80072f7d): Im Support des sicheren Channels ist ein Fehler aufgetreten
I want to use VBA-Web because of its great tools but I can't. Any idea what is wrong? Thanks, Manfred.

VBA XMLHTTP disable authentication pop-up

With reference to this question VBA XMLHTTP clear authentication? I am also trying to pass basic authentication in VBA. It works perfectly.
My only concern is login pop up which comes up whenever a wrong userid or password is sent in request. Is there a way to disable this and send a message box to user from VBA itself telling him about authentication failure?
Update
VBA code:
Dim objHTTP As New MSXML2.XMLHTTP60
With objHTTP
.Open "GET", UrlUserService, False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Cache-Control", "no-cache"
.setRequestHeader "Authorization", "Basic " + Base64Encode(userName + ":" + userPwd)
.setRequestHeader "Pragma", "no-cache"
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
.send ""
response = .Status
End With
Popup
Use Msxml2.XMLHTTP.6.0 protocol and pass the credentials as part of request
.Open "GET", pUrl, false, "pUsername", "pPassword"

How to deal with "Operation aborted" error when sending list update via Sharepoint REST?

I'm trying to build a VBA function that will update a value in a Sharepoint list:
Sub testUpdate()
Dim XmlHttp As MSXML2.XMLHTTP60
Dim result As String
Dim url As String
Dim body As String
Dim RequestDigest As String
Set XmlHttp = New MSXML2.XMLHTTP60
url = "https://sps.utility.xyz.com/sites/xyz/_api/web/lists/GetByTitle('REST Test List')/items(1)"
RequestDigest = GetDigest("https://sps.utility.xyz.com/sites/xyz")
body = "{ '__metadata': { 'type': 'SP.Data.REST_x0020_Test_x0020_ListListItem' }, 'Title': 'updating item with new title'}"
XmlHttp.Open "POST", url, False
XmlHttp.setRequestHeader "IF-MATCH", "*"
XmlHttp.setRequestHeader "accept", "application/json;odata=verbose"
XmlHttp.setRequestHeader "content-type", "application/json;odata=verbose"
XmlHttp.setRequestHeader "X-Http-Method", "MERGE"
XmlHttp.setRequestHeader "X-RequestDigest", RequestDigest
XmlHttp.setRequestHeader "Content-Length", Len(body)
XmlHttp.Send body
result = XmlHttp.responseText
End Sub
Function GetDigest(url As String)
Dim oHttp As New MSXML2.XMLHTTP60
Dim s As String
Dim l1 As Long
Dim l2 As Long
With oHttp
.Open "POST", url + "/_api/contextinfo", False
.setRequestHeader "content-type", "application/json;odata=verbose"
.Send ""
End With
s = oHttp.responseText
l1 = InStr(1, s, "FormDigestValue")
If l1 > 10 Then
l1 = l1 + 16
l2 = InStr(l1, s, "</d:FormDigestValue")
End If
If l2 > 10 Then GetDigest = Mid$(s, l1, l2 - l1)
Set oHttp = Nothing
End Function
But when testUpdate gets to the line:
XmlHttp.Send body
it throws this error:
Run-time error '-2147467260 (80004004)':
Operation aborted
Despite the error, the update succeeds--the list item's Title value changes.
Is it safe for me to simply handle this exception and bypass the error, or is it indicating that there is a real problem that I need to resolve?
The api call requires authentication. I managed to use WinHTTP to authenticate the request based on the current user, I am assuming that they have access in the below. I get a 204 response and my list item updates correctly. (the iteration is because I was testing performance and can be removed).
Tools>references>Microsoft WinHttp Services Version 5.1
Private Sub UpdateItem2(ID, strFormDigest As String, iteration)
Dim sUrl As String
sUrl ="https://123.Sharepoint.net/sites/123/_api/web/lists/getbytitle('MyDemoList')/items(" & ID & ")"
Dim oRequest As WinHttp.WinHttpRequest
Dim sResult As String
sEnv = "{ '__metadata': { 'type': 'SP.Data.MyDemoListListItem' }, 'Title': 'TEST" & iteration & "' }"
Set oRequest = New WinHttp.WinHttpRequest
With oRequest
.Open "POST", sUrl, True
.setRequestHeader "IF-MATCH", "*"
.setRequestHeader "X-HTTP-Method", "MERGE"
.setRequestHeader "accept", "application/json;odata=verbose"
.setRequestHeader "X-RequestDigest", strFormDigest
.setRequestHeader "content-type", "application/json;odata=verbose"
.SetAutoLogonPolicy AutoLogonPolicy_Always
.send sEnv
.waitForResponse
End With
End Sub

"Run-Time error '13': Type mismatch" in VBA for JSON extraction with JIRA API

New to the community here. I've done a decent amount of programming but I'm completely new to VBA. Never used it before until now and I was tasked with extracting JSON data from a Jira API into an Excel spreadsheet. I keep getting the error "Run-Time error '13': Type mismatch" and I'm not sure why. I know the error has to do with passing in incorrect types but I've tried changing the Json variable to a String with no success. Anyone have any ideas? Thanks!
By the way, this is just a trial Jira instance for testing the API functionality.
Sub test()
'Authenticate the user
Dim response As String
With CreateObject("Microsoft.XMLHTTP")
.Open "POST", "https://apitestsite.atlassian.net/rest/auth/1/session", False, "admin", "password"
.setRequestHeader "X-Atlassian-Token:", "nocheck"
.Send
response = .responseText
End With
'Query through JSON
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", "https://apitestsite.atlassian.net/rest/api/2/issue/CC-1", False, "admin", "password"
MyRequest.Send
Dim Json As Object
Set Json = JsonConverter.ParseJson(MyRequest.responseText)
MsgBox Json("fields")("summary")
End Sub
UPDATE: This is where I am at right now. Updated the code for the authentication and now no errors display from the compiler. Here is the JSONConverter class I am using: github.com/VBA-tools/VBA-JSON/blob/master/JsonConverter.bas. The issue now is that the returned JSON string says, "{"errorMessages":["Issue does not exist or you do not have permission to see it."],"errors":{}}". So I am able to connect to Jira just fine and return the JSON as a string, it's just that Jira is rejecting my credentials :/
Private JiraService As New MSXML2.XMLHTTP60
Private JiraAuth As New MSXML2.XMLHTTP60
Sub test()
'Authenticate the user
With JiraAuth
.Open "POST", "https://apitestsite.atlassian.net/rest/auth/1/session", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "X-Atlassian-Token:", "nocheck"
.send " {""username"" : ""admin"", ""password"" : ""password""}"""
sErg = .responseText
sCookie = "JSESSIONID=" & Mid(sErg, 42, 32) & "; Path=/Jira" '*** Extract the Session-ID
End With
With JiraService
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
MyRequest.Open "GET", "https://apitestsite.atlassian.net/rest/api/2/issue/CC-1", False
MyRequest.setRequestHeader "Content-Type", "application/json"
MyRequest.setRequestHeader "Accept", "application/json"
MyRequest.setRequestHeader "Set-Cookie", sCookie '*** see Create a "Cookie"
MyRequest.send
Dim Json As String
Json = MyRequest.responseText
MsgBox Json
End With
End Sub
This seems to return a valid JSON from the API, which is parseable from the Jsonconverter module.
You were using MyRequest object as possibly the wrong type of object. Elsewhere, you're relying on the MSXML2.XMLHTTP60 class.
Set MyRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
So I removed the MyRequest and just worked with the JiraService object instead. You had a With JiraService block but you weren't actually using that object at all, you were executing against the WinHttpRequest object within that block.
I also declared all variables, and modified the auth string to use Const strings defined at top of module for user/password.
Option Explicit
Private JiraService As New MSXML2.XMLHTTP60
Private JiraAuth As New MSXML2.XMLHTTP60
Const user As String = "jiratestemail82#gmail.com"
Const pw As String = "password"
Sub test()
Dim sErg$, sCookie$, Json$
'Authenticate the user
With JiraAuth
.Open "POST", "https://apitestsite.atlassian.net/rest/auth/1/session", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "X-Atlassian-Token:", "nocheck"
.send " {""username"" : """ & user & """, ""password"" : """ & pw & """}"""
sErg = .responseText
sCookie = "JSESSIONID=" & Mid(sErg, 42, 32) & "; Path=/Jira" '*** Extract the Session-ID
End With
With JiraService
.Open "GET", "https://apitestsite.atlassian.net/rest/api/2/issue/CC-1", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Set-Cookie", sCookie '*** see Create a "Cookie"
.send
Json = .responseText
End With
Dim j As Object
Set j = JsonConverter.ParseJson(Json)
MsgBox j("fields")("summary")
End Sub