Calling RESTful service using VB.NET - asp.net

I'm using the following code to call a RESTful service:
Public Function InvokeService(ByVal RESTServiceURI As String, ByVal RequestMethod As String, ByVal SOAPAction As String, ByVal HTTPHeaderContentType As String, ByVal HTTPHeaderAccept As String, ByVal RequestData As String, ByVal NetworkCredentialUsername As String, ByVal NetworkCredentialPassword As String) As String
Dim RESTResponse As String = ""
Try
Dim RESTRequest As HttpWebRequest = CType(WebRequest.Create(RESTServiceURI), HttpWebRequest)
If NetworkCredentialUsername <> "" And NetworkCredentialPassword <> "" Then
Dim objCredential As New Net.NetworkCredential(NetworkCredentialUsername, NetworkCredentialPassword)
RESTRequest.Credentials = objCredential
End If
RESTRequest.Headers.Add("SOAPAction", SOAPAction)
RESTRequest.Accept = HTTPHeaderAccept
RESTRequest.Method = RequestMethod
If RequestMethod = "POST" Or RequestMethod = "PUT" Then
RESTRequest.ContentType = HTTPHeaderContentType
RESTRequest.ContentLength = RequestData.Length
Using RS As Stream = RESTRequest.GetRequestStream
Using SW As StreamWriter = New StreamWriter(RS)
SW.Write(RequestData)
End Using
End Using
End If
Using Serviceres As WebResponse = RESTRequest.GetResponse()
Using rd As StreamReader = New StreamReader(Serviceres.GetResponseStream())
RESTResponse = rd.ReadToEnd()
End Using
End Using
Catch ex As Exception
RESTResponse = ex.Message
End Try
Return RESTResponse
End Function
But I don't know if it must to use the following lines of code:
RESTRequest.Headers.Add("SOAPAction", SOAPAction)
RESTRequest.Accept = HTTPHeaderAccept
Please help, I need this function to be able to call any RESTful service.
Is there any enhancement needed to call any RESTful service?

Related

Facebook Graph not retrieves email address

