Youtube Data API C# - use without requesting user credentials - c#

I would like to use the YouTubeData API in C# - .Net Core - without requesting user credentials.
The only thing I need from this API is to retrieve the information of a playlist, but always when I use it on localhost it is requesting the user's credential.
How can I use this API without any request for credential or using my own token?

If you want to retrieve information (title, thumbnail) of a public playlist, you only need an API key. You only need to authenticate the user if you want to create or edit playlists.
This sample program retrieves the title and the thumbnail of a playlist by id.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
namespace YtbExample
{
internal class PlayList
{
[STAThread]
static void Main(string[] args)
{
try
{
new PlayList().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "YOUR_API_KEY",
ApplicationName = this.GetType().ToString()
});
var listRequest = youtubeService.Playlists.List("snippet");
listRequest.Id = "PLdo4fOcmZ0oXzJ3FC-ApBes-0klFN9kr9";
//Get playlists by channel id
//listRequest.ChannelId = "";
listRequest.MaxResults = 50;
var listResponse = await listRequest.ExecuteAsync();
List<string> playlists = new List<string>();
// Add each result to the list, and then display the lists of
// matching playlists.
foreach (var result in listResponse.Items)
{
playlists.Add(String.Format("Title: {0}, Id: {1}, Thumbnail: {2}", result.Snippet.Title, result.Id, result.Snippet.Thumbnails.Medium.Url));
}
Console.WriteLine(String.Format("{0}\n", string.Join("\n", playlists)));
}
}
}
I hope I could help you!

Related

Google Speech API using NuGet packages

I was trying to use google speech to text API and i read about the NuGet Google APIs packages that can be helpful in speech recognition. Here is the link complete package my code based on documentation provide on https://developers.google.com/api-client-library/dotnet/get_started
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.CloudSpeechAPI.v1beta1.Data;
using Google.Apis.CloudSpeechAPI.v1beta1;
using Google.Apis.Services;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Cloud Speech Api");
try
{
new Program().Run().Wait();
}
catch(AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: "+ e.Message);
}
}
Console.WriteLine("Press any key to continue");
Console.ReadKey();
}
private async Task Run()
{
var service = new CloudSpeechAPIService(new BaseClientService.Initializer
{
ApplicationName ="Speech Recognition",
ApiKey="Api key",
});
Console.WriteLine("Executing a list request...");
var result = await service.Apis.List().ExecuteAsync();
if (result.Items != null)
{
foreach (DirectoryList.ItemsData api in result.Items)
{
Console.WriteLine(api.Id + " - " + api.Title);
}
}
}
}
}
code is showing error in line
var result = await service.Apis.List().ExecuteAsync(); //Error:'APIS ' definition not exist
also i am not sure that code is correct. please help

How can i make that when searching for youtube uploads using google api v3 it will show more then 50 results?

