WP7, getting weird response from twitter - vb.net

i am using hammock twitter library to post and get the friends list from Twitter. Previously it was working fine. But now only the request_token part is working. While trying to get the access tokens and userid, screen name getting an "OK" server response. But the result looks likes this:
� �Dͻ�0#�as�"Ё��&b�����֔ԧ��8ߑ��h9�v�r<{g�/�XR>�eݻ.>~�rH�5�Z��_�~�+Kn9��)��£�sU��)��������|�TV6!�B��2(���֚V`�!��#4�� �� ��?d�
I dont know why i am getting this.. :(
below is my code
Public Sub GetRequestToken(Consumer_KEY As String, Consumer_Secret_Key As String)
Dim credentials = New OAuthCredentials
credentials.Type = OAuthType.RequestToken
credentials.SignatureMethod = OAuthSignatureMethod.HmacSha1
credentials.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader
credentials.ConsumerKey = TwitterSettings.ConsumerKey
credentials.ConsumerSecret = TwitterSettings.ConsumerKeySecret
credentials.Version = TwitterSettings.OAuthVersion
credentials.CallbackUrl = "oob"
Dim client = New RestClient
client.Authority = "https://api.twitter.com/oauth"
client.Credentials = credentials
client.HasElevatedPermissions = True
Dim request = New RestRequest
request.Path = "/request_token"
client.BeginRequest(request, New RestCallback(AddressOf TwitterRequestTokenCompleted))
End Sub
Public Sub TwitterRequestTokenCompleted(request As RestRequest, response As RestResponse, userstate As Object)
result = Regex.Split(response.Content, "&")
oauth_token = Regex.Split(result(0), "=")(1)
oauth_secret_token = Regex.Split(result(1), "=")(1)
request_url = TwitterSettings.AuthorizeUri + "?oauth_token=" + oauth_token
case_url = "request"
Deployment.Current.Dispatcher.BeginInvoke(getresult)
End Sub
After parsing the oob pin, i am requesting for access tokens:
Public Sub GetAccessToken(Verifier As String)
Dim credentials = New OAuthCredentials
credentials.Type = OAuthType.AccessToken
credentials.SignatureMethod = OAuthSignatureMethod.HmacSha1
credentials.ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader
credentials.ConsumerKey = TwitterSettings.ConsumerKey
credentials.ConsumerSecret = TwitterSettings.ConsumerKeySecret
credentials.Token = oauth_token
credentials.TokenSecret = oauth_secret_token
credentials.Verifier = Verifier
Dim client = New RestClient
client.Authority = "https://api.twitter.com/oauth"
client.Credentials = credentials
client.HasElevatedPermissions = True
Dim request = New RestRequest
request.Path = "/access_token"
client.BeginRequest(request, New RestCallback(AddressOf RequestAccessTokenCompleted))
did anyone face this before? i need this asap.. just confused how this happened all of a sudden. Thanks in advance geeks ;)

Related

RestSharp response forbidden

I trying get a simple request to https://c-cex.com/t/prices.json
If i use this url in browser the correct response is showed , but if i make the same request using RestRequest i receive the 403 error Forbidden in all times. i trying HttpClient,WebRequest i get the same error
I put the header with user-agent, no cache and a lot of another values but did not work
Any ideas about this problem?
Dim url As String = "https://c-cex.com/t/prices.json"
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
Dim response = client.Execute(request)
Updated code with apisign request
Dim nonce As String = CInt((DateTime.UtcNow - New DateTime(1970, 1, 1)).TotalSeconds).ToString
Dim url As String = "https://c-cex.com/t/api.html?a=getbalance&currency=BTC&apikey=" & API_KEY & "&nonce=" & nonce
Dim keybytes() = UnicodeEncoding.ASCII.GetBytes(API_SECRET)
Dim hs As System.Security.Cryptography.HMACSHA512 = New System.Security.Cryptography.HMACSHA512(keybytes)
Dim urlbytes() = UnicodeEncoding.ASCII.GetBytes(url)
Dim sh() = hs.ComputeHash(urlbytes)
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
request.AddHeader("Cache-Control", "no-cache")
request.AddHeader("apisign", HttpUtility.UrlEncode(ToHexString(sh)))
Dim response = client.Execute(request)
I am getting the response without providing the header information and It looks given piece of code is working correctly for me in VB and C#.As a best practice, base URL needs to be specified in RestClient and relative URL in RestRequest.
Please recheck without adding the request header information
VB:
Imports RestSharp
Module Module1
Sub Main()
Dim host As String = "https://c-cex.com"
Dim endpoit As String = "t/prices.json"
Dim client As New RestSharp.RestClient(host)
Dim request = New RestRequest(endpoit, Method.GET)
Dim response = client.Execute(request)
Console.WriteLine("Response Body " + response.Content)
Console.WriteLine("Response Code " + response.StatusDescription)
End Sub
End Module
C#:
String host = "https://c-cex.com";
String endpoint = "t/prices.json";
RestClient _restClient = new RestClient(host);
var request = new RestRequest(endpoint, Method.GET);
var response = _restClient.Execute(request);
Console.WriteLine("Response Body :"+response.Content);
Console.WriteLine("Response Status Code :" + response.StatusDescription);

