Google Translate Api V2 C# with multiple phrases - c#

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.

Related

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

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

Youtube API List channels other than Google

I am sitting hours and cannot find the answer for issue I have. I am using latest Youtube API for .NET
The problem I wanna solve is to take information - mostly id from any channel for Youtube channel I give the name.
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "key",
ApplicationName = "appName"
});
var asd = youtubeService.Channels.List(new Repeatable<string>(new List<string> { "snippet,contentDetails,statistics" }));
asd.ForUsername = "Mauzer";
var dsa = await asd.ExecuteAsync();
To achieve that I am using ForUsername property. However the result of call does not always return the result.
For example if I type "Google" as Username it return the Google`s channel. However it doesn't work for all channels I can find exploring Youtube.
Anyone is familiar and know what I am missing?

Youtube v3 API captions downloading

I'm trying to download captions from some videos on Youtube using their nuget package. Here's some code:
var request = _youtube.Search.List("snippet,id");
request.Q = "Bill Gates";
request.MaxResults = 50;
request.Type = "video";
var results = request.Execute();
foreach (var result in results.Items)
{
var captionListRequest = _youtube.Captions.List("id,snippet", result.Id.VideoId);
var captionListResponse = captionListRequest.Execute();
var russianCaptions =
captionListResponse.Items.FirstOrDefault(c => c.Snippet.Language.ToLower() == "ru");
if (russianCaptions != null)
{
var downloadRequest = _youtube.Captions.Download(russianCaptions.Id);
downloadRequest.Tfmt = CaptionsResource.DownloadRequest.TfmtEnum.Srt;
var ms = new MemoryStream();
downloadRequest.Download(ms);
}
}
When the Download method is called I'm getting a weird Newtonsoft.JSON Exception that says:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: T. Path '', line 0, position 0.'
at Newtonsoft.Json.JsonTextReader.ParseValue()
I've read some other threads on captions downloading problems and have tried to change my authorization workflow: first I've tried to use just the ApiKey but then also tried OAuth. Here's how it looks now:
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "CLIENT_ID",
ClientSecret = "CLIENT_SECRET"
},
new[] { YouTubeService.Scope.YoutubeForceSsl },
"user",
CancellationToken.None,
new FileDataStore("Youtube.CaptionsCrawler")).Result;
_youtube = new YouTubeService(new BaseClientService.Initializer
{
ApplicationName = "LKS Captions downloader",
HttpClientInitializer = credential
});
So, is it even possible to do what I'm trying to achieve?
P.S. I was able to dig deep into the youtube nuget package and as I see, the actual message, that I get (that Newtonsoft.JSON is trying to deserialize, huh!) is "The permissions associated with the request are not sufficient to download the caption track. The request might not be properly authorized, or the video order might not have enabled third-party contributions for this caption."
So, do I have to be the video owner to download captions? But if so, how do other programs like Google2SRT work?
Found this post How to get "transcript" in youtube-api v3
You can get them via GET request on: http://video.google.com/timedtext?lang={LANG}&v={VIDEOID}
Example:
http://video.google.com/timedtext?lang=en&v=-osCkzoL53U
Note that they should have subtitles added, will not work if auto-generated.

Fetching google images using htmlagilitypack

I would like to execute a query on google images to fetch images using htmlagilitypack in c#.
For this I used an xpath request to the image
//*[#id="rg_s"]/div[1]/a/img
But it fails to fetch the image that way. What could be the correct way of doing this?
you can try this too : Here its possible to get the links of images by following
var links = HtmlDocument.DocumentNode.SelectNodes("//a").Where(a => a.InnerHtml.Contains("<img")).Select(b => b.Attributes["href"].Value).ToList();
foreach(var link in links)
{
// you can save the link or do your process here
}
Google keeps found images in div tags with class rg_di. Here is a query to get all links to images:
var links = hdoc.DocumentNode.SelectNodes(#"//div[#class='rg_di']/a")
.Select(a => a.GetAttributeValue("href", ""));
Searching google programmatically outside of their API's is against the TOS. Consider Google Custom Search or Bing Search API, both of which have established JSON and SOAP interfaces.
Both are free for a couple thousand queries per month and comply with the service's TOS.
Edit: Examples of using Bing API with C# below:
const string bingKey = "[your key here]";
var bing = new BingSearchContainer(new Uri("https://api.datamarket.azure.com/Bing/Search/"))
{
Credentials = new NetworkCredential(bingKey, bingKey)
};
var query = bing.Web("Jon Gallant blog", null, null, null, null, null, null, null);
var results = query.Execute();
foreach(var result in results)
{
Console.WriteLine(result.Url);
}
Console.ReadKey();
Google custom search API:
string apiKey = "Your api key";
string cx = "Your custom search engine id";
string query = "Your query";
var svc = new Google.Apis.Customsearch.v1.CustomsearchService(new BaseClientService.Initializer { ApiKey = apiKey });
var listRequest = svc.Cse.List(query);
listRequest.Cx = cx;
var search = listRequest.Fetch();
foreach (var result in search.Items)
{
Response.Output.WriteLine("Title: {0}", result.Title);
Response.Output.WriteLine("Link: {0}", result.Link);
}

Google plus language programming using people.list

as a new researcher I am trying to get information about relations among people on G+. I want to get other's circle list for some research purpose. It seems that the G+ API offers a web version to use people.list with a OAuth2 token. My question is, does people.list support programming language such as c#, java? I tried with c# but it seems to be blocked by the server.
Is there is a way to apply people.list in c#,java etc? If yes, are there some samples? Or someone provide some open codes to fullfill similar functions?
thanks very much.
the following is my related c# code:
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = credentials.ClientId,
ClientSecret = credentials.ClientSecret
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
var servicelist = new PlusService(new BaseClientService.Initializer()
{
Authenticator = auth
});
string userId = "********************";
PeopleResource.ListRequest circle = servicelist.People.List(userId, new PeopleResource.Collection());
circle.MaxResults = 5;
PeopleFeed danielfeed = circle.Fetch();
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
IAuthorizationState state = new AuthorizationState(new[] { TasksService.Scopes.Tasks.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
return arg.ProcessUserAuthorization(authCode, state);
}
}
The program goes wrong at "PeopleFeed danielfeed = circle.Fetch();" I think I have already passed the OAuth token to the people.list function by variable "auth". Can you give me some advices?
Google's People:list API's documentation is here. The entire API is RESTful, and does not block any language.
You can use C#, and just need to learn how to consume a REST API in C#. The C# class you will want to use is the HttpClient class. It is very well documented here and there are plenty of tutorials online, as well as here on SO.

Categories