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
Related
I'm trying to test the Computer Vision SDK for .NET.
For that i've created a Computer vision resource in azure.
I create a project in .NET6 and follow the Microsoft guide to implement the api call.
But when i reach the code line:
var textHeaders = await client.ReadAsync(urlFile);
i'm getting the exception:
ComputerVisionOcrErrorException: Operation returned an invalid status code 'BadRequest'
This is the complete code:
public static void ComputerVisionPOC()
{
// Add your Computer Vision subscription key and endpoint
const string subscriptionKey = "xxxxxxx";
const string endpoint = #"https://xxxx.cognitiveservices.azure.com/";
const string readTextUrlImage = "https://drive.google.com/file/d/xxxxxxxx/view?usp=sharing";
var client = Authenticate(endpoint, subscriptionKey);
// Extract text (OCR) from a URL image using the Read
ReadFileUrl(client, readTextUrlImage).Wait();
}
public static ComputerVisionClient Authenticate(string endpoint, string key)
{
var client =
new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
{ Endpoint = endpoint };
return client;
}
public static async Task ReadFileUrl(ComputerVisionClient client, string urlFile)
{
try
{
var textHeaders = await client.ReadAsync(urlFile);
// After the request, get the operation location (operation ID)
var operationLocation = textHeaders.OperationLocation;
Thread.Sleep(2000);
// Retrieve the URI where the extracted text will be stored from the Operation-Location header.
// We only need the ID and not the full URL
const int numberOfCharsInOperationId = 36;
var operationId = operationLocation[^numberOfCharsInOperationId..];
// Extract the text
ReadOperationResult results;
Console.WriteLine($"Extracting text from URL file {Path.GetFileName(urlFile)}...");
Console.WriteLine();
do
{
results = await client.GetReadResultAsync(Guid.Parse(operationId));
} while ((results.Status == OperationStatusCodes.Running ||
results.Status == OperationStatusCodes.NotStarted));
// Display the found text.
Console.WriteLine();
var textUrlFileResults = results.AnalyzeResult.ReadResults;
foreach (var page in textUrlFileResults)
{
foreach (var line in page.Lines)
{
Console.WriteLine(line.Text);
}
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
I will really apreciate any help on this!
A Bad request error(400) occurs when a request which has been sent to the website server is incorrect/mistyped or corrupt and if the server receiving the request fails to understand it.
There is a possibility that the URL which has been used in the code could be wrong/mistyped.
Re-check the URL in readTextUrlImage and provide the valid one.
const string readTextUrlImage = "https://drive.google.com/file/d/xxxxxxxx/view?usp=sharing";
I have reproduced the same code with valid URL and got the expected result.
Output:
can someone help me with "Invalid space resource name in request." error?
I created service account/application in Google Cloud
I created Google Chat API
I created space "server" and added my application to space
using Google.Apis.Auth.OAuth2;
using Google.Apis.HangoutsChat.v1;
using Google.Apis.Services;
Console.WriteLine("START");
SendMessage("spaces/server", "Hello Jozef");
Console.WriteLine("END");
void SendMessage(string space, string message, string thread = null)
{
try
{
var jsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "E://serverapplication-92ed800d27af.json");
using (var stream = new FileStream(jsonPath, FileMode.Open, FileAccess.Read))
{
string[] scopes = new[] { "https://www.googleapis.com/auth/chat.bot" };
var credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
var service = new HangoutsChatService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "ServerApplication"
});
var pubSubMessage = new Google.Apis.HangoutsChat.v1.Data.Message
{
Text = message,
Thread = new Google.Apis.HangoutsChat.v1.Data.Thread() { Name = thread },
Sender = new Google.Apis.HangoutsChat.v1.Data.User() { Name = "ServerApplication", DisplayName = "ServerApplication" },
};
SpacesResource.MessagesResource.CreateRequest req = new SpacesResource.MessagesResource(service).Create(pubSubMessage, space);
var result = req.Execute();
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
It seems that application and credentials are ok. What can cause this error? Is it correct if I created a "server" space and added this application there?
The service chat has thrown an exception.
HttpStatusCode is BadRequest.
Google.Apis.Requests.RequestError
Invalid space resource name in request. [400]
Errors [
Message[Invalid space resource name in request.] Location[ - ] Reason[badRequest] Domain[global]
]
Google.GoogleApiException: The service chat has thrown an exception. HttpStatusCode is BadRequest. Invalid space resource name in request.
at Google.Apis.Requests.ClientServiceRequest`1.ParseResponse(HttpResponseMessage response)
at Google.Apis.Requests.ClientServiceRequest`1.Execute()
at Program.<<Main>$>g__SendMessage|0_0(String space, String message, String thread) in E:\TestGoogleChat\Program.cs:line 37
Thank you for any ideas or observations
Your calling the method wrong. All methods need to be called though the service object.
This will get you a list of spaces.
var listOfSpaces = service.Spaces.List().Execute();
Then to create a message you add it to the space
var request = service.Spaces.Messages.Create(new Message(), "spaces/{SpaceId}");
var response = request.Execute();
spaces create
As stated in the docs for spaces.create
Developer Preview: Available as part of the Google Workspace Developer Preview Program, which grants early access to certain features.
As this method is not fully available this means that the client library will not be generated with this method. If you do have access to that method you would need to send the request yourself.
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
I want to use Google Nuget package for shortening URLs.
I included all the required files
public string shortenIt(string url)
{
UrlshortenerService service = new UrlshortenerService(new BaseClientService.Initializer()
{
ApiKey = "*************************",
ApplicationName = "***************",
});
Url response = service.Url.Insert(new Url { LongUrl = url }).Execute();
return response.Id;
}
I am getting the following error on
Url response = service.Url.Insert(new Url { LongUrl = url }).Execute();
Error:
JsonReaderException: Error parsing NaN value. Path '', line 1, position 1
I would be please to know the solution..Thanks
Google's URL shortener is no longer available, you should move to using Google's Firebase Dynamic Links.
Source: https://developers.googleblog.com/2018/03/transitioning-google-url-shortener.html
I'm using the sample code from https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi. When I receive an authorization code the method ConfidentialClientApplication.AcquireTokenByAuthorizationCodeAsync in the callback method OnAuthorizationCodeReceived throws the exception:
System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type Microsoft.Identity.Client.Internal.OAuth2.TokenResponse. Encountered unexpected character '<'.
Here's a snippet of the sample code:
/*
* Callback function when an authorization code is received
*/
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification notification)
{
// Extract the code from the response notification
var code = notification.Code;
string signedInUserID = notification.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
TokenCache userTokenCache = new MSALSessionCache(signedInUserID, notification.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
ConfidentialClientApplication cca = new ConfidentialClientApplication(ClientId, Authority, RedirectUri, new ClientCredential(ClientSecret), userTokenCache, null);
try
{
AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(code, Scopes);
}
catch (Exception ex)
{
//TODO: Handle
throw;
}
}
The issue was that the Authority URL that was being passed to ConfidentialClientApplicationwas invalid and was returning a HTTP 404 not found error. The Authority URL is created using the Tenant and DefaultPolicy values. In my case the Tenant and DefaultPolicy properties were being initialized after the Authority property resulting in the URL to not contain the proper values.
public static string Authority = String.Format(AadInstance, Tenant, DefaultPolicy);
...
public static string Tenant = ConfigurationManager.AppSettings["ida:Tenant"];
public static string DefaultPolicy = SignUpSignInPolicyId;
This resulted in the Authority URL to have the value:
https://login.microsoftonline.com/tfp///v2.0/.well-known/openid-configuration
vs
https://login.microsoftonline.com/tfp/my_tenant.onmicrosoft.com/my_policy/v2.0/.well-known/openid-configuration
During my initial search I found this issue reported to
https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/issues/720 but no solution. I've posted my answer there to help anyone in the future.