Acessing Google Calendar API from Windows Service

I am writing a windows service application in Visual Studio (VB) that polls a users google calendar for any events that are happening within the next 5 minutes.
Ideally, I'd like my service to generate the credentials, but I don't think a windows service can pop up a browser page to authenticate someone. Currently I am generating the credentials in a specific location from a console app that can pop up a browser, and having the service look for credentials in that location. I'd like to get rid of the console app altogether, but if it's necessary I'll just run it in the batch file that installs the service.
The big issue I'm having is generating the credentials file (secondary concern), and more importantly refreshing it so it doesn't expire after an hour (primary concern).
Here is my windows service code (this works perfectly fine for the hour after I run my console app and allow access to my calendar):
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Private Sub writeUpdateTimerEvent(source As Object, e As ElapsedEventArgs)
Dim credential As UserCredential
Try
Using stream = New FileStream("FILE PATH TO client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "FILE PATH TO WHERE MY CONSOLE APP IS STORING THE CREDENTIALS FILE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
If credential Is Nothing Then
credential.RefreshTokenAsync(CancellationToken.None)
End If
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.TimeMax = DateTime.Now.AddMinutes(5)
request.ShowDeleted = False
request.SingleEvents = True
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim eventsString As String = ""
Dim events As Events = request.Execute()
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
'This is where I do my operations on events occuring in the next 5 minutes
EventLog1.WriteEntry("Event occuring within 5 minutes")
Else
EventLog1.WriteEntry("No event occuring within 5 minutes")
End If
Catch ex As Exception
EventLog1.WriteEntry("error grabbing events." & Environment.NewLine & ex.message)
End Try
End Sub
Here is my console app code (pretty much the same as above):
Module Module1
Dim Scopes As String() = {CalendarService.Scope.CalendarReadonly}
Dim ApplicationName As String = "Google Calendar API .NET Quickstart"
Sub Main()
Dim credential As UserCredential
Using stream = New FileStream("client_secret.json", FileMode.Open, FileAccess.Read)
Dim credPath As String = "SAME FILE PATH AS IN MY SERVICE"
credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json")
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, New FileDataStore(credPath, True)).Result
Console.WriteLine(Convert.ToString("Credential file saved to: ") & credPath)
End Using
' Create Google Calendar API service.
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential,
.ApplicationName = ApplicationName
})
' Define parameters of request.
Dim request As EventsResource.ListRequest = service.Events.List("primary")
request.TimeMin = DateTime.Now
request.ShowDeleted = False
request.SingleEvents = True
request.MaxResults = 10
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime
' List events.
Dim events As Events = request.Execute()
Console.WriteLine("Upcoming events:")
If events.Items IsNot Nothing AndAlso events.Items.Count > 0 Then
For Each eventItem As Object In events.Items
Dim [when] As String = eventItem.Start.DateTime.ToString()
If [String].IsNullOrEmpty([when]) Then
[when] = eventItem.Start.[Date]
End If
Console.WriteLine("{0} ({1})", eventItem.Summary, [when])
Next
Console.WriteLine("You may now close this window.")
System.Environment.Exit(0)
Else
Console.WriteLine("No upcoming events found.")
End If
Console.Read()
End Sub
End Module
Got it working now, using a service account instead of a user account. No need for dealing with generating credentials or refreshing the token.
Dim serviceAccountEmail As [String] = ConfigurationManager.AppSettings("ServiceAcct")
Dim certificate = New X509Certificate2("key.p12", "notasecret", X509KeyStorageFlags.Exportable)
Dim credential1 As New ServiceAccountCredential(New ServiceAccountCredential.Initializer(serviceAccountEmail) With {
.Scopes = Scopes
}.FromCertificate(certificate))
Dim service = New CalendarService(New BaseClientService.Initializer() With {
.HttpClientInitializer = credential1,
.ApplicationName = ApplicationName
})

