Get data from SharePoint Online List using VB.NET - vb.net

I'm developing a solution to get data from SharePoint Online List, but when I try to retrieve and execute the query, do a error. The error is.
System.Net.WebException: 'The remote server returned an error: (403) Forbidden.'
Im using 4 textboxs (URL, User, Password, NameList) and a Datagridview.
Using context As ClientContext = New ClientContext(TextBox1.Text.Trim())
context.AuthenticationMode = ClientAuthenticationMode.[Default]
context.Credentials = New NetworkCredential(TextBoxName.Text.Trim(), TextBoxPassword.Text.Trim(), "https://example.sharepoint.com/sites/SPSite/")
Dim webObj As Web = context.Web
Dim listObj As List = webObj.Lists.GetByTitle(TextBoxLista.Text.Trim())
Dim cqObj As CamlQuery = CamlQuery.CreateAllItemsQuery(100)
Dim collObj As ListItemCollection = listObj.GetItems(cqObj)
context.Load(collObj)
context.ExecuteQuery() 'Line whit error
End Using
Could you help me to know the reason for the error and how to solve it?
Thank you in advance.
Regards.

This is the code whit the solution.
Thank you.
Imports Microsoft.SharePoint.Client
Imports Microsoft.SharePoint
Imports System.Security
Imports System.Net
Public Class Form4
Dim siteUrl As String = "https://namedomain.sharepoint.com/sites/TaskSP/"
'namedomain is the name of the site domain, TaskSP is the name site.
Dim context As New ClientContext(siteUrl)
Dim web As Web
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim userNameSP As String = TextBox1.Text
'Textbox1.text is the mail account to access site.
Dim password As String = TextBox2.Text
'Textbox2.text is the password of your mail account to access site.
Dim secureString As SecureString = New NetworkCredential("", password).SecurePassword
Dim cred = New SharePointOnlineCredentials(userNameSP, secureString)
Dim clientContext As New ClientContext(siteUrl)
clientContext.Credentials = cred
Dim web As Web = clientContext.Web
Dim oWebsite As Web = clientContext.Web
Dim collList As ListCollection = oWebsite.Lists
Dim oList As List = collList.GetByTitle("TestList")
'TestList is the name of the list you want to query
clientContext.Load(oList)
clientContext.ExecuteQuery()
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End Sub
End Class
I hope this is useful if you need it.
Regards.

Related

400 bad request when querying microsoft graph with http post

I've been doing some testing with Microsoft Graph and I seem to have hit a brick wall; Wondering if anyone can give me a steer in the right direction.
The following code is from my test app (vb)...
Imports System.Net
Imports System.Text
Imports System.IO
Imports Newtonsoft.Json.Linq
Class MainWindow
Public Shared graph_url As String = "https://graph.microsoft.com/v1.0/"
Public Shared br As String = ControlChars.NewLine
Dim myscope As String = "https://graph.microsoft.com/.default"
Dim mysecret As String = "zzx...BX-"
Dim mytenantid As String = "7aa6d...d409199"
Dim myclientid As String = "4e37...5a59"
Dim myuri As String = "https://login.microsoftonline.com/" & mytenantid & "/oauth2/v2.0/token"
Dim mytoken As String = ""
Public Function HTTP_Post(ByVal url As String, ByVal postdata As String)
Try
Dim encoding As New UTF8Encoding
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
postReq.Headers.Add("Authorization", "Bearer " & mytoken)
postReq.Method = "POST"
postReq.PreAuthenticate = True
Dim postreqstream As Stream = postReq.GetRequestStream()
If Not postdata = Nothing Then
Dim byteData As Byte() = encoding.GetBytes(postdata)
postreqstream.Write(byteData, 0, byteData.Length)
End If
postreqstream.Close()
request_header.Text = postReq.Headers.ToString
Dim postresponse As HttpWebResponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
Dim response As String = postreqreader.ReadToEnd
Return (response)
Catch ex As Exception
user_results.Text = ex.Message.ToString
End Try
End Function
Public Function GetNewToken()
Console.WriteLine(myuri)
Dim post_data As String = "client_id=" & myclientid & "&client_secret=" & mysecret & "&scope=" & myscope & "&grant_type=client_credentials"
Dim token As String = HTTP_Post(myuri, post_data)
get_result.Text = JObject.Parse(token).SelectToken("access_token")
mytoken = JObject.Parse(token).SelectToken("access_token")
End Function
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
GetNewToken()
End Sub
Private Sub usrget_Copy_Click(sender As Object, e As RoutedEventArgs) Handles usrget_Copy.Click
Dim url As String = "https://graph.microsoft.com/v1.0/users/*{myUPN}*"
Dim post_data As String = Nothing
Dim return_data As String = HTTP_Post(url, post_data)
req_url.Text = url
End Sub
End Class
The GetNewToken() function works fine and I retrive a valid token without an issue.
When i try and use that token to query a user, i get 400 Bad request - no additional info as such; just that.
I've examined the headers of my POST request and tried it several different ways, but cannot seem to overcome this; As far as i can tell my request is formatted as specified in the documentation for Microsoft Graph.
Have also googled the hell out of this to see if there was something obvious or simple I have overlooked; I've seen a few posts on this topic where people suggested setting the Authorization header before anything else - I tried that and it made no difference.
A few people also suggected setting the Accept to 'application/json'; I also tried that and it made no difference.
I've outputted some of the details to the gui and grabbed a screenshot so you can see what I'm seeing...
Interestingly, If i try the 'Query users' before i grab a token, I get a 401 unauthorized which would suggest that the request itself is working correctly.
As i mentioned, this is a testing app whilst I get some functionality working (some data obscured for obvious reasons); I'm not concerned about the tidyness of code or anything like that at this point.
If anyone is able to help it would be very much appriciated.
Thanks in advance.

