Visual studio 2008 express crashes when writing method call - vb.net

I'm using to Google Calendar API v3 and following the samples to create the windows form application I need. I have an issue in the getAuthorization method provided in the sample.
Basically whenever I write down aut.RefreshToken(... Visual studio crashes
Here's my getAuthorization method:
Private Shared Function GetAuthorization(ByVal arg As NativeApplicationClient) As IAuthorizationState
Dim scopes() As String = { _
CalendarService.Scopes.Calendar.GetStringValue, _
CalendarService.Scopes.CalendarReadonly.GetStringValue _
}
' Get the auth URL:
Dim state As IAuthorizationState = New AuthorizationState(scopes)
state.Callback = New Uri(NativeApplicationClient.OutOfBandCallbackUrl)
Dim refreshToken As String = GetRefreshToken()
If refreshToken <> "" Then
state.RefreshToken = refreshToken
'If arg.RefreshToken(state) Then
' SaveRefreshToken(refreshToken)
' Return state
'End If
End If
Dim authUri As Uri = arg.RequestUserAuthorization(state)
' Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString())
Dim authCode As String = ""
While authCode = ""
authCode = InputBox("Paste the code provided by Google here:", "Verification code")
End While
' Retrieve the access token by using the authorization code:
Dim result = arg.ProcessUserAuthorization(authCode, state)
SaveRefreshToken(refreshToken)
Return result
End Function
As it can be seen, the arg.RefreshToken block has been commented. If I try to uncomment it or writing it again, VS crashes.
I have to point out that I've tried this code on VS Pro 2010 and worked without any problems

Compiling the method in a dll on its own in VS 2010 worked as I expected, however if anyone ever encountered anything similar, I would appreciate any help as this solution is far from ideal.

Related

RestSharp call to eBay oauth2 user token

I am trying to get eBay user tokens for my users using the identity api. I finally got it to work in Postman. Converted the call from Postman to a restsharp call from a vb.net test app. The Postman call works, the VB call returns "404 Not Found". Looked at the two calls using Fiddler. The only difference I can see is that the Postman call goes to:
"POST https://api.sandbox.ebay.com/identity/v1/oauth2/token";
and the VB app call goes to
"POST https://api.sandbox.ebay.com/identity/v1/oauth2/token/1"
It would appear that somewhere the VB app is appending "/1" to the api url. Not sure where this is occurring as I can step through the code as it executes and don't see it.
Is there a property in RestSharp that might cause this value to be appended?
EDIT added code. This code is supposed to return a user token and refresh token from eBay. It is taken pretty much from Postman with mods to work with the latest version.
Async Sub RSGetCode(sCode As String)
Dim client As RestClient = New RestClient("https://api.sandbox.ebay.com/identity/v1/oauth2/token")
Dim request As RestRequest = New RestRequest(Method.Post)
sCode = WebUtility.UrlDecode(sCode)
With request
.AddHeader("Content-Type", "application/x-www-form-urlencoded")
.AddHeader("Authorization", "Basic TXVycGh5c0MtNzYxNy00ZGRmLTk5N2ItOD..........................")
.AddParameter("grant_type", "authorization_code")
.AddParameter("code", sCode)
.AddParameter("redirect_uri", "Murphys_Creativ-Mu...........")
.AddParameter("Scope", "https://api.ebay.com/oauth/api_scope/sell.inventory")
End With
Dim responce = Await client.PostAsync(request)
'Dim responce = Await client.ExecuteAsync(request)
Dim sR As String = responce.Content
End Sub```
I got it to work by slightly reformating the code. See below.
Async Sub PostRestCode(sCode As String)
Dim client As RestClient = New RestClient("https://api.sandbox.ebay.com")
Dim request As RestRequest = New RestRequest("identity/v1/oauth2/token", Method.Post)
With request
.AddHeader("Content-Type", "application/x-www-form-urlencoded")
.AddHeader("Authorization", "Basic TXVycGh5c0MtNzYxNy00ZGRmLTk5N2ItODc2OGMzZWZkYT..............................")
.AddParameter("grant_type", "authorization_code")
.AddParameter("code", sCode) '"v^1.1#i^1#I^3#p^3#f^0#r^1#t^Ul41Xzg6NEN.......................................")
.AddParameter("redirect_uri", "Murphys_Creativ-Mu......................")
.AddParameter("Scope", "https://api.ebay.com/oauth/api_scope/sell.inventory")
End With
Dim responce = Await client.PostAsync(request)
'Dim responce = Await client.ExecuteAsync(request)
Dim sR As String = responce.Content
End Sub

Need help in solving error in HTTP GET request

Need help in solving error in HTTP GET request [closed]
I have the following code in VB.NET framework which should pull the data in json format and add it to a list view control using GET request. However I am getting following error:
System.Threading.Tasks.Task.FromResult(System.Net.Http.HttpResponseMessage)
Dim client = New HttpClient()
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{Subscription-Key}")
Dim uri = "https://example.com/" & SearchKey
Dim response = client.GetAsync(uri)
lstMer.Items.Add(response.ToString)
Initially I wrote the following code in VBA and it was working fine:
Dim jsonText as String
Set req = New MSXML2.ServerXMLHTTP60
key_id = "{Subscription-Key}"
key_header_name = "Subscription-Key-Id"
liveURL = "https://example.com/" & SearchKey
req.Open "GET", liveURL, False
req.setRequestHeader {Subscription-Key-Id}, {Subscription-Key}
req.setRequestHeader "Host", "site Address"
req.send
jsonText = req.responseText
The requirement is to get the headers from URL and fill a list view.
I think I understand. You don't get an error
System.Threading.Tasks.Task.FromResult(System.Net.Http.HttpResponseMessage)
rather you get that as a result of response.ToString(). This is because you are calling client.GetAsync(uri) directly, which returns a Task.FromResult<TResult>. However, it is meant to be run async, and there are some convenient keywords for achieving this, namely Async / Await. If you await the task, instead of returning a Task.FromResult<TResult>, it will return a TResult. So change your code to do just that
Private Async Sub Foo()
Dim client = New HttpClient()
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{Subscription-Key}")
Dim uri = "https://example.com/" & SearchKey
Dim response = Await client.GetAsync(uri)
lstMer.Items.Add(response.ToString)
End Sub
See HttpClient.GetAsync and about what it returns Task.FromResult

.NET Google API access token failing with no refresh token specified

I am trying to set up a class that can wrap around the .NET Google API so that I can use an Access Token that I have previously obtained to access a user's Google Drive. As of right now, I am just trying to get it to work so that I do not require a Refresh Token (more on that in a second). The ultimate goal is for somebody to go through a web page I have set up to authenticate where I obtain both an Access Token and a Refresh Token by directly calling to the Google Rest API (which I store in a database). They can then request to upload/download files onto their Drive on a different page which will first obtain the appropriate information from the database and then use the .NET Google API Library when accessing Drive.
However, when I attempt to access their Drive I get the the following error:
The access token has expired and could not be refreshed. Errors: refresh error, refresh error, refresh error
I know that the Access Token is valid because I obtain it only seconds earlier during my testing. Here is my code for setting up the Drive Service:
' NOTE: Code altered for brevity
Public Sub Initialize(accessToken As String)
' Set up the client secret information based on the default constants
Dim clientSecrets As New ClientSecrets()
clientSecrets.ClientId = DEFAULT_CLIENT_ID
clientSecrets.ClientSecret = DEFAULT_CLIENT_SECRET
' Set up a token based on the token data we got
' NOTE: Is it OK to leave some strings as NULL?
Dim token As New Responses.TokenResponse()
token.AccessToken = accessToken
token.RefreshToken = ""
token.TokenType = "Bearer"
token.IssuedUtc = DateTime.Now
token.ExpiresInSeconds = 3600
token.Scope = "drive"
token.IdToken = ""
' Set up a flow for the user credential
Dim init As New GoogleAuthorizationCodeFlow.Initializer()
init.ClientSecrets = clientSecrets
init.Scopes = New String() {DriveService.Scope.Drive}
init.Clock = Google.Apis.Util.SystemClock.Default
' Set up everything else and initialize the service
Dim baseInit As New BaseClientService.Initializer()
baseInit.HttpClientInitializer = New UserCredential(New GoogleAuthorizationCodeFlow(init), "user", token)
baseInit.ApplicationName = APP_NAME
_service = New DriveService(baseInit)
End Sub
Shortly after that, I then use the following code to request a folder so I can check to see if it exists or not.
Private Function GetDriveFolder(folderPath As String, ByRef folderIds As String(), Optional createMissingFolders As Boolean = False, Optional parentFolderId As String = "root") As Data.File
Dim creatingFolderPath As Boolean = False
Dim currentFolder As Data.File = Nothing
Dim folderPathSplit As String() = folderPath.Replace("/", "\").Trim("\").Split("\")
Dim folderIdList As New List(Of String)
folderIds = {}
' Loop through each folder in the path and seek each out until we reach the end
For x As Integer = 0 To folderPathSplit.Length - 1
Dim result As FileList = Nothing
If Not creatingFolderPath Then
' Build a list request which we will use to seek out the next folder
Dim request As FilesResource.ListRequest = _service.Files.List()
request.Q = "mimeType='application/vnd.google-apps.folder' and name='" & folderPathSplit(x) & "'"
If currentFolder Is Nothing Then
request.Q &= " and '" & EscapeDriveValue(parentFolderId) & "' in parents"
Else
request.Q &= " and '" & EscapeDriveValue(currentFolder.Id) & "' in parents"
End If
request.Spaces = "drive"
request.Fields = "files(id, name)"
' Execute the search, we should only get a single item back
' NOTE: Error thrown on this request
result = request.Execute()
End If
' So on.....
So, I'm just trying to get it to work with only the Access Token for the time being because if it ends up getting refreshed I'll need to know so that I can update my database. However, if I do include the Refresh Token I get the following error:
Error:"unauthorized_client", Description:"Unauthorized", Uri:""
I'm guessing this has something to do with the way I have configured my application through the Dev Console but if I authenticate through the Google API Library by having it launch a browser to get my credentials everything works fine. So, I'm really not sure where to go from here as I haven't found anybody having similar problems and the guides don't cover specifying your own Access Token.
Also, as a quick note this is the URL I am using when having the user authenticate:
String.Format("https://accounts.google.com/o/oauth2/v2/auth?client_id={0}&state={1}&redirect_uri={2}&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&access_type=offline&include_granted_scopes=true&prompt=select_account%20consent&response_type=code", GOOGLEAPI_CLIENTID, validateState, redirectUri)
Thanks for the help!
If you have an access-token then the simplest way to create a google credential is to use the GoogleCredential.FromAccessToken() method passing in your access token.
This returns you a GoogleCredential instance which you can use to set the HttpClientInitializer property when building the DriveService.
If you then still get an error when accessing the drive service, then it's likely there's something incorrect in how you are asking for the access-token.

How do I upload data to a server with valid SSL certificate using a client vb.net program?

I am working on a program and uploads a shipping manifest to a the shippers website. When I try to upload, I get a nondescript error back from their server, and when checking with the shipper, they tell me that "there is an issue with the SSL" I am using.
I've spent quite a bit of time piecing together code that, from what I seem to understand, is supposed to work, but I'm not making any progress. As far as I know everything else is fine with the upload, but there is a problem with my SSL certificate
If I understand what this code is supposed to do correctly, I should get a certificate from the shippers website, which allows certification to my program for a space of time during which I can upload the data. I'm really not sure that this is what my code is doing at all, but the only code examples I have seen show it something like this.
Here's my code with the URLs changed:
'This references a custom class that compiles the manifest I'm going to upload
Dim StringToUpload As String = Compile_Manifest(MyDate, UseTestDB)
Dim webClient As New System.Net.WebClient
webClient.Credentials = System.Net.CredentialCache.DefaultCredentials
'From what I understand,
'this is supposed to set up properties used in next section of code
System.Net.ServicePointManager.SecurityProtocol = Net.SecurityProtocolType.Ssl3
System.Net.ServicePointManager.ServerCertificateValidationCallback = _
AddressOf AcceptAllCertifications
'I can see that this reaches the server,
'but I don't know how it relates to the next section of code
'that actually uploads the manifest
Dim ServerRequest As System.Net.WebRequest = _
System.Net.WebRequest.Create("https://www.certify.some-shippper.com:443/somefolder")
Dim ServerResponse As System.Net.WebResponse
ServerResponse = ServerRequest.GetResponse()
ServerResponse.Close()
'This code works for the upload of the manifest,
'and it seems the above code is unrelated and does not use a SSL certificate.
'When this code runs I get the same error back from the shippers server,
'indicating an issue with my SSL, with or without the two sections of code above.
Dim StrResult As String = ""
Dim WrappedString As String = TransmitPLD.WrapPldFile(StringToUpload)
'This references a custom class that wraps the data to upload
'in information from the shipper.
Dim ByesToUpload As Byte() = _
System.Web.HttpUtility.UrlEncodeToBytes(WrappedString, _
System.Text.ASCIIEncoding.ASCII)
Dim Result As Byte() = _
webClient.UploadData("https://www.certify.some-shippper.com:443/somefolder", _
ByesToUpload)
StrResult = System.Web.HttpUtility.UrlDecode(Result, _
System.Text.ASCIIEncoding.ASCII)
MessageBox.Show(StrResult)
So it turns out I went about it the wrong way. I needed to upload my data through System.Net.WebRequest and it takes care of the certificates for me. Not implementing all the parts of the code I needed, it didn't handle the retrieval of the shipper's certificate.
In case anyone else gets confused about the matter like I did, here's my working code for anyone to see, adapt and use. My resource for fixing the code (and by that I mean starting from scratch) was the MSDN page for the WebRequest class, and it has code examples much the same as what I have below in C++, C#, and VB.NET and here is the link.
First there are some global variables that need to be set and class that needs to be created for to store the upload response:
' This is set in the function that Upload function
' and uploads the data in the ReadCallback sub
Private Shared WrappedString As String
' This is used to wait for the callback in the Upload function
Private Shared allDone As New Threading.ManualResetEvent(False)
Friend Class RequestState
' This class stores the request state of the request.
Public request As Net.WebRequest
Public Sub New()
request = Nothing
End Sub ' New
End Class ' RequestState
Then there is a sub needed for the upload part web request which will be called further below in the upload function:
Private Shared Sub ReadCallback(asynchronousResult As IAsyncResult)
Try
Dim myRequestState As RequestState = CType(asynchronousResult.AsyncState, RequestState)
Dim myWebRequest As Net.WebRequest = myRequestState.request
' End the request.
Dim streamResponse As IO.Stream = myWebRequest.EndGetRequestStream(asynchronousResult)
' Convert the string into a byte array.
Dim byteArray As Byte() = System.Text.Encoding.ASCII.GetBytes(WrappedString)
' Write the data to the stream.
streamResponse.Write(byteArray, 0, byteArray.Length)
streamResponse.Close()
' Allow the main thread to resume.
allDone.Set()
Catch ex As Exception
Throw New Exception("Error in " & Reflection.MethodBase.GetCurrentMethod.Name.ToString & " **" & ex.Message, ex)
End Try
End Sub ' ReadCallback
Finally, this is the function that should be called to upload the data, which uses all the code above:
Public Shared Function Upload(ByVal MyDate As Date) As String
Dim StrResult As String = ""
UploadSucess = False
Try
' This is my code that builds the manifest that I want to upload
Dim StringToUpload As String = Compile_PLD200(MyDate)
WrappedString = TransmitPLD.WrapPldFile(StringToUpload)
Dim myWebRequest As Net.WebRequest
myWebRequest = Net.WebRequest.Create("https://www.some.website.com:443/someplace")
' Create an instance of the RequestState and assign
' myWebRequest to it's request field.
Dim myRequestState As New RequestState()
myRequestState.request = myWebRequest
myWebRequest.ContentType = "multipart/mixed; boundary=BOUNDARY"
myRequestState.request.Method = "POST"
' Start the asynchronous 'BeginGetRequestStream' method call.
Dim r As IAsyncResult = CType(myWebRequest.BeginGetRequestStream(AddressOf ReadCallback, myRequestState), IAsyncResult)
' Pause the current thread until the async operation completes.
allDone.WaitOne()
' Send the Post and get the response.
Dim myWebResponse As Net.WebResponse = myWebRequest.GetResponse()
Dim streamResponse As IO.Stream = myWebResponse.GetResponseStream()
Dim streamRead As New IO.StreamReader(streamResponse)
Dim readBuff(256) As [Char]
Dim count As Integer = streamRead.Read(readBuff, 0, 256)
While count > 0
Dim outputData As New [String](readBuff, 0, count)
Console.WriteLine(outputData)
count = streamRead.Read(readBuff, 0, 256)
StrResult += outputData
End While
' Close the Stream Object.
streamResponse.Close()
streamRead.Close()
' Release the HttpWebResponse Resource.
myWebResponse.Close()
Catch ex As Exception
Throw New Exception("Error in " & Reflection.MethodBase.GetCurrentMethod.Name.ToString & " **" & ex.Message, ex)
End Try
Return StrResult
End Function ' Upload
Again here is the MSDN page for the WebRequest class which has a code example too.
Hope this helps anyone who was stuck like I was. And any criticisms as to the implementation of the code are welcome. This just happen to do what I want, I can't say it is the most efficient implementation.

Set "client_updated_time" when uploading file to OneDrive

I have nearly completed a basic OneDrive interface, and am able to handle creating and writing folders, files, and so forth. The last element to get working is to update a file's date/time stamp to match that of the local (originating) file.
When I drop a file via the browser interface, the file's date/time stamp shows correctly in the view. This is reflected in the "client_updated_time" when I read the file's properties later in my application. Clear enough.
However, I cannot find any way to update this field programmatically from within my application. I am using the following code, to no avail. I have a valid _accessToken value, a valid fileId for the new file, and the call results always indicates success.
The "name" and "updated_time" elements are just in there to see if anything happens, and the file will indeed rename if I mangle the fileName variable a bit. I didn't expect the "updated_time" to updated, but it seems to me that the "client_updated_time" element should work.
Using fiddler, it appears that the browser-based interface (java?) opens a session, sends the file over, and then in the close-session call uses a header entry labelled "X-Last-Modified-ISO8601" to set the file's date-time stamp. However, using the REST interface, I cannot find any examples of this. The documentation for setting file properties mentions renaming only (which works in this code).
Any feedback on how to accomplish setting "client_updated_time" with REST calls would be much appreciated!
Here's the relevant code:
Private _liveURL As String = "https://apis.live.net/v5.0/"
Private Sub AddAuthorizationHeader(hc As HttpClient, authorization As String)
If Len(authorization) > 0 Then
hc.DefaultRequestHeaders.Authorization = New Headers.AuthenticationHeaderValue("Bearer", authorization)
End If
End Sub
Public Function WebPUT(uri As String, contentType As String, authorization As String, data As String) As String
Dim response As String = String.Empty
Try
Dim hc As New HttpClient()
Dim content As New Http.StringContent(data, System.Text.Encoding.UTF8, contentType)
AddAuthorizationHeader(hc, authorization)
Using r = hc.PutAsync(uri, content).Result
response = r.Content.ReadAsStringAsync.Result
End Using
Catch ex As Exception
' fake it
response = "{""error"": {""code"": ""invalid_request"", ""message"": """ + ex.Message + """}}"
End Try
Return response
End Function
Private Function UpdateFileDateTime(fileId As String, fileName As String, fileDt As String) As Boolean
Dim response As Boolean = False
Dim wr As String = WebHelper.WebPUT(_liveURL + fileId, "application/json", _accessToken, "{ ""name"": """ + fileName + """, ""updated_time"": """ + fileDt + """, ""client_updated_time"": """ + fileDt + """ }")
'... parse wr for response
Return response
End Function
Based on the file object reference, that field is read-only via the REST API: http://msdn.microsoft.com/en-us/library/dn631834.aspx