Error Uploading Video to YouTube - c#

I am using following code to upload a video to YouTube.
It always gives following error.
The remote server returned an error: (403) Forbidden.
My Code is
YouTubeRequestSettings settings;
YouTubeRequest request;
string devkey = YouTubeDeveloperKey;
string username = YoutubeUserName;
string password = YoutubePassword;
settings = new YouTubeRequestSettings("VideoEditor", devkey, username, password) { Timeout = -1 };
request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = Title;
newVideo.Description = Description;
newVideo.Private = true;
newVideo.YouTubeEntry.Private = false;
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(FilePath, "video/flv");
Video createdVideo = request.Upload(newVideo);
Please do you have any idea about this error

As per the Youtube API V2 documentation, error 403 is an authorization error.
Most probably the username and password might be wrong.
My guess: Did you enable two step authentication on your Google account ?
If so, you must use an application-specific password.

Try to go to your youtube application via https://console.developers.google.com then select your application go to APIs and auth -> APIs.
It will display a list of multiple available APIs, click on Youtube Data API, and then click "enable". This will enable this API to be used by your app and most likely will solve your issue.

Related

Youtube Live API - Broadcast premission denied using OAuth

I am trying to broadcast live from my .Net application using Youtube.Data.Api v3.
I have set up OAuth and downloaded the .JSON file, and that works fine. I know that, because I have already successfully obtained a list of channels resp. videos on my account, i.e., following code works:
var channelsRequest = ytService.Channels.List("contentDetails, snippet");
channelsRequest.Mine = true;
var channelsListResponse = channelsRequest.Execute();
But if I try to execute a insert request (for completeness I show you the whole method),
public static LiveBroadcast CreateImmediateBroadcast(string title = "DefaultBroadcast") {
var snippet = new LiveBroadcastSnippet();
snippet.Title = title;
snippet.ScheduledStartTime = DateTime.Now;
snippet.ScheduledEndTime = DateTime.Now + TimeSpan.FromMinutes(60);
var status = new LiveBroadcastStatus();
status.PrivacyStatus = "unlisted";
var broadcast = new LiveBroadcast();
broadcast.Kind = "youtube#liveBroadcast";
broadcast.Snippet = snippet;
broadcast.Status = status;
var insertBroadcastRequest = ytService.LiveBroadcasts.Insert(broadcast, "snippet, status");
insertBroadcastRequest.Execute();
return broadcast;
}
I get an exception when calling insertBroadcastRequest.Execute(), namely:
Google.GoogleApiException was unhandled
HResult=-2146233088
Message=Google.Apis.Requests.RequestError
Insufficient Permission [403]
Errors [
Message[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]
]
ServiceName=youtube
Source=Google.Apis
StackTrace:
at Google.Apis.Requests.ClientServiceRequest`1.Execute() in C:\Users\cloudsharp\Documents\GitHub\google-api-dotnet-client\Src\Support\GoogleApis\Apis\Requests\ClientServiceRequest.cs:line 96
at YoutubeConsole.YouTubeAPI.CreateImmediateStream(String title) in C:\Users\bussg\Source\Workspaces\OwnExperimental\YoutubeConsole\YoutubeConsole\YouTubeAPI.cs:line 87
at YoutubeConsole.YouTubeAPI.Test() in
...
Also, for completeness, here is my authorization,
using (var stream = new FileStream(Directory.GetCurrentDirectory() + #"\GoogleAuthOtherApplication.json", FileMode.Open, FileAccess.Read)) {
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.YoutubeForceSsl},
"user",
CancellationToken.None,
new FileDataStore("YouTubeAPI")
).Result;
}
Also, For the YouTubeService.Scope I have tried all options. The insert method should work with ForceSsl according to the documentation.
Also this documentation page sais
Note: A channel must be approved to use the YouTube Live feature, which enables the channel owner to stream live content to that channel. If you send API requests on behalf of an authenticated user whose channel is not enabled or eligible to stream live content, the API will return an insufficientPermissions error.
But all my channels are approved for Youtube Live. Any ideas how to get this to work?
Ok after some testing between us over Email.
You need to have the correct scope "YouTubeService.Scope.YoutubeForceSsl" by changing "user" we forced it to request permissions again. My tutorial on how filedata store works in the Google .net client library
remove the space "snippet, status" by sending "snippet,status" it worked for me.
For the fun of it: Issue 8568:LiveBroadcasts: insert - spaces in part

Using EWS Managed Api with Office 365 Api

I am trying to use EWS managed Api with Office 365 Api via Azure AD. I have done the following tasks so far.
I have the admin privilege in Azure AD.
I have successfully registered my application in Azure AD.
I got Client ID, App key and resource ID from Azure AD.
I have enabled "Have full access to user's mailbox. as suggested by Jason.
I have successfully created a MVC5 web application.
I have followed this blog post of Jeremy.
Here the link of the blog I have followed :
http://www.jeremythake.com/2014/08/using-the-exchange-online-ews-api-with-office-365-api-via-azure-ad/#comment-280653
Code in my controller:
var outlookClient = await AuthHelper.EnsureOutlookServicesClientCreatedAsync("Mail");
IPagedCollection<IMessage> messagesResults = await outlookClient.Me.Messages.ExecuteAsync();
string messageId = messagesResults.CurrentPage[0].Id;
string tokenx = AuthHelper.GetSessionToken();
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.HttpHeaders.Add("Authorization", "Bearer " + tokenx);
service.PreAuthenticate = true;
service.SendClientLatencies = true;
service.EnableScpLookup = false;
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ExFolder rootfolder = ExFolder.Bind(service, WellKnownFolderName.MsgFolderRoot);
Edited : I am getting accessToken Successfully and using it to make call against EWS managed Api, but it fails with 403:Forbidden exception. Your help will be highly appreciated.
best regards,
Jason Johnston helped me solve my problem.
The link:
Office 365 / EWS Authentication using OAuth: The audience claim value is invalid
I checked the EWS trace, I learned that EWS was complaining about invalid token and insufficient privileges. I re-registered my application to Azure AD and enabled full access to mailbox.
I commented this below code.
//var outlookClient = await AuthHelper.EnsureOutlookServicesClientCreatedAsync("Mail");
//try
//{
// IPagedCollection<IMessage> messagesResults = await outlookClient.Me.Messages.ExecuteAsync();
// string messageId = messagesResults.CurrentPage[0].Id;
//}
//catch
//{
// System.Diagnostics.Debug.WriteLine("Something bad happened. !!");
//}
I am getting access token from this below link sample.
https://github.com/OfficeDev/Office-365-APIs-Starter-Project-for-ASPNETMVC
Here is the complete code of controller which does the main task of authentication.
string resourceUri = "https://outlook.office365.com";
var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Settings.Authority, new NaiveSessionCache(signInUserId));
string tokenx = await AuthHelper.AcquireTokenAsync(authContext, resourceUri, Settings.ClientId, new UserIdentifier(userObjectId,UserIdentifierType.UniqueId));
System.Diagnostics.Debug.WriteLine("Token:" + tokenx);
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.TraceListener = new EwsTrace();
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.HttpHeaders.Add("Authorization", "Bearer " + tokenx);
service.PreAuthenticate = true;
service.SendClientLatencies = true;
service.EnableScpLookup = false;
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ExFolder rootfolder = ExFolder.Bind(service, WellKnownFolderName.MsgFolderRoot);
Console.WriteLine("The " + rootfolder.DisplayName + " has " + rootfolder.ChildFolderCount + " child folders.");
The important thing I noticed is I can't use the same token to access office365 api and EWS managed Api as EWS works with full mailbox access while office365 doesn't. I request the developer to confirm this,maybe I am doing something wrong, however my problem is solved for now.
Yep, that's right. The scope required for EWS isn't compatible with the Office 365 APIs, and vice versa.

Google Apps - The remote server returned an error: (401) Unauthorized

I am trying to get files from gdrive(google docs), but it returning the error The remote server returned an error: (401) Unauthorized.The same error returning for Google Calendar also. I tried both DotNetOpenAuth and Oauth for authorize the user.
Error (from google calendar):
Execution of request failed: https://www.google.com/calendar/feeds/default/private/full?max-results=1&xoauth_requestor_id=mymail%40gmail.com&start-min=2013-12-04T12:37:34%2B05:30&sortorder=ascending&singleevents=true
what am I doing wrong?
Thanks.
My Code (google calendar):
GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("writely", "AppName");
requestFactory.ConsumerKey = "key";
requestFactory.ConsumerSecret = "secret";
String user = "mail#domain.com";
DocumentsService client = new DocumentsService("AppName");
client.RequestFactory = requestFactory;
// Retrieve user's list of Google Docs
DocumentsListQuery query = new DocumentsListQuery();
query.Uri = new OAuthUri("https://docs.google.com/feeds/default/private/full", user, requestFactory.ConsumerKey);
DocumentsFeed feed = client.Query(query);
foreach(DocumentEntry entry in feed.Entries)
{
Console.WriteLine(entry.Title.Text);
}

Upload video to youtube using c# winform "Invalid credentials" exception

I am trying to upload a video to youtube using C# Winform and I always get to "Invalid credentials" exception.
I am using username and password of my gmail account: is this ok?
the application name - can it be anything? or I need register it somewhere?
I have created in http://code.google.com/apis/youtube/dashboard a developer key, do I need to do more activation in order to make this code work?
This is my code:
YouTubeRequestSettings settings;
YouTubeRequest request;
string devkey = "My DEV KEY";
string username = "MY GAMIL MAIL";
string password = "MY GAMIL PASSWORD";
settings = new YouTubeRequestSettings("SOME APPLICATION", devkey, username, password) { Timeout = -1 };
request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = Title;
newVideo.Description = Description;
newVideo.Private = true;
newVideo.YouTubeEntry.Private = false;
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(FilePath, "video/mp4");
Video createdVideo = request.Upload(newVideo);
return createdVideo.VideoId;
That overload takes an auth token, not a username and password.
If you want to hard-code your password (which is a terrible idea), you also need to pass a client name.
I have found this example that has very detailed steps to achieve upload to youtube and many other things in C#
http://www.cstruter.com/blog/313
Hope it helpts

Accessing GData Calender from Google Apps account?

I'm building a simple app too that needs to access a calendar that's in my Google Apps account. But I'm having problems with authentication. I've tried the following code but it doesn't work:
Service service = new Service("<appname>");
service.setUserCredentials("<email>", "<password>");
CalendarEntry entry = (CalendarEntry)service.Get("<eventUrl>");
How do you get this to work with Google Apps? Is there any other type of authentication that I have to use for Google apps?
Update:
Unlocking the captcha solved my problem with getting the feed. Now I've hit the next wall: updating an event.
entry.Title.Text = "Foo";
entry.Update();
Gives me the GDataRequestException exception: "Can not update a read-only entry".
Im using the private calendar xml address that I got under kalendarsettings:
https://www.google.com/calendar/feeds/_%40group.calendar.google.com/private-/basic
I would recommend using Fiddler to see what http response you are getting back from Google. When I ran your code against my google apps account, I was getting back an "Error=CaptchaRequired" response. This required that I go to https://www.google.com/a/yourgoogleappdomain.com/UnlockCaptcha (replacing with your domain obviously). After I did that I was able to properly connect. You may be getting a different error code too so check for that and post it here. You could have an invalid password or invalid url or this functionality is disabled by your google apps administrator. Here is my sample code:
var calendarService = new CalendarService("company-app-version");
calendarService.setUserCredentials("<email>", "<password>");
var eventQuery = new EventQuery("http://www.google.com/calendar/feeds/user%40domain.com/private/full");
var eventFeed = calendarService.Query(eventQuery);
foreach (var atomEntry in eventFeed.Entries)
{
Console.WriteLine(atomEntry.Title.Text);
}
Make sure to replace the email, password, and email inside of the URL (url encode the # sign too).
using Google.GData.Client;
public bool ValidateGoogleAccount(string login, string password)
{
try
{
Service bloggerService = new Service("blogger", "App-Name");
bloggerService.Credentials = new GDataCredentials(login, password);
string token = bloggerService.QueryAuthenticationToken();
if (token != null)
return true;
else
return false;
}
catch (Google.GData.Client.InvalidCredentialsException)
{
return false;
}
}
Yet another solution Austin from google provides (it worked for me):
http://groups.google.com/group/google-calendar-help-dataapi/browse_thread/thread/400104713435a4b4?pli=1

Categories