Google cloud translator .net client - c#

I am trying to use google translator api in my .net project. I have installed this library
Install-Package Google.Cloud.Storage.V1
In my code I am trying this
Console.OutputEncoding = System.Text.Encoding.Unicode;
TranslationClient client = TranslationClient.Create();
var response = client.TranslateText("Hello World.", "ru");
Console.WriteLine(response.TranslatedText);
I am getting authentication error, I am really confused how to do that. Can't I just pass an api key into the create function as it is? Or is that an issue?
I see that Create function has an option
GoogleCredential.FromJson(parmas)
But can I pass a json string as it in there? And if yes, what should be the format of that JSON?
Thanks in advance.

Here are sample applications:
https://github.com/GoogleCloudPlatform/dotnet-docs-samples
Authentication info:
https://cloud.google.com/docs/authentication/
https://cloud.google.com/docs/authentication/api-keys
First install NuGet package:
PM> install-package Google.Cloud.Translation.V2 -pre
Here is the absolute simplest code that worked for me.
3 lines of code, not bad :)
var service = new TranslateService(new BaseClientService.Initializer { ApiKey = apiKeyTranslate });
var client = new TranslationClientImpl(service, TranslationModel.ServiceDefault);
var result = client.TranslateText("Hello, World", "sr");
Response.Write(result.TranslatedText);

Refer this link - https://developers.google.com/identity/protocols/application-default-credentials. Download .json file.
Install Google.Cloud.Translation.V2
string credential_path = #"D:\..\..\cred.json";
System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path);

Related

C#: Download Release Asset from Github