Trying to request access token from Google oauth2

i'am trying to get started with dealing googles oauth2
My application vill be so called server application. it should be workin wihtout user input. My code so far(only trying to get access token):
Dim strToken = Request.QueryString("code")
Dim strExchange = "response_type=code"
strExchange += "&redirect_uri=http://xxxx.zzzzz.com/test/google.aspx"
strExchange += "&client_id=xxxx7hju.apps.googleusercontent.com"
strExchange += "&scope=&"
strExchange += "client_secret=yJpGI1yQBCvvxxxxx&grant_type=authorization_code"
Dim url = "https://accounts.google.com/o/oauth2/auth?"
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString(url & strExchange)
Response.Write(result)
This gives me bad reguest (400)
You can try this Article which handles the google calender entries. their you are able to get proper documentation for oauth2.0 authentication technique. Hope that all the values ware taken from App.Config
clientId = ConfigurationManager.AppSettings("client_id").ToString
clientSecret = ConfigurationManager.AppSettings("client_secret").ToString
redirecturi = ConfigurationManager.AppSettings("redirect").ToString
mainUser = ConfigurationManager.AppSettings("mainuser").ToString
Public Sub authorize()
Dim Uri As String = "https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id=" & clientId & "&redirect_uri=" & redirecturi & "&scope=https://www.googleapis.com/auth/calendar&login_hint=" & mainUser & "&include_granted_scopes=true"
Response.Redirect(Uri)
End Sub

Dropnet code in vb not working

I'm trying to use dropnet for file upload on Dropbox in vb, but does not work. Results the following error: Received Response [Unauthorized]: Expected to see [OK]. The HTTP response was [{"error": "Request token not found."}]
Here is my code:
_client = New DropNetClient("xxxxxxx", "xxxxxxx")
Dim login As UserLogin = _client.GetToken()
_client.UserLogin = login
Dim url = _client.BuildAuthorizeUrl()
Process.Start(url)
Dim tokenAcess = _client.GetAccessToken()
_client.GetAccessTokenAsync(Function(accessToken)
_client = New DropNetClient("xxxxxx", "xxxxxx", tokenAcess)
End Function, Function([error]) MessageBox.Show([error].Message)
End Function)
Try
Dim rawData As Byte() = File.ReadAllBytes("c:\image.png")
Dim result As MetaData = _client.UploadFile("/", "image.png", rawData)
MessageBox.Show("Successfully uploaded to Dropbox.", "Uploaded to Dropbox")
Catch dropboxEx As Exception
MessageBox.Show("Error: " + dropboxEx.Message)
End Try

HttpWebrequest with Vb.net

I am trying to download a report off of our company website using VbNet. I have the following code:
Dim hwrequest As Net.HttpWebRequest = Net.HttpWebRequest.Create("https://delph.am.mycompany.com/apps/Reports/ExportDocument11.asp?ID=826&Request=List&OpenType=Edit")
hwrequest.CookieContainer = cookies
hwrequest.Accept = "*/*"
hwrequest.AllowAutoRedirect = False
hwrequest.UserAgent = "http_requester/0.1"
hwrequest.Timeout = 60000
hwrequest.Method = "GET"
Dim hwresponse As Net.HttpWebResponse = hwrequest.GetResponse()
If hwresponse.StatusCode = Net.HttpStatusCode.OK Then
Dim responseStream As IO.StreamReader = _
New IO.StreamReader(hwresponse.GetResponseStream())
responseData = responseStream.ReadToEnd()
End If
But the Response object just returns:
<head><title>Object moved</title></head>
<body><h1>Object Moved</h1>This object may be found <a HREF="/Security/ErrorTrap.asp?
ErrorID=7">here</a>.</body>
and the Location header of the response returns: {X=46,Y=46} and I am not sure what that means.
Can anyone please tell me what I am doing wrong? Thanks in advance.
Try changing hwrequest.AllowAutoRedirect = False to hwrequest.AllowAutoRedirect = True
hwrequest.UserAgent = "http_requester/0.1"
may also be causing you troubles.