If i make the max results to be 400 it will make exception since it should be between 0-50 to 400.
So for now for testing i did it 50.
How can i make somehow that when it found 50 results and added them to the List it will make then another search for the next 50 results and so on until the end ?
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Upload;
using Google.Apis.Util.Store;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;
namespace Automatic_Record
{
class Youtube_Retrieve_Uploads
{
public Youtube_Retrieve_Uploads()
{
test();
/*try
{
Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}*/
}
private void test()
{
YouTubeService yt = new YouTubeService(new BaseClientService.Initializer() { ApiKey = "AIzaSyDcqx8nMWQL9wshpAs0Q-h0twpGd6R1BJM" });
List<string> videos = new List<string>();
var searchListRequest = yt.Search.List("snippet");
searchListRequest.ChannelId = "UCUE_2qgW-nJOjOlO28uZHtQ";//"UCbe-iLd-TEl3_YQaNSm8dng";
searchListRequest.MaxResults = 50;
var searchListResult = searchListRequest.Execute();
foreach (var item in searchListResult.Items)
{
if (item.Snippet.Title.StartsWith("Gta"))
{
videos.Add("ID: " + item.Id.VideoId);
videos.Add("SNIPPET: " + item.Snippet.Title);
}
}
}
This is working fine but i'm getting only 50 results. I want to get the whole videos starts with Gta but in general i want to get the first 50 results then the next 50 then the next 50 until there are no more results.
You need to loop through pages by using a token to identify which page you're on.
Follow the nextPageToken variable through this example:
var nextPageToken = "";
while (nextPageToken != null)
{
var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
playlistItemsListRequest.PlaylistId = uploadsListId;
playlistItemsListRequest.MaxResults = 50;
playlistItemsListRequest.PageToken = nextPageToken;
// Retrieve the list of videos uploaded to the authenticated user's channel.
var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
foreach (var playlistItem in playlistItemsListResponse.Items)
{
// Print information about each video.
Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
}
nextPageToken = playlistItemsListResponse.NextPageToken;
}
See this link for more help and examples:
https://developers.google.com/youtube/v3/code_samples/dotnet

Searching an uploaded youtube video from my youtube video channel using c#

In Youtube,Please help me in searching the video which I uploaded in my youtube channel..
Here is the code I am trying..
namespace Google.Apis.YouTube.Samples
{
that you have enabled the YouTube Data API for your project.
/// </summary>
internal class Search
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("YouTube Data API: Search");
Console.WriteLine("========================");
try
{
new Search().Run().Wait();
}
catch (AggregateException ex)
{
foreach (var e in ex.InnerExceptions)
{
Console.WriteLine("Error: " + e.Message);
}
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
private async Task Run()
{
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "API KEY ",
ApplicationName = "YouTubeUpload"
});
var searchListRequest = youtubeService.Search.List("snippet");
searchListRequest.Q = "T52cSiV4vV8"; // Replace with your search term.
searchListRequest.MaxResults = 50;
// Call the search.list method to retrieve results matching the specified query term.
var searchListResponse = await searchListRequest.ExecuteAsync();
List<string> videos = new List<string>();
List<string> channels = new List<string>();
List<string> playlists = new List<string>();
foreach (var searchResult in searchListResponse.Items)
{
switch (searchResult.Id.Kind)
{
case "youtube#video":
videos.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.VideoId));
break;
case "youtube#channel":
channels.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.ChannelId));
break;
case "youtube#playlist":
playlists.Add(String.Format("{0} ({1})", searchResult.Snippet.Title, searchResult.Id.PlaylistId));
break;
}
}
Console.WriteLine(String.Format("Videos:\n{0}\n", string.Join("\n", videos)));
Console.WriteLine(String.Format("Channels:\n{0}\n", string.Join("\n", channels)));
Console.WriteLine(String.Format("Playlists:\n{0}\n", string.Join("\n", playlists)));
}
}
}
On running the above code I am getting a 'Bad Request 400' exceptionException screenshot
Am i missing something??
You need set a field "ApiKey" with your APIkey, in Google Console Developer
First, enable the Youtube Data API to your project and then create credentials to get your APIKey.

How to integrate Google Bigquery with c# console application

