function to search in youtube - c#

I write function for search in youtube.
I create project on "console.developers.google.com" . the name project is youtubesearch and I get apiKey.
I have the error
"An unhandled exception of type
'Google.GData.Client.InvalidCredentialsException' occurred in
Google.GData.Client.dll"
at foreach loop
my code is:
private void getsearch(string serchFor)
{
YouTubeRequestSettings setting = new YouTubeRequestSettings("youtubesearch", "APIkey","ise34857#gmail.com","password for my email");
YouTubeRequest Request = new YouTubeRequest(setting);
YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
query.OrderBy = "viewCount";
query.Query = serchFor;
query.SafeSearch = YouTubeQuery.SafeSearchValues.Moderate;
Feed<Video> videofeed = Request.Get<Video>(query);
videoLookUp = new Dictionary<string, string>();
foreach (Video v in videofeed.Entries)
{
if (v.Media.Content!=null)
{
Console.WriteLine(v.Title);
Console.WriteLine(v.Media.Content.Url);
comboBox1.Items.Add(v.Title);
videoLookUp.Add(v.Title,v.Media.Content.Url);
}
}
}
Please check object setting if my parameter is right and tell me if I had any proplem in my code

Although the YouTube Data API (v2) has been officially deprecated, you can check in this documentation on how to properly authenticate your application using .NET client library. It also shows here how to properly use the YouTubeRequestSettings object.
To perform any operation using the YouTube API, you create a YouTubeRequestSettings object, which specifies the authentication information and authentication scheme to be used. With that object, you then create a YouTubeRequest object that you will use to actually perform the operations. (If you do not specify authentication information when creating the YouTubeRequestSettings object, then you will only be able to use the YouTubeRequest object to perform operations that do not require authentication.
YouTubeRequestSettings settings =
new YouTubeRequestSettings("example app", clientID, developerKey);
YouTubeRequest request = new YouTubeRequest(settings);
For more information and sample code, check this tutorial.

Related

How can I use a google speech to text api key in deployed WPF app?

I have created a C# WPF app that uses google Speech-to-Text API. Currently, on my development machine, I have added an environment variable in windows, which references to the JSON file that google gave me.
Will I need to create that environment variable to every machine I deploy my app or is there a way to somehow store the JSON key on a server and reference it from there?
Possibly, Passing Credentials Using Code helps you.
This is the code copied from there:
// Some APIs, like Storage, accept a credential in their Create()
// method.
public object AuthExplicit(string projectId, string jsonPath)
{
// Explicitly use service account credentials by specifying
// the private key file.
var credential = GoogleCredential.FromFile(jsonPath);
var storage = StorageClient.Create(credential);
// Make an authenticated API request.
var buckets = storage.ListBuckets(projectId);
foreach (var bucket in buckets)
{
Console.WriteLine(bucket.Name);
}
return null;
}
// Other APIs, like Language, accept a channel in their Create()
// method.
public object AuthExplicit(string projectId, string jsonPath)
{
LanguageServiceClientBuilder builder = new LanguageServiceClientBuilder
{
CredentialsPath = jsonPath
};
LanguageServiceClient client = builder.Build();
AnalyzeSentiment(client);
return 0;
}

SubscriptionNotFound: The subscription 'resourceGroups' could not be found

I'm trying to follow the Resource group authenticate service principal to be able to access some resource manager stuff. But when trying to do anything, I get the following error:
SubscriptionNotFound: The subscription 'resourceGroups' could not be found.
Using the C# code in the article to get an access token, and then calling the follow methods:
var dnsClient = new DnsManagementClient(new Microsoft.Azure.TokenCloudCredentials(result.AccessToken));
var zone = dnsClient.Zones.CreateOrUpdate("someresourcegroup", "mydomain.com", new Microsoft.Azure.Management.Dns.Models.ZoneCreateOrUpdateParameters {
IfNoneMatch = "*",
Zone = new Microsoft.Azure.Management.Dns.Models.Zone {
Name = "mydomain.com",
Location = "northeurope"
}
});
Any idea what I'm doing wrong? I've created a service principal as a Contributor, so permissions shouldn't be a problem?
The error message says The subscription 'resourceGroups' could not be found, please try specify your subscriptionid when creating the TokenCloudCredentials object.
var dnsClient = new DnsManagementClient(new Microsoft.Azure.TokenCloudCredentials("your_subscriptionid", result.AccessToken));
Tested from my side and it works.

Error when calling any method on Service Management API

I'm looking to start an Azure runbook from a c# application which will be hosted on an Azure web app.
I'm using certificate authentication (in an attempt just to test that I can connect and retrieve some data)
Here's my code so far:
var cert = ConfigurationManager.AppSettings["mgmtCertificate"];
var creds = new Microsoft.Azure.CertificateCloudCredentials("<my-sub-id>",
new X509Certificate2(Convert.FromBase64String(cert)));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group-id>", "<automation-account-name>");
Every time I run this, no matter what certificate I use I get the same error:
An unhandled exception of type 'Hyak.Common.CloudException' occurred in Microsoft.Threading.Tasks.dll
Additional information: ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I've tried downloading the settings file which contains the automatically generated management certificate you get when you spin up the Azure account... nothing I do will let me talk to any of the Azure subscription
Am I missing something fundamental here?
Edit: some additional info...
So I decided to create an application and use the JWT authentication method.
I've added an application, given the application permissions to the Azure Service Management API and ensured the user is a co-administrator and I still get the same error, even with the token...
const string tenantId = "xx";
const string clientId = "xx";
var context = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantId));
var user = "<user>";
var pwd = "<pass>";
var userCred = new UserCredential(user, pwd);
var result = context.AcquireToken("https://management.core.windows.net/", clientId, userCred);
var token = result.CreateAuthorizationHeader().Substring("Bearer ".Length); // Token comes back fine and I can inspect and see that it's valid for 1 hour - all looks ok...
var sub = "<subscription-id>";
var creds = new TokenCloudCredentials(sub, token);
var client = new AutomationManagementClient(creds, new Uri("https://management.core.windows.net/"));
var content = client.Runbooks.List("<resource-group>", "<automation-id>");
I've also tried using other Azure libs (like auth, datacentre etc) and I get the same error:
ForbiddenError: The server failed to authenticate the request. Verify that the certificate is valid and is associated with this subscription.
I'm sure it's just 1 tickbox I need to tick buried somewhere in that monolithic Management Portal but I've followed a few tutorials on how to do this and they all end up with this error...
public async Task StartAzureRunbook()
{
try
{
var subscriptionId = "azure subscription Id";
string base64cer = "****long string here****"; //taken from http://stackoverflow.com/questions/24999518/azure-api-the-server-failed-to-authenticate-the-request
var cert = new X509Certificate2(Convert.FromBase64String(base64cer));
var client = new Microsoft.Azure.Management.Automation.AutomationManagementClient(new CertificateCloudCredentials(subscriptionId, cert));
var ct = new CancellationToken();
var content = await client.Runbooks.ListByNameAsync("MyAutomationAccountName", "MyRunbookName", ct);
var firstOrDefault = content?.Runbooks.FirstOrDefault();
if (firstOrDefault != null)
{
var operation = client.Runbooks.Start("MyAutomationAccountName", new RunbookStartParameters(firstOrDefault.Id));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Also in portal:
1) Application is multitenant
2) Permissions to other applications section - Windows Azure Service Manager - Delegated permissions "Access Azure Service Management(preview)"
Ensure that your Management certificate has private key and was not made from the .CER file. The fact that you're not supplying a password when generating the X509Certificate object makes me think you're using public key only
Ensure that your Managemnet's certificate public key (.CER file) has been uploaded to the Azure management portal (legacy version, Management Certificate area)
Use CertificateCloudCredentials and not any other credential type of an object
Ok, stupid really but one of the tutorials I followed suggested installing the prerelease version of the libs.
Installing the preview (0.15.2-preview) has fixed the issue!

Google plus API returns error code 401 when publishing

I am using Google Plus API for .Net for implementing sharing on google plus using WebAuthenticationBroker. It returns a token after the user gets logged in but when I send a moments post request it returns error 401.
My code on clicking on image is
String GoogleURL = "https://accounts.google.com/o/oauth2/auth?client_id=xxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com&redirect_uri=http://www.google.com&response_type=code&scope=" + Uri.EscapeDataString("https://www.googleapis.com/auth/plus.stream.write https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.login");
PlusService service = new PlusService();
System.Uri StartUri = new Uri(GoogleURL);
System.Uri EndUri = new Uri("https://accounts.google.com/o/oauth2/approval?");
WebAuthenticationBroker.AuthenticateAndContinue(new Uri(GoogleURL), EndUri);
now when it returns after authenticating I have called method upload on google in continue which is as follows--
PlusService service = new PlusService();
Moment body = new Moment();
ItemScope itemScope = new ItemScope();
itemScope.Id = "replacewithuniqueforaddtarget";
itemScope.Image = "http://www.google.com/s2/static/images/GoogleyEyes.png";
itemScope.Type = "";
itemScope.Description = "The description for the action";
itemScope.Name = "An example of add activity";
body.Object = itemScope;
body.Type = "http://schema.org/AddAction";
MomentsResource.InsertRequest insert =
new MomentsResource.InsertRequest(
service,
body,
"me",
MomentsResource.InsertRequest.CollectionEnum.Vault);
Moment wrote = insert.Execute();
But it returns exception 401. The code to post I found on Google Console Help. Can somebody help in this?
I finally found out that google APIs are not directly open to third party developers and it just made my case void and had to use HTTP method for this. Thanks #DalmTo for answering.

Create a Subscription in instagram with c#

I followed this link OAuth 2.0 In .NET With Instagram API, and it helped me fix my issue with getting my access token.
My code is this:
NameValueCollection parameters = new NameValueCollection
{
{"client_id", ClientId},
{"client_secret", ClientSecretId},
{"object", "user"},
{"aspect", "media"},
{"verify_token", "thisIsANormalSubscription"},
{"callback_url", CallbackURI}
};
WebClient client = new WebClient();
var result = client.UploadValues(SubscriptionURI, parameters);
SubscriptionURI = "https://api.instagram.com/v1/subscriptions".
I'm following the guide from instagram(http://instagram.com/developer/realtime/) including all the parameters for the POST request. But I only get the 400 error when it does the client.UploadValues.
PS:This is my first post, so might not be as appealing for the eye as I would wish
if you have your access token you can use this plugin I found, it gets the most recent photos from a user.
Instagram .NET
If you're using the Instasharp Client API (https://github.com/InstaSharp/InstaSharp) you can do something like this:
public InstagramConfig Config
{
get
{
return new InstagramConfig(InstagramAuthorisationModel.ApplicationId, InstagramAuthorisationModel.Secret);
}
}
public void YourSubscribeMethod(string searchTerm)
{
var result = await new Subscription(Config).CreateTag(searchTerm))
}
where InstagramAuthorisationModel is a class that holds your registered application id and secret
You can create subscriptions for Geography, (CreateGeography), User (CreateUser) and (CreateLocation) methods.

Categories

Resources