GetResponse not a member of WebRequest in UWP

I wrote a VB program to access information from the Web.
It works but when trying to do the same thing in UWP (Universal Windows) …
I get the following message:
"'GetResponse' is not a member of 'WebRequest'"
Here is the code I am using less the website info. How can this code be used in the Universal Windows Platform.
Imports System
Imports System.IO
Imports System.Net
Module Code
Sub SendWebRequest()
Dim MyWebRequest As WebRequest
Dim MyWebResponse As WebResponse
Dim SR As StreamReader
Dim ReadString As String
Dim MyCache As New CredentialCache()
Dim MyCredential As NetworkCredential = MyCache.GetCredential(New Uri("http://xxxxxx.com:xxxx"), "Basic")
If MyCredential Is Nothing Then
MyCache.Add(New Uri("http://http://xxxxxx.com:xxxx"), "Basic", New NetworkCredential("UserName", "UsePassWord"))
End If
MyWebRequest = WebRequest.Create("http://http://xxxxxx.com:xxxx/xxxx")
MyWebRequest.Credentials = myCache
MyWebResponse = MyWebRequest.GetResponse()
SR = New StreamReader(MyWebResponse.GetResponseStream)
Do
ReadString = SR.ReadLine
If InStr(ReadString, "Listen to the pronunciation of") Then
'Do Something
Exit Do
End If
Loop Until SR.EndOfStream
MyWebResponse.Close()
End Sub
End Module
I updated using adding Async and Await . . .
Run time issue at MyWebresponse = Await MyWebRequest.GetResponseAsync()
Exception User-Unandled: System.PlatformNotSupportedException: 'The value 'System.Net.CredentialCache' is not supported for property 'Credentials'.'
Async Sub SendWebRequest()
Dim MyWebRequest As WebRequest
Dim MyWebResponse As WebResponse
Dim SR As StreamReader
Dim ReadString As String
Dim MyCache As New CredentialCache()
Dim MyCredential As NetworkCredential = MyCache.GetCredential(New Uri("http://xxxxxx.com:xxxx"), "Basic")
If MyCredential Is Nothing Then
MyCache.Add(New Uri("http://http://xxxxxx.com:xxxx"), "Basic", New NetworkCredential("UserName", "UsePassWord"))
End If
MyWebRequest = WebRequest.Create("http://http://xxxxxx.org:xxxx/xxxx")
MyWebRequest.Credentials = myCache
MyWebResponse = Await MyWebRequest.GetResponseAsync()
SR = New StreamReader(MyWebResponse.GetResponseStream)
Do
ReadString = SR.ReadLine
If InStr(ReadString, "Listen to the pronunciation of") Then
'Do Something
Exit Do
End If
Loop Until SR.EndOfStream
MyWebResponse.Close()
End Sub
If someone can see what I am doing wrong above, I'd appreciate it.
In the mean time I'll try HttpClient as suggested by jmcilhinney
In theory, you should be able to change this:
Sub SendWebRequest()
to this
Async Sub SendWebRequest()
and this:
MyWebResponse = MyWebRequest.GetResponse()
to this:
MyWebResponse = Await MyWebRequest.GetResponseAsync()
This thread indicates that that might not work though. It does suggest an HttpClient as an alternative though, which would mean code something like this:
Dim client As New HttpClient
Dim response = Await client.GetAsync(New Uri("URL here"))
If response.IsSuccessStatusCode Then
Dim data = Await response.Content.ReadAsStringAsync()
For Each line In data.Split({vbLf, vbCrLf}, StringSplitOptions.RemoveEmptyEntries)
'Use line here.
Next
End If
Note that I'm not 100% sure whether those 'vb' constants would work in UWP but I used them here for simplicity.
The following does what I need in UWP. Send a Web Request and monitor the return.
...Thanks jmcilhinney for your help
Imports System.Net
Imports System.Net.Http
Imports System.Text
Module Code
Async Sub SendWebRequest()
Dim client As New HttpClient
Dim byteArray = Encoding.ASCII.GetBytes("UserName:PassWord")
client.DefaultRequestHeaders.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray))
Dim response = Await client.GetAsync(New Uri("http://xxxxx.xxxxxx.org:####/xxxxx"))
If response.IsSuccessStatusCode Then
Dim data = Await response.Content.ReadAsStringAsync()
For Each line In data.Split({vbLf, vbCrLf}, StringSplitOptions.RemoveEmptyEntries)
'Use line here.
Next
End If
End Sub
End Module