I use Facebook login for website currently it doesn't retrieves email address I have update to Facebook Graph API endpoint version from v9.0 to v11.0 also I requested for both email and public_profile permissions in App Review section like below image but it still retrieve just (id,name,first_name,last_name ) and email is empty here is the VB.NET code to handle the Facebook Graph API
Public Sub GetUserData(ByVal FacebookAppId As String, ByVal FacebookAppSecret As String, ByVal RedirectURL As String, ByVal Code As String)
Dim targetUri As Uri = New Uri("https://graph.facebook.com/v11.0/oauth/access_token?client_id=" & FacebookAppId & "&client_secret=" & FacebookAppSecret & "&redirect_uri=" & RedirectURL & "&code=" & Code)
Dim at As HttpWebRequest = CType(HttpWebRequest.Create(targetUri), HttpWebRequest)
Dim str As System.IO.StreamReader = New System.IO.StreamReader(at.GetResponse().GetResponseStream())
Dim token As String = str.ReadToEnd().ToString().Replace("access_token=", "")
Dim combined As String() = token.Split(""""c)
Dim accessToken As String = combined(3)
Dim url As String = "https://graph.facebook.com/v11.0/me?fields=id%2Cname%2Cemail%2Cfirst_name%2Clast_name&access_token=" & accessToken.Trim(""""c) & ""
Dim request As WebRequest = WebRequest.Create(url)
request.ContentType = "application/json"
request.Method = "GET"
Dim userInfo As StreamReader = New StreamReader(request.GetResponse().GetResponseStream())
Dim jsonResponse As String = String.Empty
jsonResponse = userInfo.ReadToEnd()
Dim sr As JavaScriptSerializer = New JavaScriptSerializer()
Dim jsondata As String = jsonResponse
Dim converted As FacebookUserData = sr.Deserialize(Of FacebookUserData)(jsondata)
userId = converted.id
userName = converted.name
userFirstName = converted.first_name
userLastName = converted.last_name
userEmail = converted.email
End Sub
Permissions and Features image
Here is the login button
Protected Sub btnFBSignIn_Click(sender As Object, e As EventArgs) Handles btnFBSignIn.Click
Dim fbAppId As String = "AppID"
Dim fbUrllRedirect = "https://mywebsite.com/Login"
Dim fbApiUrl As String = "https://www.facebook.com/v11.0/dialog/oauth/?client_id=" & fbAppId & "&redirect_uri=" & fbUrllRedirect & "&response_type=code&state=1"
Response.Redirect(fbApiUrl)
End Sub

Get each key value out of a dictionary of strings object without using newsoft json

I have an indexpage.aspx which I post data into on page load. In this page I created list of strings
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim openWith As New SortedList(Of String, String)
' Add some elements to the list. There are no
' duplicate keys, but some of the values are duplicates.
openWith.Add("version", "1")
openWith.Add("key", ConfigurationManager.AppSettings("publickey"))
openWith.Add("cmd", "get_callback_address")
openWith.Add("currency", "coin")
Call POSTAPI("get_callback_address", openWith)
End Sub
Now I have a payment class which has postapi function, here's the class
Public Shared Function POSTAPI(cmd As String, Optional parms As SortedList(Of String, String) = Nothing) As Dictionary(Of String, Object)
Dim post_data As String = ""
For Each parm As KeyValuePair(Of String, String) In parms
If post_data.Length > 0 Then
post_data += "&"
End If
post_data += parm.Key + "=" + Uri.EscapeDataString(parm.Value)
Next
Dim keyBytes As Byte() = encoding.GetBytes(s_privkey)
Dim postBytes As Byte() = encoding.GetBytes(post_data)
Dim hmacsha512 = New System.Security.Cryptography.HMACSHA512(keyBytes)
Dim hmac As String = BitConverter.ToString(hmacsha512.ComputeHash(postBytes)).Replace("-", String.Empty)
' do the post:
Dim cl As New System.Net.WebClient()
cl.Headers.Add("Content-Type", "application/x-www-form-urlencoded")
cl.Headers.Add("HMAC", hmac)
cl.Encoding = encoding
Dim ret = New Dictionary(Of String, Object)()
Try
Dim resp As String = cl.UploadString("https://www.coinpayments.net/api.php", post_data)
Dim decoder = New System.Web.Script.Serialization.JavaScriptSerializer()
ret = decoder.Deserialize(Of Dictionary(Of String, Object))(resp)
Catch e As System.Net.WebException
ret("error") = "Exception while contacting CoinPayments.net: " + e.Message
Catch e As Exception
ret("error") = "Unknown exception: " + e.Message
End Try
Return ret
End Function
Its posting successfully but A successful call to the 'get_callback_address' or 'get_deposit_address' command will give you a result similar to this (JSON):
{
"error":"ok",
"result":{
"address":"1BitcoinAddress",
"pubkey":"",
"dest_tag":100,
}
}
Above are the keys and values is returning. Now my question is I only want to get the values of result and split it so it gives me "1BitcoinAddress", "pubkey" and save it to my database(I want to get the 3 values of that resultkey so i can save it in my database".
Thank you.
Since you deserialized the incoming json as a Dictionary(Of String, Object) the JavaScriptSerializer should have already created a second dictionary for the value of the result key. The only thing you have to do now, is create a variable that takes the value stored in the dictionary and cast it as a Dictionary(Of String, Object) in order to use it, like in this example
Dim json As String = "{" +
"""error"":""ok""," +
"""result"":{" +
"""address"":""1BitcoinAddress""," +
"""pubkey"":""""," +
"""dest_tag"":100" +
"}" +
"}"
Dim deserializer = New System.Web.Script.Serialization.JavaScriptSerializer()
'get the full dictionary
Dim dictionary = deserializer.Deserialize(Of Dictionary(Of String, Object))(json)
' make sure there is a key in your dictionary
If dictionary.ContainsKey("result") Then
'cast the value for "result" as a dictionary
Dim resultDictionary As Dictionary(Of String, Object) = _
DirectCast(dictionary("result"), Dictionary(Of String, Object))
'you can then access the keys by their key
Console.WriteLine("address: {0}, pubkey: {1}, dest_tag: {2}", _
resultDictionary("address"), _
resultDictionary("pubkey"), _
resultDictionary("dest_tag"))
End If
With your input, the program gives an output on the console, like this:
address: 1BitcoinAddress, pubkey: , dest_tag: 100
The big question of your question is really why you want to solve the deserialization without the use of Json.net. On the website for the JavaScriptSerializer,
it says at once:
Json.NET should be used serialization and deserialization. Provides serialization and deserialization functionality for AJAX-enabled applications.

Cross communication between two web applications using web requests: is this close to viable?

I am using the following code to try and learn how pages post, listen and respond between one another using web requests. I begin the process by issuing a request in the first of the two procedures, intending to have the second process retrieve the request and respond back to the calling process. My calling process is receiving a blank response.
Question: Why, and how close to viable is this test?
Here's my two page load events, located in two separate web applications.
Both apps are hosted on IIS:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sPostURL As String = "http://localhost/DDI_TXListener_Test/Listener_Page.aspx"
Dim dataToPost As String = String.Empty ' //This is the data for form posting
Dim HttpWebResponse As System.Net.WebResponse = Nothing
Dim StreamReader As System.IO.StreamReader = Nothing
Dim respString As String = String.Empty
Dim stOut As System.IO.Stream = Nothing
dataToPost = "Name"
Try
Dim httpReq As System.Net.WebRequest = System.Net.WebRequest.Create(sPostURL)
httpReq.Method = "POST"
httpReq.ContentType = "application/x-www-form-urlencoded"
Dim byte1 As Byte() = System.Text.Encoding.ASCII.GetBytes(dataToPost)
httpReq.ContentLength = byte1.Length
httpReq.Timeout = 10000
stOut = httpReq.GetRequestStream()
stOut.Write(byte1, 0, byte1.Length)
stOut.Dispose()
stOut = Nothing
HttpWebResponse = httpReq.GetResponse()
StreamReader = New System.IO.StreamReader(HttpWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"))
respString = StreamReader.ReadToEnd()
Catch ex As Exception
Finally
If Not StreamReader Is Nothing Then
StreamReader.Dispose()
StreamReader = Nothing
End If
If Not HttpWebResponse Is Nothing Then
HttpWebResponse.Close()
HttpWebResponse = Nothing
End If
End Try
' <asp:label> control on the html form in front of this code page
returnedhit.Text = respString
End Sub
And I have this as what I hope to use as the receiving/fulfilling end of the above request at:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim sPostURL As String = "http://localhost/DDI_TXRequester_Test/RequesterPage.aspx"
Dim dataToPost As String = String.Empty ' //This is the data for form posting
Dim HttpWebResponse As System.Net.WebResponse = Nothing
Dim StreamReader As System.IO.StreamReader = Nothing
Dim respString As String = String.Empty
Dim stOut As System.IO.Stream = Nothing
Try
Dim httpReq As System.Net.WebRequest = System.Net.WebRequest.Create(sPostURL)
HttpWebResponse = httpReq.GetResponse()
StreamReader = New System.IO.StreamReader(HttpWebResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"))
respString = StreamReader.ReadToEnd()
If respString <> "" Then
Dim cnt As Integer = 0
Dim delim As Char() = {"&"c}
Dim bodpos As Integer = InStr(respString, "<body>") + 6
Dim respstr As String = Right$(respString, (Len(respString) - bodpos))
Dim strArr As String() = respstr.Split(delim)
For Each s As String In strArr
cnt += 1
Select Case cnt
Case 1
Session.Add("opRequested", Right$(Trim(s), (Len(Trim(s)) - 18)))
Case Else '
End Select
Next s
If CStr(Session("opRequested")) = "Name" Then dataToPost = "Name=Jones" Else dataToPost = "Error=Unknown Request"
httpReq.Method = "POST"
httpReq.ContentType = "application/x-www-form-urlencoded"
Dim byte1 As Byte() = System.Text.Encoding.ASCII.GetBytes(dataToPost)
httpReq.ContentLength = byte1.Length
httpReq.Timeout = 10000
stOut = httpReq.GetRequestStream()
stOut.Write(byte1, 0, byte1.Length)
stOut.Dispose()
stOut = Nothing
End If
Catch ex As Exception
Finally
If Not stOut Is Nothing Then
stOut.Dispose()
stOut = Nothing
End If
If Not StreamReader Is Nothing Then
StreamReader.Dispose()
StreamReader = Nothing
End If
If Not HttpWebResponse Is Nothing Then
HttpWebResponse.Close()
HttpWebResponse = Nothing
End If
End Try
End Sub

HttpWebRequests Returning error from Youtube

I cannot seem to understand what I'm doing wrong here.
My code below keeps returning a 400 code from youtube....
If Not Page.Request.QueryString("code") Is Nothing Then
Dim code As String = "code=" & Page.Request.QueryString("code") & "&client_id=myclientid&client_secret=mysecret&redirect_uri=http://localhost:61163/Testing/YoutubeAPI.aspx&grant_type=authorization_code"
Dim request As HttpWebRequest = WebRequest.Create("https://accounts.google.com/o/oauth2/token")
Dim byteData As Byte() = Encoding.UTF8.GetBytes(code)
With request
.Method = "POST"
.ContentType = "application/x-www-form-urlencoded"
.ContentLength = byteData.Length
End With
Dim requestStream As Stream = request.GetRequestStream()
requestStream.Write(byteData, 0, byteData.Length)
requestStream.Close()
Dim WebResponse As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim responseStream As Stream = WebResponse.GetResponseStream()
Dim sb As StringBuilder = New StringBuilder
Using reader As New StreamReader(responseStream, System.Text.Encoding.UTF8)
Dim line As String = reader.ReadLine()
If Not line Is Nothing Then
sb.Append(line)
End If
End Using
End If
the error occurs at request.GetRequestStream()... the best I can figure out at this stage is that google doesn't like what i'm asking for but cannot seem to find out why?
(My client ID and secret have been swopped incidentally....)
well am not sure if the etiquette is correct here in answering my own question but you may find it useful nonetheless.
The answer lay in the URL encoding of content string...
so now slightly amended the awesomeness of OAuth2 is unleashed and I can get pretty much whatever I want from the youtube API :) (although NO thanks to the black hole rabbit-hole of google documentation...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.Request.QueryString("code") Is Nothing Then
Dim Token As String = CodeTrade("code=" & Server.UrlEncode(Page.Request.QueryString("code")) & "&redirect_uri=" & Server.UrlEncode("http://localhost:61163/Testing/YoutubeAPI.aspx") & "&client_id=xxx=&client_secret=xxx&grant_type=authorization_code")
'now i CAN do something with the magical and elusive access_token from this point forward....
End If
End Sub
Public Shared Function CodeTrade(code As String) As String
Dim apiResponse As String
Dim postData As String = code
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://accounts.google.com/o/oauth2/token"), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
apiResponse = DirectCast(response, HttpWebResponse).StatusDescription.ToString()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Return responseFromServer
End Function

error 400 on google oauth request

I have this code. It returns an error 400 bad request and I cannot find why.
The error at line 31 (which is where it's supposed to get the response...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.Request.QueryString("code") Is Nothing Then
Dim Token As String = GetToken("code=" & Server.UrlEncode(Page.Request.QueryString("code")) & "&client_id=xxx&client_secret=xxx&grant_type=authorization_code&redirect_uri=" & Server.UrlEncode("http://localhost:61163/Testing/YoutubeAPI.aspx"))
'do something with the magical and elusive access_token from this point forward....
End If
End Sub
Public Shared Function GetToken(code As String) As String
Dim apiResponse As String
Dim postData As String = code
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://accounts.google.com/o/oauth2/token"), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
apiResponse = DirectCast(response, HttpWebResponse).StatusDescription.ToString()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Return responseFromServer
End Function
I am not sure about your code but you can always use YouTube Dotnet client libraries.
Here's a sample application using it.
well am not sure if the etiquette is correct here in answering my own question but you may find it useful nonetheless.
The answer lay in the URL encoding of content string...
so now slightly amended the awesomeness of OAuth2 is unleashed and I can get pretty much whatever I want from the youtube API :) (although NO thanks to the black hole rabbit-hole of google documentation...
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.Request.QueryString("code") Is Nothing Then
Dim Token As String = CodeTrade("code=" & Server.UrlEncode(Page.Request.QueryString("code")) & "&redirect_uri=" & Server.UrlEncode("http://localhost:61163/Testing/YoutubeAPI.aspx") & "&client_id=xxx=&client_secret=xxx&grant_type=authorization_code")
'now i CAN do something with the magical and elusive access_token from this point forward....
End If
End Sub
Public Shared Function CodeTrade(code As String) As String
Dim apiResponse As String
Dim postData As String = code
Dim request As HttpWebRequest = DirectCast(WebRequest.Create("https://accounts.google.com/o/oauth2/token"), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
apiResponse = DirectCast(response, HttpWebResponse).StatusDescription.ToString()
dataStream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
dataStream.Close()
response.Close()
Return responseFromServer
End Function

Resources