Google API - Read from google sheets using API key, not OAuth2 - c#

I'm trying to move a project from Java over to c#. The project uses Google Sheets API key, not OAuth2
The documentation on Google's website show only how to do it for OAuth2 - https://developers.google.com/sheets/api/quickstart/dotnet#step_2_set_up_the_sample
The original Java code is
Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, httpRequestInitializer)
.setApplicationName(APPLICATION_NAME)
.build();
Spreadsheet sp = service.spreadsheets().get(spreadsheetId).execute();
List<com.google.api.services.sheets.v4.model.Sheet> sheets = sp.getSheets();
and i'm struggling to convert to c#. I've tried
static string ApplicationName = "#Timetable";
private static readonly String API_KEY = "APIKEY";
static readonly string spreadsheetId = "SPREADSHEET ID";
public void getSheets() {
var service = new SheetsService(new BaseClientService.Initializer()
{
ApplicationName = ApplicationName,
ApiKey = API_KEY,
});
var ssRequest = service.Spreadsheets.Get(spreadsheetId);
Spreadsheet ss = ssRequest.Execute();
List<string> sheetList = new List<string>();
}
but i get the error
System.ArgumentException: 'Invalid Application name Arg_ParamName_Name'
Whats the correct process?

Turns out it doesn't like spaces or special characters in the application name

Related

c# - Google Sheets API v4 - Getting list of all sheets

So at the moment I'm simply trying to get a list of all sheet names available in a google sheets. The sheet is a public sheet
The API key and spreadsheet id match what's online, but I'm getting back Error 400, bad request.
class GoogleAPI {
static string ApplicationName = "Timetable";
private static readonly String API_KEY = "AI**D0";
static readonly string spreadsheetId = "1K**h8";
public void getSheets()
{
var sheetsService = new SheetsService(new BaseClientService.Initializer()
{
ApplicationName = ApplicationName,
ApiKey = API_KEY,
HttpClientFactory = new ProxySupportedHttpClientFactory(),
});
SpreadsheetsResource.GetRequest request = sheetsService.Spreadsheets.Get(spreadsheetId);
Data.Spreadsheet response = request.Execute();
Console.WriteLine(JsonConvert.SerializeObject(response));
}
}
The error from the console
Exception thrown: 'Google.GoogleApiException' in System.Private.CoreLib.dll
An exception of type 'Google.GoogleApiException' occurred in System.Private.CoreLib.dll but was not handled in user code.
The request URL is invalid.
If I echo the details of the request as below
Debug.WriteLine("*********************************");
Debug.WriteLine(sheetsService.BaseUri);
Debug.WriteLine(request.RestPath);
Debug.WriteLine(request.SpreadsheetId);
Debug.WriteLine("***********************************");
I get
https://sheets.googleapis.com/
v4/spreadsheets/{spreadsheetId}
19c3dGbBHhU7EtrCJBa7-bKMn7Jlg3R9xMXOP9HBZDPc
The url giving the correct response is
https://sheets.googleapis.com/v4/spreadsheets/19c3dGbBHhU7EtrCJBa7-bKMn7Jlg3R9xMXOP9HBZDPc?key=AIzaSyDHBvpqlZ5MM04ZrsuGRzpPp_WDI7mS5D0

YouTube Data API v3: deleting videos using a service account: Unauthorized client or scope in request

