Use refresh token in Google's People API Client Library for .NET - google-contacts-api

I am rewriting an app that used Google Contacts API (RIP) to use People API. I already have a refresh token. Previously, I created an instance of the OAuth2Parameters object, and used it to create an instance of the RequestSettings class to be passed to the ContactsRequest constructor
OAuth2Parameters oparams = new OAuth2Parameters
{
AccessToken = tokenData.access_token,
RefreshToken = tokenData.refresh_token,
ClientId = ClientId,
ClientSecret = ClientSecret,
AccessType = "offline",
ApprovalPrompt = "force",
Scope = _contactScope
};
if (string.IsNullOrWhiteSpace(oparams.AccessToken))
{
oparams.AccessToken = "xyz"; //it doesn't matter what this token is, it just can't be blank, it will get refreshed
OAuthUtil.RefreshAccessToken(oparams);
dataStore._storedResponse.access_token = oparams.AccessToken;
}
var settings = new RequestSettings("My App")
{
OAuth2Parameters = oparams
};
if (paging)
{
settings.PageSize = 50;
settings.AutoPaging = true;
}
return new ContactsRequest(settings);
I cannot figure out how to do the same in the new world of People API. I obviously need to use PeopleServiceService object, but its constructor takes an instance of the Initializer object, and I don't know out how I can initialize it with the refresh token and (possibly) access token.

Here's the official tutorial on how to do authentication with the .NET library for all Google APIs:
https://developers.google.com/api-client-library/dotnet/guide/aaa_oauth
Here's a useful snippet from it that will also help with persisting the refresh token to a file and use it in future authentication attempts:
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { BooksService.Scope.Books },
"user", CancellationToken.None, new FileDataStore("Books.ListMyLibrary"));
}
// Create the service.
var service = new BooksService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Books API Sample",
});
var bookshelves = await service.Mylibrary.Bookshelves.List().ExecuteAsync();

Related

Http get request giving forbidden response in windows phone 8

HTTP "POST" data with login credentials to the BASEn server using API URL, in response it is giving a status 200, OK.
var values = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("mode", "login"),
new KeyValuePair<string, string>("user", logintxtbx.Text),
new KeyValuePair<string, string>("password", passtxtbx.Text)
};
httpClient = new HttpClient(new HttpClientHandler());
HttpResponseMessage response = await httpClient.PostAsync("https://xx-yyy.com/auth", new FormUrlEncodedContent(values)); var strin = response.StatusCode.ToString();
var responseString = await response.Content.ReadAsStringAsync();
MessageBox.Show("login Success");
GetFullResponse(httpClient);
}
After validating my credentials, the server will create a session to me if i try to do "GET" HTTP by using another urls, it should gives my required data but this thing was not happening, every time iam getting "403" forbidden response.
This is the code using for "GET" data.
var uri = new Uri("https://xx-yyy.com/_ua/web/web/v1/xyz/?xyx=1431369000000&end=1431436740000&_=1431436741550");
var Response = await httpClient.GetAsync(uri);
var statusCode = Response.StatusCode;
Response.EnsureSuccessStatusCode()
var ResponseText = await Response.Content.ReadAsStringAsync();
i don't know whats wrong, i was doing.
Can any one suggest me how can i do this to be happen.
var handler = new HttpClientHandler();
var cookieContainer = handler.CookieContainer;
var client = new HttpClient(handler);
store cookies using cookieContainer and use them to authenticate the future calls using the same way as on web.
Store the cookies to the phone using IsolatedStorageSettings
Reference for more details here

batch Google contact in dotnet

I cannot find any sample for batching contact insertions in dotnet.
We're using nuget package : Install-Package Google.GData.Contacts
For appointments we're batching in this way:
BatchRequest batch = new BatchRequest(service);
Google.Apis.Calendar.v3.EventsResource.InsertRequest ir = new EventsResource.InsertRequest(aservice, theEvent, userName);
batch.Queue<Google.Apis.Calendar.v3.Data.Event>(ir,
( error, i, message) =>
{
// code here
});
With the Google contacts apis, we do not find any InsertRequest object.
We're using the ContactRequest class for Oauth integration.
RequestSettings settings = new RequestSettings(ApplicationName);
string token = GetOauthAccessToken();
OAuth2Parameters oauth2 = new OAuth2Parameters();
oauth2.AccessToken = token;
settings.OAuth2Parameters = oauth2;
GetNextContactService = new ContactsRequest(settings);
Note: in the past, we were using the ContactService class with which we managed to batch inserts, but with this class we did not manage to attach an oauth token like in the code above.
old code:
PushContactService = new ContactsService("MigrationAsAService");
GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "theappname");
requestFactory.ConsumerKey = this.ConnectorSettings.ConsumerKey;
requestFactory.ConsumerSecret = this.ConnectorSettings.ConsumerSecret;
PushContactService.RequestFactory = requestFactory;
ContactsFeed feed = new ContactsFeed(
new Uri(PushContactsURI),
PushContactService
);
feed.BatchData = new GDataBatchFeedData();
feed.BatchData.Type = GDataBatchOperationType.insert;
You should be able to use the ContactsService class with OAuth2, by creating a GOAuth2RequestFactory and setting that as the service's request factory.

Google and .Net windows console progeam

