batch Google contact in dotnet - google-contacts-api

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.

Related

Use refresh token in Google's People API Client Library for .NET

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();

2 step authentication C# Access JSON API via SSIS 2010

I have managed in SSIS 2010 to access a JSON API with basic authentication ... Username and password, using the script below
I need to amend the script below to also include passing credentials of a Client Secret and Client ID
anyone know how to amend this for SSIS 2010. I have tried with no joy, so I have pasted the working code so far
Please help
WebRequest req = WebRequest.Create(#"https://sub.domain.com/api/operations? param=value&param2=value");
req.Method = "GET";
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String (Encoding.Default.GetBytes("username:password"));
//req.Credentials = new NetworkCredential("username", "password");
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
It may depend on how the API is set up and what it's expecting, but in my case, I did this in the creation of an HttpClientHandler:
using System.Net.Http;
using System.Configuration;
...
HttpClientHandler handler = new HttpClientHandler { Credentials = new NetworkCredential(ConfigurationManager.AppSettings["API.UserName"].ToString(), ConfigurationManager.AppSettings["API.Password"].ToString()) };
HttpClient apiClient = new HttpClient(handler);
OR, without using Configurations:
using System.Net.Http;
...
HttpClientHandler handler = new HttpClientHandler { Credentials = new NetworkCredential("MyUserName", "MyPassword") };
HttpClient apiClient = new HttpClient(handler);
Then use the Client to make calls. Here's how I do it:
HttpResponseMessage httpResponse = apiClient.GetAsync(curl).Result;

Autodesk forge viewer gives error after updation of tls1.2

we have uploaded ipt and rvt files into autodesk forge bucket to view files into viewer.
Following segment show how we translate file to view into viewer.html.
Code is executed successfully but, when we open file into viewer, it gives error that file is not viewable.
HttpClient client = new HttpClient();
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + authToken);
client.DefaultRequestHeaders.Add("contenttype", "application/json");
string url = "https://developer.api.autodesk.com/modelderivative/v2/designdata/job";
JObject jsonbody = new JObject
(
new JProperty("input", new JObject
(
new JProperty("urn", urn)
)),
new JProperty("output", new JObject
(
new JProperty("formats", new JArray
(
new JObject
(
new JProperty("type", "svf"),
new JProperty("views", new JArray("3d", "2d"))
)
))
))
);
var ser = JsonConvert.SerializeObject(jsonbody);
StringContent insertString = new StringContent(ser, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(url, insertString).Result;
string result = response.Content.ReadAsStringAsync().Result;
JObject jsonobject = JObject.Parse(result);
urn = (string)jsonobject["urn"];
Response.Redirect("Viewer.html?token=" + authToken + "&urn=" + urn);
Looks like you are redirecting to view the model immediately after calling the translation, while you should have polled for the job status and wait for its completion.
Note that any translation job with our Model Derivative service is asynchronous and will be queued for processing right after they are called. Jobs with large models might take minutes and even hours to complete. See here for API usage details to query the job status.
Also see below for sample .NET code to poll a web service:
Polling a web service

GetStringAsync method not responding

I'm trying to get some custom columns values (longitude,latitude) from ASPNetUsers Table from the DB , When I send a Get request throw browser I get a 200 ok with the requested json .. but when I try to use GetStringAsync to deserialize the response in my xamarin app I don't get any response .
In AccountController class
// POST api/Account/GetUserPostion
[Route("GetUserPostion")]
public LocationDataToPostAsync GetUserPostion()
{
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var manager = new ApplicationUserManager(store);
LocationDataToPostAsync locationData = new LocationDataToPostAsync();
var model = manager.FindById(User.Identity.GetUserId());
locationData.UserId = User.Identity.GetUserId();
if (model.Longitude != null) locationData.Longitude = (double) model.Longitude;
if (model.Latitude != null) locationData.Latitude = (double) model.Latitude;
return locationData;
}
In ApiService class in xamarin forms app
public async Task<LocationDataToPostAsync> GetUserLocationAsync(string accessToken)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var json = await client.GetStringAsync("http://10.0.2.2:45455/api/Account/GetUserPostion");
var location = JsonConvert.DeserializeObject<LocationDataToPostAsync>(json);
return location;
}
It is unclear from your code if the Task is awaited or you are calling .Result or .GetAwaiter().GetResult() on the Task. However, as we found out in the comments adding .ConfigureAwait(false) fixed your issue.
This indicates that the code cannot return to the context it came from, so adding .ConfigureAwait(false) the code doesn't return to the context.
In your case the context is probably the UI thread and when it tries to return the UI thread is blocked.
The most likely scenario why the UI Thread is block is because you called your Task in a wrong manner. If you call it with .Result on the UI thread you are synchronously blocking the UI thread, hence anything that tries to return to the UI thread, will deadlock, since you are blocking that.
The easy fix here is to just add .ConfigureAwait(false) in your code. The better solution would be not to block the UI thread by awaiting the Task.

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.