VB.NET - Salesforce POST Request returns 400 Bad Request Error

NOTE: I've never written vb.net code before this. I've googled for a solution but did not find anything that worked.
I'm trying to get access token from Salesforce. Below code worked just yesterday. And I have no idea why it is not working today. I've tried adding content-type as application/x-www-form-urlencoded but it did not work either. When I use curl I'm able to get access token. Also I'm able to get access token using advanced rest client in google chrome. Any ideas why it is returning 400 Bad Request unknown error retry your request?
Imports System.Collections.Specialized
Imports System.Net
Imports System.Text
Module Module1
Sub Main()
Dim clientId As String = "clientId"
Dim clientSecret As String = "clientSecret"
Dim redirectUri As String = "https://test.salesforce.com"
Dim environment As String = "https://test.salesforce.com"
Dim tokenUrl As String = ""
Dim username As String = "username#salesforce.com"
Dim password As String = "passwordtoken"
Dim accessToken As String = ""
Dim instanceUrl As String = ""
Console.WriteLine("Getting a token")
tokenUrl = environment + "/services/oauth2/token"
Dim request As WebRequest = WebRequest.Create(tokenUrl)
Dim values As NameValueCollection = New NameValueCollection()
values.Add("grant_type", "password")
values.Add("client_id", clientId)
values.Add("client_secret", clientSecret)
values.Add("redirect_uri", redirectUri)
values.Add("username", username)
values.Add("password", password)
request.Method = "POST"
Try
Dim client = New WebClient()
Dim responseBytes As Byte() = client.UploadValues(tokenUrl, "POST", values)
Dim response As String = Encoding.UTF8.GetString(responseBytes)
Console.WriteLine(response)
Console.ReadKey()
Catch ex As Exception
Console.WriteLine(ex.Message)
Console.WriteLine("Press any key to close")
Console.ReadKey()
End Try
End Sub
End Module
Well, appearently problem was about TLS version mismatch. All Salesforce sandboxes refuse TLS 1.0 connections. Our vb.net test code was using TLS 1.0 thus returning an error. It would be great if Salesforce would return better error code.
All I needed to do was add a line of code on top of the code block:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11

