YouTube API, C#.net - Getting video info from YouTube failed some times - c#

I'm trying to add comment to videos on YouTube , some times when I'm getting a video to add comment on it, YouTube send me the below error:
Execution of request failed: http://gdata.youtube.com/feeds/api/videos/ceVlltPBcHg/comments
The inner message of the exception is: "The remote server returned an error: (403) Forbidden."
public bool commentVideo(string videoId)
{
Uri Url = new Uri("http://gdata.youtube.com/feeds/api/videos/" + videoId);
YouTubeRequestSettings s = new YouTubeRequestSettings(AppName, ApiKey,UserName,
Password);
s.Timeout = 10000000;
YouTubeRequest account = new YouTubeRequest(s);
account.Proxy = GetProxyForUser(user);
Video video = account.Retrieve<Video>(Url);//some times got exception
string rating = commentRepository.getRating();
Comment c = new Comment();
c.Content = commentRepository.getComment();
account.AddComment(video, c);
Console.WriteLine("Comment successfully added to : " + videoId);
return true;
}
What is wrong in my code?

It seems google's qouta security rules return error to my code. Code works correctly when I use the code in long intervals.

Related

google api v3 query google contacts .NET

I am trying to build a C# application that queries my google contacts,and prints them to console.
The email address is :bhmi12#gmail.com
excellent is the name of the google app.
I have two problems:
The First Problem every time i run the app i have to call:
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
surf to the URL and get a new AccessCode even that google claims u only have to do it once. and then u get an access token.
The second Problem is that this code doesnt work, when it goes to PrintAllContacts it failes under a wierd exception:
There is some error in your request thats all we know"(the google response
to my request).
Is this the right way to write the scope?
thanks very much.
The code:
{
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.ClientId = #"my id";
parameters.ClientSecret = #"my secret";
parameters.RedirectUri = #"urn:ietf:wg:oauth:2.0:oob";
parameters.ResponseType="code";
parameters.Scope = #"https://www.google.com/m8/feeds/contacts/bhmi12%40gmail.com/full";
//string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
parameters.AccessCode = #"";
try
{
OAuthUtil.GetAccessToken(parameters);
//OAuthUtil.RefreshAccessToken(parameters);
var contacts = new ContactsRequest(new RequestSettings("excellent", parameters));
PrintAllContacts(contacts);
}
catch (GDataRequestException e)
{
Console.WriteLine("Operation failed ({0}): {1}", e.Message, e.ResponseString);
}
}
No. The scope is the following constant string value that looks like a URL:
"https://www.googleapis.com/auth/contacts.readonly"
If you intend to modify the user's contacts, then use this instead:
"https://www.google.com/m8/feeds"
Reference: https://developers.google.com/google-apps/contacts/v3/#authorizing_requests_with_oauth_20

Error Uploading Video to YouTube

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.

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);
}

APNS Input string was not in a correct format. Disconnected