I want to download release asset zipball´s in a C# application for further use.
I´m using Octokit to get all release informations from the repo, including the respective browserdownload_url.
After some research it seemed to me, that you cant download this release asset zip´s via octokit, so trying with httpclient as suggested by some SO posts, that were asking these questions.
The release zip´s are on a Github Enterprise Repository, so they require Authentication.
And that is probably my issue, i cant make the authentication work with the httpClient...
The request always responds with Code 404
(which is the regular behaviour if you try by putting the url into the regular browser without logging in)
My actual implementation looks like this
public void DownloadRelease(string dlUrl, string targetPath)
{
var githubToken = "aaaaaaaaaaabbbbbbbbbcccccccccdddddddddd"; //Token created in the github developer settings with all available rights
//dlUrl = https://github.server.de/organization/project/releases/download/v1.2.34/release.zip
using (var client = new System.Net.Http.HttpClient())
{
var credentials = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}:", githubToken);
credentials = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(credentials));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentials);
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", githubToken);
var contents = client.GetByteArrayAsync(dlUrl).Result;
System.IO.File.WriteAllBytes(targetPath, contents);
}
}
Update:
At the End we followed the way of using the curl way:
https://docs.github.com/en/enterprise-server#3.0/rest/reference/repos#download-a-repository-archive-zip
And one more mistake on my end: There were releases without downloadable Asset IDs which i didnt catch in the code.
Based on the documentation (https://docs.github.com/en/enterprise-server#2.22/rest/overview/other-authentication-methods#via-oauth-and-personal-access-tokens) my best guess is, that your crendentials are wrong.
The docs say, the format should be username:token, yet you are only using token followed by a colon : - that doesn't look right to me, either.
So essentially you need to refactor your credentials variable a bit:
var credentials = $"{username}:{githubToken}";

Convert a Kerberos based WindowsIdentity into a Base64 string

If I have the following code:
var token = System.Security.Principal.WindowsIdentity.GetCurrent();
I get a WindowsIdentity that is Kerberos based. I need to make a call with a header like this:
Authorize: Negotiate <Kerberos Token Here>
Is there a way to convert that token object into a Base64 string?
As the maintainer of the Kerberos.NET as mentioned in the other answer, you can always go that route. However, if you want SSO using the currently signed in Windows identity you have to go through Windows' SSPI stack.
Many .NET clients already support this natively using Windows Integrated auth, its just a matter of finding the correct knobs. It's unclear what client you're using so I can't offer any suggestions beyond that.
However if this is a custom client you have to call into SSPI directly. There's a handful of really good answers for explaining how to do that such as: Client-server authentication - using SSPI?.
The aforementioned Kerberos.NET library does have a small wrapper around SSPI: https://github.com/dotnet/Kerberos.NET/blob/develop/Kerberos.NET/Win32/SspiContext.cs
It's pretty trivial:
using (var context = new SspiContext($"host/yourremoteserver.com", "Negotiate"))
{
var tokenBytes = context.RequestToken();
var header = "Negotiate " + Convert.ToBase64String(tokenBytes);
...
}
I could not get this to work, but I was able to get a token using the excellent Kerberos.NET NuGet package. With that I was able to get it like this:
var client = new KerberosClient();
var kerbCred = new KerberosPasswordCredential("UserName", "p#ssword", "domain");
await client.Authenticate(kerbCred);
Console.WriteLine(client.UserPrincipalName);
var ticket = await client.GetServiceTicket("http/ServerThatWantsTheKerberosTicket.domain.net");
return Convert.ToBase64String(ticket.EncodeGssApi().ToArray());
As an aside, I needed help figuring out what the SPN value was for the GetServiceTicket and the project maintainer was fantastically helpful (and fast!).

Nuget api issue

I need to automatically collect the information from the nuget packages of a series of projects. For this purpose I use the API that miscrosoft makes available.
Making the call:
https://api.nuget.org/v3/registration3/epplus/index.json
I get the most recent version: v.4.5.3.1 while on the nuget website it is: v. 5.1.2.
To make the call I use the following code:
static void GetNuGetIndex(Model.Package package)
{
string uri = "https://api.nuget.org/v3/registration3/" + package.Name.ToLower() + "/index.json";
string json = new WebClient().DownloadString(uri);
var packageIndex = JsonConvert.DeserializeObject<JSONModel.NuGetPackageIndex>(json);
int packageIndexItemCounter = 0;
if (packageIndex.Items.Count > 0)
foreach (var packageItem in packageIndex.Items)
{
packageIndexItemCounter++;
List<JSONModel.NuGetPackageItem> items = packageItem.Items;
if (packageItem.Items == null)
{
string lookupjson = new WebClient().DownloadString(packageItem.LookupUrl);
items = JsonConvert.DeserializeObject<JSONModel.NuGetPackageItems>(lookupjson).Items;
}
GetNuGetItems(package, items, package.Name, package.Version, (packageIndexItemCounter.Equals(packageIndex.Items.Count) ? packageItem.Upper : "" ));
}
}
Can anyone give me an explanation of why I have this problem and how can it be solved?
Thanks
I believe this is because this endpoint has been discontinued.
Consulting to the service index api, available at: https://api.nuget.org/v3/index.json (DOC) you can see that the address you are using is not returned.
When consulting the endpoint https://api.nuget.org/v3/registration5-semver1/epplus/index.json provided by the index api, the "upper" field will now return the most current version
I looked here, which suggests you need a different query to return packages:
https://api.nuget.org/v3/registration5-semver1/epplus/index.json
As Kelvin mentioned, that registration hive has been discontinued. I would recommend using the NuGet client SDK to interact with the NuGet API: https://learn.microsoft.com/en-us/nuget/reference/nuget-client-sdk#list-package-versions
If you still would like to use the NuGet APIs directly, I recommend reading through the following resources:
https://learn.microsoft.com/en-us/nuget/api/overview
https://learn.microsoft.com/en-us/nuget/api/service-index
https://learn.microsoft.com/en-us/nuget/api/registration-base-url-resource
TLDR: You have to "discover" the latest location of the registration endpoint using the V3 Service Index API at https://api.nuget.org/v3/index.json.

Retrieving Profiles and connections - Parameter missing?

I use Google's .NET people API (v.1.25) and follow the documentation (https://developers.google.com/people/v1/read-people).
Under
Retrieve Profiles and Connections
Get the user's connections
for .NET the documentation gives this example code snippet:
PeopleResource.ConnectionsResource.ListRequest peopleRequest =
peopleService.People.Connections.List("people/me");
peopleRequest.PersonFields = "names,emailAddresses";
ListConnectionsResponse connectionsResponse = peopleRequest.Execute();
IList<Person> connections = connectionsResponse.Connections;
But PersonFields do not exist in the class ListRequest - nor does it exist in GetRequest as the doc suggests in the next example.
Do I misunderstand something or is there a fault in the docs or in the API?
It seems like you are using an old version of the library. If you browse the .NET documentation from the Install Client Libraries page it shows the version is 1.5.1.
If you browse to the ConnectionsResource.ListRequest documentation it shows that PersonFields exists.
Just use .Fields instead of .PersonFields. Also I had to declare the entire package name (Google.Apis.People.v1.). Example below.
Google.Apis.People.v1.People.PeopleService peopleService;
Google.Apis.People.v1.PeopleResource.ConnectionsResource.ListRequest peopleRequest = peopleService.People.Connections.List("people/me");
peopleRequest.Fields = "names,emailAddresses";
ListConnectionsResponse connectionsResponse = peopleRequest.Execute();
IList<Google.Apis.People.v1.Data.Person> connections = connectionsResponse.Connections;
Hope this helps.

Hammock Package , Tweetsharp and C# Windows Phone 8

I followed this link
http://samjarawan.blogspot.co.uk/2010/09/building-real-windows-phone-7-twitter_18.html
step by step and when I am running my app, I am getting an error i.e. "Error Calling Twitter".
When I searched about it, I found that in this part of code
var client = new RestClient
{
Authority = "https://api.twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true,
SilverlightAcceptEncodingHeader = "gzip",
DecompressionMethods = DecompressionMethods.GZip
};
I need to do some changes, but what changes didn't find any where. Another answer I got that I need to update Hammock and Tweetsharp, but its already updated. Please suggest me and help me out.
Try changing DecompressionMethods or SilverlightAcceptEncodingHeader.

Categories