Authenticating to Web Service VB.Net

Hi I am trying to Authenticate to my web service and missing something..
My Service reference is called - MBSDKServiceLD
My Web Reference is called - LANDeskMBSDK
I have these connected in Visual Studio 2013 And are resolving methods in the code
Here is my code for the authentication but its not complete..
Option Explicit On
Imports System.Net
Dim objFSO As Object
Dim objExec As Object
Dim objNetwork As Object
Dim strComputer As String
Dim strUser As String
Dim User As String
Dim Password As String
Dim Domain As String
Dim URL As String
Dim Cred As String
Dim strTaskName As String
Dim strPackageName As String
Dim strDeliveryMethod As String
Dim strCustomGroup As String
Dim boolStartNow As Boolean
Dim WakeUpMachines As Boolean
Dim boolCommonTask As Boolean
Dim strAutoSync As String
Dim TaskID As String
Dim strConnection As New System.Data.SqlClient.SqlConnection
Dim LDWebService
Dim intTaskID As String
Dim LDService As Object
Dim strDeviceName As String
Sub RunLANDeskTask(ByVal sender As Object, ByVal LDService As MBSDKServiceLD.MBSDKSoap)
End Sub
Sub CreateTask
User = "username1"
Password = "password1"
Domain = "domain1"
URL = "http://myserver/MBSDKService/MsgSDK.asmx?WSDL"
Dim MyCredentails As New System.Net.CredentialCache()
Dim NetCred As New System.Net.NetworkCredential(User, Password, Domain)
MyCredentails.Add(New Uri(URL), "Basic", NetCred)
strPackageName = "Adobe Acrobat XI PRO"
strDeliveryMethod = "Standard push distribution"
Dim strTargetDevice As String
strTargetDevice = Nothing
strTaskName = strPackageName & " - " & DateTime.Now & " -Provisioning Task for" & " " & strComputer
Try
RunLANDeskTask(LANDeskMBSDK, LDService.CreateTask(strTaskName, strDeliveryMethod, strPackageName, False, False, strAutoSync).TaskID)
Catch ex As Exception
MsgBox("Error creating task")
End Try
End Sub
What comes after this part or have i got this totally wrong?
When I type LDService. I see all the methods so I am connecting to the reference in VS but not authenticating.
It should really be as simple as this (sorry it's in c#):
MyWebService svc = new MyWebService();
svc.Credentials = new System.Net.NetworkCredential(UserID, pwd);
bool result = svc.MyWebMethod();
The following might be helpful:
This is quite old, but the comments are good.
I've just found the following on MSDN, which looks like what you want:
localhost.Sample svc = new localhost.Sample();
try {
CredentialCache credCache = new CredentialCache();
NetworkCredential netCred =
new NetworkCredential( "Example", "Test$123", "sseely2" );
credCache.Add( new Uri(svc.Url), "Basic", netCred );
svc.Credentials = credCache;
Ok i got this working... But i have to run the code under an account that can access the Web service -
Dim URL As String = "http://server/MBSDKService/MsgSDK.asmx?WSDL"
Dim myService As New LANDeskMBDSK.MBSDK
myService.Url = URL
Dim CredCache As New System.Net.CredentialCache
CredCache.Add(New Uri(myService.Url), "Basic", Cred)
myService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials

Importing Google Drive Quickstart Code to Visual Basic

I am trying to get the Quickstart code for .Net imported to Visual Basic (VB .NET) and I had some errors. I am a newbie to this kind of programming. Would appreciate some pointers, or someone pointing out something that is fundamentally wrong with the code.
Appreciate the help!
The errors that I get when I try to compile the Console App are:
Error 2 Argument not specified for parameter 'arg' of 'Private Shared Function GetAuthorization(arg As Google.Apis.Authentication.OAuth2.DotNetOpenAuth.NativeApplicationClient) As DotNetOpenAuth.OAuth2.IAuthorizationState'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 22 86 Nipod Drive Console
Error 3 'BaseClientService' is ambiguous in the namespace 'Google.Apis.Services'. C:\Documents and Settings\Hirak\Local Settings\Application Data\Temporary Projects\Nipod Drive Console\Module1.vb 23 48 Nipod Drive Console
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports Google.Apis.Services
Namespace GoogleDriveSamples
Class DriveCommandLineSample
Shared Sub Main(ByVal args As String)
Dim CLIENT_ID As [String] = "YOUR_CLIENT_ID"
Dim CLIENT_SECRET As [String] = "YOUR_CLIENT_SECRET"
'' Register the authenticator and create the service
Dim provider = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim auth = New OAuth2Authenticator(Of NativeApplicationClient)(provider, GetAuthorization)
Dim service = New DriveService(New BaseClientService.Initializer() With { _
.Authenticator = auth _
})
Dim body As New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("document.txt")
Dim stream As New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
Console.WriteLine("File id: " + file.Id)
Console.WriteLine("Press Enter to end this process.")
Console.ReadLine()
End Sub
Private Shared Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState
' Get the auth URL:
Dim state As IAuthorizationState = New AuthorizationState( New () {DriveService.Scopes.Drive.GetStringValue()})
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = arg.RequestUserAuthorization(state)
' Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
Console.Write(" Authorization Code: ")
Dim authCode As String = Console.ReadLine()
Console.WriteLine()
' Retrieve the access token by using the authorization code:
Return arg.ProcessUserAuthorization(authCode, state)
End Function
End Class
End Namespace
I reliase this is an old subject, but this may help someone in future, make sure you compile in framework 3.5
Sorry cant seem to edit or delete my previous answer, for anyone in future, this should help:
Imports System
Imports System.Diagnostics
Imports DotNetOpenAuth.OAuth2
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports Google.Apis.Drive.v2
Imports Google.Apis.Drive.v2.Data
Imports Google.Apis.Util
Imports System.Security
Imports Google.Apis.Services
Public Class GoogleDrive
Public Function UploadFile() As Boolean
Const CLIENT_ID As String = "xxxxxxxxxxxxx.apps.googleusercontent.com"
Const CLIENT_SECRET As String = "-yyyyyyyyyyyyyyyyyyyyyyy"
'Register the authenticator and create the service
Dim provider As NativeApplicationClient = New NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET)
Dim getAuth As Func(Of NativeApplicationClient, IAuthorizationState) = AddressOf GetAuthorization
Dim auth As OAuth2Authenticator(Of NativeApplicationClient) = New OAuth2Authenticator(Of NativeApplicationClient)(provider, getAuth)
Dim service = New DriveService(New BaseClientService.Initializer() With {.Authenticator = auth})
Dim body As File = New File()
body.Title = "My document"
body.Description = "A test document"
body.MimeType = "text/plain"
Dim byteArray As Byte() = System.IO.File.ReadAllBytes("D:\document.txt")
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream(byteArray)
Dim request As FilesResource.InsertMediaUpload = service.Files.Insert(body, stream, "text/plain")
request.Upload()
Dim file As File = request.ResponseBody
MessageBox.Show("File : " & file.Id)
End Function
Private Function GetAuthorization(ByVal Client As NativeApplicationClient) As IAuthorizationState
Dim RetVal As IAuthorizationState
Dim state As IAuthorizationState = New AuthorizationState(New String() {DriveService.Scopes.Drive.GetStringValue()})
'Check to see if we have a saved refresh token
If My.Settings.SavedAuth.ToString <> "" Then
state.RefreshToken = My.Settings.SavedAuth
If (Client.RefreshToken(state)) Then
Return state
End If
End If
'Get the auth URL:
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim authUri As Uri = Client.RequestUserAuthorization(state)
'Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
'wait until user has entered the code
Dim authCode As String = InputBox("Authorisation code", "Authorisation Code", "")
'Retrieve the access token by using the authorization code:
RetVal = Client.ProcessUserAuthorization(authCode, state)
'store the refresh token
Call StoreRefreshToken(state.RefreshToken)
Return RetVal
End Function
Private Function LoadRefreshToken() As String
Return My.Settings.SavedAuth
End Function
Private Sub StoreRefreshToken(ByVal Token As String)
My.Settings("SavedAuth") = Token
My.Settings.Save()
End Sub
End Class