I'm trying to delete one or more videos using a simple C# app (I intend to use a Windows Service later) and I'm getting this error:
Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"unauthorized_client", Description:"Unauthorized client or scope in request.", Uri:""
at Google.Apis.Requests.ClientServiceRequest`1.Execute() in c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\test\default\Src\GoogleApis\Apis\Requests\ClientServiceRequest.cs:line 93
Uploading videos works perfectly. For both operations, I use the same initialization method:
private static YouTubeService AuthorizeYoutubeService()
{
string serviceAccountEmail = "...#developer.gserviceaccount.com";
string keyFilePath = "Warehouse<...>.p12";
string userAccountEmail = "login#gmail.com";
if (!File.Exists(keyFilePath))
{
System.Windows.Forms.MessageBox.Show("Secret file not found!");
return null;
}
var scope = new string[] { YouTubeService.Scope.Youtube };
var cert = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
try
{
ServiceAccountCredential credential = new ServiceAccountCredential
(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = scope,
User = userAccountEmail
}.FromCertificate(cert));
var service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "warehouse"
});
return service;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return null;
}
}
The difference compared to simply uploading videos, is the defined Scope: YouTubeService.Scope.YoutubeUpload. When I try to delete a video using it, I get an insufficientPermissions (403) error.
So after looking in the documentation I've changed it to YouTubeService.Scope.Youtube.
Here's the code I'm trying to use:
var youtubeService = AuthorizeYoutubeService();
foreach (string id in deleteIds)
{
var videoDeleteRequest = youtubeService.Videos.Delete(id);
var result = videoDeleteRequest.Execute();
}
Where deleteIds is a list of 11 character strings containing IDs of existing videos.
I have YouTube Data API enabled in the developers console.
I've installed the API via NuGet, I don't think there's anything wrong with the packages.
I'm quite new to Google development, and all similar questions were about the calendar API.
I appreciate any help.
What I ended up doing is reseting the list of apps connected to the Google account and setting it up again from scratch. My app was added 2 times for some reason.

Amazon MWS client library C# AWS Access Key Id error

I am using Amazon C# client library to get product information and keep getting an error " The AWS Access Key Id you provided does not exist in our records." (Yes, I tried the seller forum, but didn't get an answer there). When I use the same Access Key using their scratchpad, I get the correct response. I did see this post (Getting 'The AWS Access Key Id you provided does not exist in our records' error with Amazon MWS) and tried swapping the parameters and that didn't work. Here is my C# code. Any help would be greatly appreciated
string AccessKey = "xxx";
string SecretKey = "xxx";
string AppName = "ProductFunctionsApp";
string AppVersion = "1.0";
string ServiceURL = "https://mws.amazonservices.com/Products/2011-10-01";
string SellerId="xxxx";
string MarketPlaceId = "xxx";//US
//right now MWSAuthToken is only if a developer is using a sellers account
MarketplaceWebServiceProductsConfig config = new MarketplaceWebServiceProductsConfig();
config.ServiceURL = ServiceURL;
config.SignatureMethod = "HmacSHA256";
config.SignatureVersion = "2";
MarketplaceWebServiceProductsClient client = new MarketplaceWebServiceProductsClient(AppName, AccessKey, SecretKey, AppVersion, config);
ASINListType type = new ASINListType();
List<string> ASINList = new List<string>();
ASINList.Add("B001E6C08E");
type.ASIN = ASINList;
;
GetCompetitivePricingForASINRequest request = new GetCompetitivePricingForASINRequest();
request.SellerId = SellerId;
request.ASINList = type;
request.MarketplaceId = MarketPlaceId;
GetCompetitivePricingForASINResponse response = client.GetCompetitivePricingForASIN(request);
Some of their API Clients have the class initialization parameters defined in different orders.
So if you copy and paste the initialization code you'll end up with the application name being sent instead of the access key.
var service = new MarketplaceWebServiceProductsClient(
applicationName, applicationVersion, accessKeyId, secretAccessKey, config);
And it's different here:
var service = new FBAInventoryServiceMWSClient(
accessKeyId, secretAccessKey, applicationName, applicationVersion, config);
Just check each one carefully.

Excel Services in SharePoint Online

I have a working code using Excel Services published on on-premises SharePoint:
var _service = new ExcelService { UseDefaultCredentials = true };
Status[] _status;
var _sessionId = _service.OpenWorkbookForEditing("http://<sharepoint url>/<list>/<file>.xlsx", "en-US", "en-US", out _status);
ExcelService is a valid web reference pointing to http://<sharepoint url>/_vti_bin/excelservice.asmx
However, the same code doesn't work when using the Excel Services on SharePoint Online.
I am able to get the API version:
_service.GetApiVersion(out _status);
Excel Web Services (16.0)
But opening a workbook throws a SoapException:
We couldn't find the file you wanted.
I tried passing the credentials:
var _pass = new SecureString();
foreach (char _c in "<SP Online password>".ToCharArray()) { _pass.AppendChar(_c); }
var _cred = new SharePointOnlineCredentials("<SP Online login>", _pass);
var _service = new ExcelService { Credentials = _cred };
And the credentials seem to be valid, i.e. this code works:
// login test
using (ClientContext _sp = new ClientContext("<SP Online url>") { Credentials = _cred })
{
var _web = _sp.Web;
_sp.Load(_web);
_sp.ExecuteQuery();
Console.WriteLine(_web.Title);
}
What am I missing?
It seems it's an authentication issue but it's hard to tell since the error message is pretty opaque. How can I find out more details about the error?
Are Excel Services exposed only for specific licences?
Note, I am able to use Excel REST API but that doesn't work in my scenario (heavy editing).

Google Translate Api V2 C# with multiple phrases

Can anyone show me an example of how to make multiple phrase translation with google translate api?
I am using the following now:
var service = new TranslateService(new BaseClientService.Initializer()
{
ApiKey = "my-key-here",
ApplicationName = "something"
});
string[] translatelist = new string[] { contentToTranslate, "en" };
var response = service.Translations.List(translatelist, "tr").ExecuteAsync();
string translatedtext = response.Result.Translations[0].TranslatedText;
I tried making translatelist 2 dimensional but it didn't work. Thanks in advance.

Categories