I need to write a windows console program that will take the results from a SQL query, and dump the results into a excel sheet. We are moving away from Microsoft, and towards Google technology. So I need to create a worksheet, dump the results in that file, and store on drive.
Is the sdk the best way to go on this? Am I going to need the SDK for Drive and for Worksheetes? I also need to have the console run on it's own, no user interaction at all. I have been working with this sample below, and got it to work. I'm not sure if I'm going in the right direction with this. Any advice would be great!
using System;
using System.Threading;
using System.Threading.Tasks;
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v2;
using Google.Apis.Drive.v2.Data;
using Google.Apis.Services;
using Google.Apis.Discovery;
using Google.GData.Client;
using Google.GData.Extensions;
namespace GoogleDriveSamples
{
class DriveCommandLineSample
{
static void Main(string[] args)
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "xxxxxxxxxx-bn0vi796pn7tog7utb9pt6pmptl8cpsq.apps.googleusercontent.com",
ClientSecret = "FwuyHxBAj2Z1",
},
new[] { DriveService.Scope.Drive },
"user",
CancellationToken.None).Result;
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Credit Q",
});
File body = new File();
body.Title = "My document";
body.Description = "A test document";
body.MimeType = "text/plain";
byte[] byteArray = System.IO.File.ReadAllBytes("FTP.txt");
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
request.Upload();
File file = request.ResponseBody;
Console.WriteLine("File id: " + file.Id);
Console.WriteLine("Press Enter to end this process.");
Console.ReadLine();
}
}
}
You can do it in google apps script in about 5 lines of code.
Lok at the official samples. Basically use spreadsheetApp and jdbc.

Send Cookies with HTTPWebRequestion through WP8 App

I have to send the cookies to server for every subsequent HTTPWebRequest. My code goes below.
class APIManager
{
CookieContainer cookieJar = new CookieContainer();
CookieCollection responseCookies = new CookieCollection();
private async Task<string> httpRequest(HttpWebRequest request)
{
string received;
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory
.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
using (var responseStream = response.GetResponseStream())
{
using (var sr = new StreamReader(responseStream))
{
cookieJar = request.CookieContainer;
responseCookies = response.Cookies;
received = await sr.ReadToEndAsync();
}
}
}
return received;
}
public async Task<string> Get(string path)
{
var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
request.CookieContainer = cookieJar;
return await httpRequest(request);
}
public async Task<string> Post(string path, string postdata)
{
var request = WebRequest.Create(new Uri(path)) as HttpWebRequest;
request.Method = "POST";
request.CookieContainer = cookieJar;
byte[] data = Encoding.UTF8.GetBytes(postdata);
using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
await requestStream.WriteAsync(data, 0, data.Length);
}
return await httpRequest(request);
}
}
Every time i ask for the question people say that i have to set the cookie container with request by following code line.
request.CookieContainer = cookieJar;
and i used it but still server returns the 'token does not match' error. Do i need to talk to the vendor for it?
Following image shows my problem and requirement.
I haven't seen you do something with the cookieJar !
//Create the cookie container and add a cookie.
request.CookieContainer = new CookieContainer();
// This example shows manually adding a cookie, but you would most
// likely read the cookies from isolated storage.
request.CookieContainer.Add(new Uri("http://api.search.live.net"),
new Cookie("id", "1234"));
cookieJar in your APIManager is a member, everytime your instance APIManager, the cookieJar is a new instance. you need to make sure cookieJar contains what the website needs.
you can have a look at this How to: Get and Set Cookies

GetRequestToken is not working in TweetSharp on Windows Phone

I can't use GetRequestToken in TwitterService anymore
and also GetAccessToken!
TwitterService service = new TwitterService("ConsumerKey", "ConsumerKeySecret");
service.GetRequestToken(Constants.CallbackUri, (request, response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
Request = request;
var uri = service.GetAuthorizationUri(request);
Dispatcher.BeginInvoke(() => AuthBrowser.Navigate(uri));
}
});
it gives me:
'TweetSharp.TwitterService' does not contain a definition for 'GetRequestToken' and no extension method 'GetRequestToken' accepting a first argument of type 'TweetSharp.TwitterService' could be found (are you missing a using directive or an assembly reference?)
I solved it by getting Request Token via Hammock(https://github.com/danielcrenna/hammock)
and here is the code
/// <summary>
/// Gets Twitter Request Token
/// </summary>
private void GetTwitterToken()
{
var credentials = new OAuthCredentials
{
Type = OAuthType.RequestToken,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = "Your Consumer Key",
ConsumerSecret = "Your Consumer Secret",
Version = TwitterSettings.OAuthVersion,
CallbackUrl = TwitterSettings.CallbackUri
};
var client = new RestClient
{
Authority = "https://api.twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true,
};
var request = new RestRequest
{
Path = "/request_token"
};
client.BeginRequest(request, new RestCallback(TwitterRequestTokenCompleted));
}
and
private void TwitterRequestTokenCompleted(RestRequest request, RestResponse response, object userstate)
{
_oAuthToken = GetQueryParameter(response.Content, "oauth_token");
_oAuthTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret");
var authorizeUrl = TwitterSettings.AuthorizeUri + "?oauth_token=" + _oAuthToken;
if (String.IsNullOrEmpty(_oAuthToken) || String.IsNullOrEmpty(_oAuthTokenSecret))
{
Dispatcher.BeginInvoke(() => MessageBox.Show("error calling twitter"));
return;
}
Dispatcher.BeginInvoke(() => AuthBrowser.Navigate(new Uri(authorizeUrl)));
}
and You can do the same with access token.
Have you checked to see if the TweetSharp Library supports Windows Phone 8?