I am trying to set up apple push notifications, i am writing my own code for the server and as far as i know i have set up the app correctly. How ever i keep getting the following error come back from the log:
Payload queue received. Connecting to apple server. Creating SSL
connection. Conected. Payload generated for
"Token goes here i deleted it :
{"aps":{"alert":"test","badge":1,"sound":"default"}} Notification
successfully sent to APNS server for Device Toekn :
"Token here I've deleted it" An
error occurred while reading Apple response for token
"Token here I've deleted it" -
Input string was not in a correct format. Disconnected
This is my code.
var push = new PushNotification(true, #"C:\wwwroot\UltraNet\PushService\bin\Debug\206dist.p12", "ultrait");
var payload = new NotificationPayload("devicetoken here ive deleted it", "test", 1, "default");
var p = new List<NotificationPayload> { payload };
var result = push.SendToApple(p);
Console.ReadLine();
I have made sure that the certificates etc are set up correctly.
I am testing it as a adhoc app at the moment because it takes so long for a new version to be able to go live.
I really don't know where I'm going wrong if any one could help it would be brilliant thank you.
I also don't know what i need to do with the PEM files that i have created.
Edit***
I have the correct token this is another error that i receive
Payload generated for
df99286a1cb993cecba86b2e21f3fc4c04d214fcf7e0cf35a668fc822bdaa053 :
{"aps":{"alert":"test","badge":1,"sound":"default"}} Notification
successfully sent to APNS server for Device Toekn :
df99286a1cb993cecba86b2e21f3fc4c04d214fcf7e0cf35a668fc822bdaa053
Disconnected. An error occurred while reading Apple response for token
df99286a1cb993cecba86b2e21f3fc4c04d214fcf7e0cf35a668fc822bdaa053 -
Safe handle has been closed
Based on the code of ReadResponse (see below), the Input string was not in a correct format error message refers to the response received from Apple, and not to the notification you sent.
The code failed to properly read the error response from Apple.
Had it succeeded in reading the response, you would have known what the exact failure was and which message failed. Since you don't have the error response, it's a safe bet to assume the problem is your device token. That's the most common failure. If you can isolate the device token for which the error occurs, you should simply delete that token from your DB. Invalid Device Token error often occurs when you try to use sandbox tokens when pushing to production environment or vica versa.
private void ReadResponse(IAsyncResult ar)
{
if (!_conected)
return;
string payLoadId = "";
int payLoadIndex = 0;
try
{
var info = ar.AsyncState as MyAsyncInfo;
info.MyStream.ReadTimeout = 100;
if (_apnsStream.CanRead)
{
var command = Convert.ToInt16(info.ByteArray[0]);
var status = Convert.ToInt16(info.ByteArray[1]);
var ID = new byte[4];
Array.Copy(info.ByteArray, 2, ID, 0, 4);
payLoadId = Encoding.Default.GetString(ID);
payLoadIndex = ((int.Parse(payLoadId)) - 1000);
Logger.Error("Apple rejected palyload for device token : " + _notifications[payLoadIndex].DeviceToken);
Logger.Error("Apple Error code : " + _errorList[status]);
Logger.Error("Connection terminated by Apple.");
_rejected.Add(_notifications[payLoadIndex].DeviceToken);
_conected = false;
}
}
catch (Exception ex)
{
Logger.Error("An error occurred while reading Apple response for token {0} - {1}", _notifications[payLoadIndex].DeviceToken, ex.Message);
}
}
It was all to do with my certificates.
Because i hadn't turnt my combined PEM certificate back to a p12 file.

Pushsharp apple notification A call to SSPI failed error

I am using PushSharp to send Apple Push Notification in C# , i have my production .pem file and its password. Below is my code snippet.Am always getting this error ..
"A call to SSPI failed, see inner exception. ---> System.ComponentModel.Win32Exception: The message received was unexpected or badly formatted-"
OR
"System.IO.IOException: Authentication failed because the remote party has closed the transport stream."
I tried almost all codes available in net.Even tried MoonAPNS but same error, For custom script also am getting this SSPI failure error. I use the same .pem file and run a php script to send push notification to APN from same server,it works.
var push = new PushBroker();
var appleCert = File.ReadAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ck.pem"));
push.RegisterAppleService(new ApplePushChannelSettings(false, appleCert, "pwd"));
push.QueueNotification(new AppleNotification()
.ForDeviceToken("XXXXXXXXXXXXXXX")
.WithAlert("Hello World!")
.WithBadge(7)
.WithSound("sound.caf"));
LogManager.Info("Waiting for Queue to Finish..");
push.StopAllServices();
Please help
Thanks in advance
I think your c# may be incorrect, To verify, rather than with a .pem, can you try with your p12 cert using the below code as a test...
Boolean bsandbox = true;
string p12fileName =AppDomain.CurrentDomain.BaseDirectory + "yourCert.p12";
string p12password = "1234";
string deviceID1 = "2909b25e0c699b2dc4864b4b9f719e67aac7e0fab791a72a086ffb788ba28f6a"; //
string msg = "This is the message sent at : ";
string alert = "Hello world at " + DateTime.Now.ToLongTimeString();
int badge = 1;
string soundstring = "default";
var payload1 = new NotificationPayload(deviceID1, alert, badge, soundstring);
payload1.AddCustom("custom1", msg);
var notificationList = new List<NotificationPayload> { payload1 };
var push = new PushNotification(bsandbox, p12fileName, p12password);
var rejected = push.SendToApple(notificationList);`

Categories