If it is possible to integrate Google big query with C# console application?.
If yes how we can do, i searched over internet i could not find proper answer for that.
I want connection string format? I have created Client ID from Google Developer console how authentication has done? It is one time configuration or every time we need to login in google account to authenticate.
If there is any sample application to connect sample data it would be helpful.
Thanks,
Selvakumar S
Here's a working sample based on another question in StackOverflow:
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using Google.Apis.Util;
using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace BigQueryConsole
{
public class BigQueryConsole
{
// Put your client ID and secret here (from https://developers.google.com/console)
// Use the installed app flow here.
// Client ID looks like "9999999.apps.googleusercontent.com"
static string clientId = "YOURCLIENTID";
static string clientSecret = "YOURSECRET";
// Project ID is in the URL of your project on the APIs Console
// Project ID looks like "999999";
static string projectId = "YOURPROJECTID";
// Query in SQL-like form
static string query = "SELECT state, count(*) from [publicdata:samples.natality] GROUP BY state ORDER BY state ASC";
public static void Main(string[] args)
{
// Register an authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = clientId;
provider.ClientSecret = clientSecret;
// Initiate an OAuth 2.0 flow to get an access token
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new BigqueryService(auth);
JobsResource j = service.Jobs;
QueryRequest qr = new QueryRequest();
qr.Query = query;
QueryResponse response = j.Query(qr, projectId).Fetch();
foreach (TableRow row in response.Rows)
{
List<string> list = new List<string>();
foreach (TableRow.FData field in row.F)
{
list.Add(field.V);
}
Console.WriteLine(String.Join("\t", list));
}
Console.WriteLine("\nPress enter to exit");
Console.ReadLine();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { BigqueryService.Scopes.Bigquery.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
}
In your answer i could not able to add namespace
"using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;"
But i manage to retrieve results from BigQuery using below code, you need to update Project Name, Project Id and Query.
Download Client ID (I am using Installed Application - Other category ) generate JSON file and add into your Debug folder.
using Google.Apis.Auth.OAuth2;
using System.IO;
using System.Threading;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using System.Data;
using Google.Apis.Services;
using System;
namespace GoogleBigQuery
{
public class Class1
{
private static void Main()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open,
FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { BigqueryService.Scope.Bigquery },
"user", CancellationToken.None).Result;
}
// Create and initialize the Bigquery service. Use the Project Name value
// from the New Project window for the ApplicationName variable.
BigqueryService Service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "PROJECT NAME"
});
string query = "YOUR QUERY";
JobsResource j = Service.Jobs;
QueryRequest qr = new QueryRequest();
qr.Query = query;
DataTable DT = new DataTable();
int i = 0;
QueryResponse response = j.Query(qr, "PROJECT ID").Execute();
if (response != null)
{
int colCount = response.Schema.Fields.Count;
foreach (var Column in response.Schema.Fields)
{
DT.Columns.Add(Column.Name);
}
foreach (TableRow row in response.Rows)
{
DataRow dr = DT.NewRow();
for (i = 0; i < colCount; i++)
{
dr[i] = row.F[i].V;
}
DT.Rows.Add(dr);
}
}
else
{
Console.WriteLine("Response is null");
}
}
}
}
Thanks.

RallyDev - Getting Tasks for Stories using Rally.RestAPI.dll and Service V2.0

I'm pulling data off the Rally server at https://rally1.rallydev.com using C# and the Rally.RestAPI.dll. The server was recently upgraded to webservice v2.0 and I'm having some problems getting tasks for a user story. I know the way child collections are presented were changed in the API with the move to 2.0, but what I'm trying isn't working.
v2.0 removed the ability to return child collections in the same
response for performance reasons. Now fetching a collection will return
an object with the count and the url from which to get the collection
data.A separate request is needed to get to the elements of the
collection.
Here is the code that iterates over user story results, accesses "Tasks" collection on stories and issues a separate request to access individual Task attributes:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
namespace aRestApp_CollectionOfTasks
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "secret", "https://rally1.rallydev.com", "v2.0");
//Set our Workspace and Project scopings
String workspaceRef = "/workspace/11111"; //please replace this OID with an OID of your workspace
String projectRef = "/project/22222"; //please replace this OID with an OID of your project
bool projectScopingUp = false;
bool projectScopingDown = true;
Request storyRequest = new Request("HierarchicalRequirement");
storyRequest.Workspace = workspaceRef;
storyRequest.Project = projectRef;
storyRequest.ProjectScopeUp = projectScopingUp;
storyRequest.ProjectScopeDown = projectScopingDown;
storyRequest.Fetch = new List<string>()
{
"Name",
"FormattedID",
"Tasks",
"Estimate"
};
storyRequest.Query = new Query("LastUpdateDate", Query.Operator.GreaterThan, "2013-08-01");
QueryResult queryStoryResults = restApi.Query(storyRequest);
foreach (var s in queryStoryResults.Results)
{
Console.WriteLine("----------");
Console.WriteLine("FormattedID: " + s["FormattedID"] + " Name: " + s["Name"]);
//Console.WriteLine("Tasks ref: " + s["Tasks"]._ref);
Request taskRequest = new Request(s["Tasks"]);
QueryResult queryTaskResult = restApi.Query(taskRequest);
if (queryTaskResult.TotalResultCount > 0)
{
foreach (var t in queryTaskResult.Results)
{
var taskEstimate = t["Estimate"];
var taskName = t["Name"];
Console.WriteLine("Task Name: " + taskName + " Estimate: " + taskEstimate);
}
}
else
{
Console.WriteLine("no tasks found");
}
}
}
}
}

Categories

Resources