ngoctuan / google-gdata

Automatically exported from code.google.com/p/google-gdata
0 stars 0 forks source link

Error Uploading Video to youtube - .NET 2.0 #197

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Im trying to submit a video to you tube using this code:

 public string UploadVideo(string title, string description, Category
category, string keywords, HttpPostedFile videoFile)
        {
            string code = "";
            try
            {
                string clientCode = <HERE IS THE CLIENT CODE>
                string devCode = <HERE IS THE DEV CODE>
                string appName = <HERE IS THE APP NAME>

                YouTubeService service = new YouTubeService(appName,
clientCode, devCode);
                service.setUserCredentials(<HERE IS THE USER>,<HERE IS THE
PASS>);

                YouTubeEntry newEntry = new YouTubeEntry();

                newEntry.Media = new MediaGroup();
                newEntry.Media.Title = new MediaTitle(title);
                newEntry.Media.Categories.Add(new
MediaCategory(category.ToString(), YouTubeNameTable.CategorySchema));
                newEntry.Media.Keywords = new MediaKeywords(keywords);
                newEntry.Media.Description = new MediaDescription(description);
                newEntry.Private = false;

                newEntry.MediaSource = new
MediaFileSource(videoFile.InputStream, videoFile.FileName,
videoFile.ContentType);

                ((GDataRequestFactory)service.RequestFactory).KeepAlive =
false;
                FormUploadToken token = service.FormUpload(newEntry);

                code = token.Token;
            }
            catch (Exception ex)
            {
                //LOG EXCEPTION
                throw ex;
            }
            return code;

        }

I Want to upload a Video to youtube using the API for .NET 2.0.

Im getting this Exception : 

((System.Net.WebException)(ex))

{"The request was aborted: The request was canceled."}
Inner Exception :{"Cannot close stream until all bytes are written."}

Stack Trace:

"   at System.Net.ConnectStream.CloseInternal(Boolean internalCall, Boolean
aborting)\r\n   at
System.Net.ConnectStream.System.Net.ICloseEx.CloseEx(CloseExState
closeState)\r\n   at System.Net.ConnectStream.Dispose(Boolean
disposing)\r\n   at System.IO.Stream.Close()\r\n   at
Google.GData.Client.GDataGAuthRequest.CopyRequestData()\r\n   at
Google.GData.Client.GDataGAuthRequest.Execute(Int32 retryCounter)\r\n   at
Google.GData.Client.GDataGAuthRequest.Execute()\r\n   at
Google.GData.Client.MediaService.EntrySend(Uri feedUri, AtomBase baseEntry,
GDataRequestType type, AsyncSendData data)\r\n   at
Google.GData.Client.Service.EntrySend(Uri feedUri, AtomEntry baseEntry,
GDataRequestType type)\r\n   at
Google.GData.YouTube.YouTubeService.FormUpload(YouTubeEntry newEntry)\r\n 
 at
aycron.sanderostepway.core.youtube.AycronYouTubeHelper.UploadVideo(String
title, String description, Category category, String keywords,
HttpPostedFile videoFile) in D:\\Proyectos\\Sandero
Stepway\\SanderoStepway\\aycron.sanderostepway.core\\youtube\\AycronYouTubeHelpe
r.cs:line
73"

I have installed Google_Data_API_Setup(1.2.3.0) in a windows 2005 server SP2

Thank you!

Original issue reported on code.google.com by danti...@gmail.com on 13 Dec 2008 at 5:01

GoogleCodeExporter commented 9 years ago
Need more information. This code normally works fine. 

What's the size of the video?
Do you have a proxy? 
What's the reason to have keepalive == false set? 

I am suspecting that your system is aborting the connection. Is this running in 
an ASP page and you are reaching 
the scripttimeout? 

Original comment by fman...@gmail.com on 15 Dec 2008 at 12:00

GoogleCodeExporter commented 9 years ago
The video size is More than 2 MB.
We dont have a Proxy.
The reason for keepalive = false is that I saw it in several forums about this 
error. 
If I remove it, the error continues.

I use the Direct Upload with the same CODE and it works fine. So I think that 
the 
error could be an API bug.

Thank you!!

Original comment by danti...@gmail.com on 15 Dec 2008 at 12:35

GoogleCodeExporter commented 9 years ago
Now... without changing my code... the upload started to fail in DIRECT 
UPLOAD... 
I think that it could be a problem with the service...

Have you tested my code?

Original comment by danti...@gmail.com on 16 Dec 2008 at 9:08

GoogleCodeExporter commented 9 years ago
I can't understand why direct upload would start to fail. 

Your code, the one for formupload, is failing because you are not supposed to 
attach the media to the entry. 
You are supposed to send the media with a form post. So i suspect that this 
happens:

-> the .NET library posts the entry to the "get form uploadtoken" uri
-> that uri does not process the mime post body (that the .NET lib creates due 
to the attached mediasource)
-> now the answer comes back, we get the token, release all the in memory 
objects, whcih throws this error, 
was the stream is getting closed without all the data written to the service

so, do not attach the media source. Let me know. In a future version, i put a 
check in that code to warn. 

Original comment by fman...@gmail.com on 17 Dec 2008 at 12:08

GoogleCodeExporter commented 9 years ago
Thank you for the explanation.!

I think that youtube should upload more complete examples to help the 
developers with 
the API.

again, thank for your help!

Original comment by danti...@gmail.com on 17 Dec 2008 at 12:20

GoogleCodeExporter commented 9 years ago
This is just guessing. Let me know if that fixes your issue. 

Original comment by fman...@gmail.com on 17 Dec 2008 at 3:58

GoogleCodeExporter commented 9 years ago
I can´t edit my ASP.NET form Action dynamically, so I cannot use the form 
upload way.

Have you got some example code to do that?

Thank you!

Original comment by danti...@gmail.com on 18 Dec 2008 at 6:51

GoogleCodeExporter commented 9 years ago
The Form Upload works OK!!!

But we have errors uploading with the Direct Upload.

The API Documentation for .NET is Wrong!!!

Thank you!

Original comment by danti...@gmail.com on 20 Dec 2008 at 12:58

GoogleCodeExporter commented 9 years ago
Can you be more specific? 

Original comment by fman...@gmail.com on 15 Jan 2009 at 12:22

GoogleCodeExporter commented 9 years ago
Using Direct Upload Im getting the exception descripted in the first Message.

Original comment by danti...@gmail.com on 15 Jan 2009 at 2:12

GoogleCodeExporter commented 9 years ago
Need more data. Uploading can fail for a lot of reasons. Can i get the HTTP 
snippet of the failiure? How big is the 
video? Are you behind a firewall? If it is ASP.NET, is there a scripttimeout?

Original comment by fman...@gmail.com on 21 Jan 2009 at 11:42

GoogleCodeExporter commented 9 years ago
Hello, I have a problem with the form upload too.

This is the code:

public static FormUploadToken Upload(string userName, string title, string path)
            {
                string url = string.Empty;
                try
                {

                    YouTubeService service = Login(); //This Login works fine, I've 
tried it in the direct upload.

                    YouTubeEntry newEntry = new YouTubeEntry();

                    newEntry.Media = new MediaGroup();
                    newEntry.Media.Categories.Add(new MediaCategory("Travel", 
YouTubeNameTable.CategorySchema));
                    newEntry.Media.Categories.Add(new MediaCategory(userName, 
YouTubeNameTable.DeveloperTagSchema));

                    newEntry.Media.Keywords = new MediaKeywords("viajes, travel");
                    newEntry.Media.Description = new MediaDescription("No 
description available");
                    newEntry.Media.Title = new MediaTitle(title);
                    newEntry.Private = false;
                    //newEntry.Location = new GeoRssWhere(37, -122);
                    // alternatively, you could just specify a descriptive string
                     newEntry.setYouTubeExtension("location", "Mountain View, CA");

                    path = path.ToLower();

                    string mimeFormat;
                    if (path.Contains(".avi") || path.Contains(".mpg") || 
path.Contains(".mpeg"))
                        mimeFormat = "video/mpeg";
                    else if (path.Contains(".wmv"))
                        mimeFormat = "video/x-ms-wmv";
                    else if (path.Contains(".mov"))
                        mimeFormat = "video/quicktime";
                    else if (path.Contains(".mp4"))
                        mimeFormat = "video/mp4";
                    else if (path.Contains(".swf"))
                        mimeFormat = "application/x-shockwave-flash";
                    else if (path.Contains(".flv"))
                        mimeFormat = "video/x-flv";
                    else if (path.Contains(".3gp"))
                        mimeFormat = "video/3gpp";
                    else
                        throw new Exception("File extension not recognized");

                    newEntry.MediaSource = new MediaFileSource(path, mimeFormat);

                    FormUploadToken token = service.FormUpload(newEntry);

                    return token;
                }
                catch (Exception ex)
                {
                    throw new Exception("Exception during file upload.", ex);
                }
                FormUploadToken tokAux = new FormUploadToken
(string.Empty,string.Empty);

                return tokAux;
            }

If you could help me, I would be able to do something. Till now, the struggle 
with 
the insufficient examples in the dotNet api has been long and tiring.

please, help.

Original comment by mikelang...@gmail.com on 9 Feb 2009 at 2:24

GoogleCodeExporter commented 9 years ago
ok, so what is the problem with the code? What is going wrong? Whats the server 
error message or the compiler 
error or whatever. 

Original comment by fman...@gmail.com on 18 Feb 2009 at 12:10

GoogleCodeExporter commented 9 years ago
so what is already wrong just by looking at the code is that you are not 
supposed to have a mediasource when 
you use a formupload. You only send the meta data. You might want to read the 
documentation:

http://code.google.com/apis/youtube/2.0/developers_guide_protocol_browser_based_
uploading.html#Browser_
based_uploading

to understand this better. 

Original comment by fman...@gmail.com on 18 Feb 2009 at 3:13

GoogleCodeExporter commented 9 years ago
 Hi   dantiags ,
did it work for you ?

Original comment by waves...@gmail.com on 23 Feb 2009 at 7:58

GoogleCodeExporter commented 9 years ago
I used the Form Upload way and it works.

but i didn´t try again with the Direct Upload, because Im very busy.

Original comment by danti...@gmail.com on 23 Feb 2009 at 8:13

GoogleCodeExporter commented 9 years ago
Fine. The bug report was about formupload, that works now, and was a programmer 
error. 

The claim about a not working direct upload is not substantiated, there is no 
information given about that 
problem, and the reporter is to busy to provide data. Hence closing as not a 
bug. 

Original comment by fman...@gmail.com on 26 Feb 2009 at 3:07

GoogleCodeExporter commented 9 years ago
I'm having the same problem with the error: "Cannot close stream until all 
bytes are
written.
I'm using direct upload method in desktop application.
The error only happens when video files are bigger. With smaller files there is 
no
problem.
Here is the code:
YouTubeService service = new YouTubeService(
                                            Properties.Settings.Default.ApplicationName,
                                            Properties.Settings.Default.clientID,
                                            Properties.Settings.Default.developerKey
                                            );

service.setUserCredentials(Properties.Settings.Default.GoogleUserName,
Properties.Settings.Default.GooglePassword);
                                        service.QueryAuthenticationToken();

                                        YouTubeEntry newEntry = new YouTubeEntry();

                                        newEntry.Media = new
Google.GData.YouTube.MediaGroup();
                                        newEntry.Media.Title = new MediaTitle(dr.Title);
                                        newEntry.Media.Categories.Add(
                                            new MediaCategory(dr.VideoCategory,
YouTubeNameTable.CategorySchema));
                                        newEntry.Media.Keywords = new
MediaKeywords(dr.Title.Replace(" ", ","));
                                        newEntry.Media.Description = new
MediaDescription(dr.Description);
                                        newEntry.Private = false;

                                        newEntry.Location = new GeoRssWhere(37, -122);
                                        newEntry.MediaSource = new MediaFileSource(
                                            FullName,

getMimeType(System.IO.Path.GetExtension(FullName))
                                        );

                                        YouTubeEntry createdEntry =
service.Upload(newEntry);

                                        MessageBox.Show(createdEntry.VideoId);

Original comment by mayernho...@yahoo.com on 24 Aug 2009 at 3:15

GoogleCodeExporter commented 9 years ago
Can you provide more information about:

your runtime environment
the size of the files that are failing

Frank

Original comment by fman...@gmail.com on 26 Aug 2009 at 3:01

GoogleCodeExporter commented 9 years ago
Hi fmantek
I also use C# client library to upload file.
Is it necessary to set longer timeout and keepAlive to false?
If I dont' set this two property when I upload a video size>20 MB, it will 
result in 
exception with "The request was aborted: The request was canceled."
Besides it was slow to upload a video with direct upload.
It took ten minutes to upload a 25MB file, at the mean time, it took only 2 
minutes 
to upload a 25MB file on youtube website.
Is there possibility to accelerate the upload?

Original comment by jim.te...@gmail.com on 27 Aug 2009 at 10:43

GoogleCodeExporter commented 9 years ago
Did anyone get a solution to this problem? I am using the .Net API and getting 
the 
same error when trying to upload - "Cannot close stream until all bytes are 
written."

Small videos work fine.

server.scripttimeout = 10000
<httpRuntime executionTimeout="3600" maxRequestLength="102400" />
IIS Timeout = 3600

Not sure what else i can change.

Original comment by dwthom...@gmail.com on 22 Oct 2009 at 1:17

GoogleCodeExporter commented 9 years ago
The upload speed in direct upload is not related to the .net api, but an issue 
with
the youtube site, there is nothing i can do about it. 

So yes, you will end up to set timeouts to as high as possible if you do that. 

I would recommend doing either formupload or async upload anyhow. 

I am going to close this bug again. if you still have an issue, open a new bug 
with a
complete repro case. This is very hard to debug with that little information
available (if a 25Mb file causes the problem is dependent on a lot of factors:
location, internet access speed, computing environment etc). 

The failure "cannat close stream..." always has the reason that the outside
environment closed down the connection before the upload was completed. Why, is 
a
matter for a lot more detail than is available in those bugreports.

I just uploaded a 200Mb movie several times. Sometimes it failed with a 400 
from the
server, sometimes it succeeded. 

This whole thing with bigger files will only get better when we have a resumable
upload protocol.

Original comment by fman...@gmail.com on 3 Nov 2009 at 10:18

GoogleCodeExporter commented 9 years ago
hey everyone,"cannot close stream until all bytes are written" error for 
uploading 
more than 4mb files,just set the timeout for the request object you have 
created for 
the youtuberequestobject related to GDataRequestFactory class
just like below,could solve the error.
YouTubeRequestSettings settings = new YouTubeRequestSettings
(appname,clientid,developerkey,username,pwd)
        YouTubeRequest request = new YouTubeRequest(settings);
((GDataRequestFactory)request.Service.RequestFactory).Timeout = 9999999;

Original comment by ayya...@gmail.com on 6 Nov 2009 at 10:50

GoogleCodeExporter commented 9 years ago
[deleted comment]
GoogleCodeExporter commented 9 years ago
Yep same issue here.  Timeout happens no matter the file size.  Code:

        public string UploadToYouTube(string productId, int companyId, string fileName, string title, string keywords, string description, bool testing)
        {
            string developerKey = "";
            string ytUsername = "";
            string ytPassword = ConfigurationManager.AppSettings["YouTubePassword"];

            developerKey = _productRepository.GetYoutubeDevKey(companyId);
            ytUsername = _productRepository.GetYoutubeUsername(companyId);

            service.RequestFactory = authFactory;
            service.setUserCredentials(ytUsername, ytPassword);
            string clientToken = service.QueryClientLoginToken();

            YouTubeRequestSettings settings = new YouTubeRequestSettings("SiteManager Videos", developerKey, clientToken);
            YouTubeRequest request = new YouTubeRequest(settings);

            Video newVideo = new Video();

            newVideo.Title = title;
            newVideo.Tags.Add(new MediaCategory("Sports", YouTubeNameTable.CategorySchema));
            newVideo.Keywords = keywords;
            newVideo.Description = description;
            newVideo.YouTubeEntry.Private = false;
            request.Settings.Timeout = 9999999;

            string mimeFormat = "";
            if (fileName.Contains(".avi") || fileName.Contains(".mpg") || fileName.Contains(".mpeg"))
                mimeFormat = "video/mpeg";
            else if (fileName.Contains(".wmv"))
                mimeFormat = "video/x-ms-wmv";
            else if (fileName.Contains(".mov"))
                mimeFormat = "video/quicktime";
            else if (fileName.Contains(".mp4"))
                mimeFormat = "video/mp4";
            else if (fileName.Contains(".swf"))
                mimeFormat = "application/x-shockwave-flash";
            else if (fileName.Contains(".flv"))
                mimeFormat = "video/x-flv";
            else if (fileName.Contains(".3gp"))
                mimeFormat = "video/3gpp";
            else
                throw new Exception("File extension not recognized");
            newVideo.YouTubeEntry.MediaSource = new MediaFileSource(fileName, mimeFormat);

            Video createdVideo = request.Upload(newVideo);

            /*** TODO: Display some kind of message or progress indicating the video is still being uploaded. ***/

            return createdVideo.VideoId;
        }

I've got the "request.Settings.Timeout = 9999999" line in there as well as the 
"<httpRuntime executionTimeout="3600" maxRequestLength="1048576"/>" line in the 
system.web section of my Web.Config.  Still no dice.  The request is always 
cancelled after 90 seconds.

What would be nice is something in the API to give the user some sort of 
indication of the progress of the upload.

Original comment by AlexJero...@gmail.com on 17 Oct 2011 at 3:24

GoogleCodeExporter commented 9 years ago
Have you tried using resumable upload instead? It fires events to update you on 
the progress and to notify the upload completion.

Original comment by ccherub...@google.com on 17 Oct 2011 at 4:03

GoogleCodeExporter commented 9 years ago
ccherub: I've attempted to implement resumable upload code but it seems to be 
predicated on having a Document class provided by Google that I don't have.  I 
sought out and added the reference to the GData DocumentEntry dll but that just 
caused build errors, and also still didn't help Visual Studio to recognize any 
sort of Document class.

Original comment by transfer...@gmail.com on 17 Oct 2011 at 5:30

GoogleCodeExporter commented 9 years ago
Are you using the latest version of the library?

Also, check the YouTubeUploader sample:

http://code.google.com/p/google-gdata/source/browse/#svn%2Ftrunk%2Fclients%2Fcs%
2Fsamples%2FYouTubeUploader%253Fstate%253Dclosed

It is a complete application using the ResumableUpload component to upload 
videos to YouTube

Original comment by ccherub...@google.com on 17 Oct 2011 at 5:49

GoogleCodeExporter commented 9 years ago
I downloaded the YouTubeUploader.sln file there and tried to open it using File 
> Open > Project/Solution in Visual Studio 2010, and I get "the selected file 
is not a valid solution file."  Any way I can just view the source code?

Original comment by transfer...@gmail.com on 17 Oct 2011 at 6:23

GoogleCodeExporter commented 9 years ago
OK PROGRESS.  I seem to have solved the timeout issue... instead of doing:

request.Settings.Timeout = 9999999;

I did

((GDataRequestFactory)request.Service.RequestFactory).Timeout = 60 * 60 * 1000; 
//one hour

So it now spends several minutes while I assume the video is being uploaded... 
but after all of that time, I find out I'm not authenticated. :/  Shouldn't I 
be told that BEFORE a 15-20 minute upload completes?

The error returned is "401: Unauthorized" by the remote server.  I'm going to 
try catching the exception and see if I get more information out of it.

Original comment by transfer...@gmail.com on 17 Oct 2011 at 7:30

GoogleCodeExporter commented 9 years ago
The ResponseString was "Invalid AuthSub Token."  ... But I'm not even using 
AuthSub, I'm using ClientLogin by providing a username and password.  Moreover, 
I CAN'T use AuthSub because we have more than one YouTube account, and I want 
to be able upload the same video to all accounts with a single button click, 
and AuthSub would require the user to log out of one Google account and into a 
different one manually in between uploads.

Right now I'm looking into OAuth to see if that's a viable alternative but so 
far I haven't seen any example code for .NET...

Original comment by transfer...@gmail.com on 17 Oct 2011 at 8:18

GoogleCodeExporter commented 9 years ago
Aaaand I got it.  Just had to use the 4-parameter version of 
YouTubeRequestSettings(appName, devKey, username, password) instead of the 
3-paramater one (appName, devKey, authSubToken).  And it uploaded and processed!

You may now ignore me.

But yes, for people having the timeout issue, give 
((GDataRequestFactory)request.Service.RequestFactory).Timeout = 60 * 60 * 1000 
a shot if you haven't already.

Original comment by transfer...@gmail.com on 17 Oct 2011 at 8:30

GoogleCodeExporter commented 9 years ago
Hai Guyz...
          use the below code to upload a video
using Google.GData.Extensions;
using Google.GData.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.YouTube;
using Google.GData.Client;

   string devkey = "AIzaSyBcybxqpxBbFjwJ25AkLu1QcCwaiui-nlU";
            string username = "videoswathi@gmail.com";
            string password = "video123";
            YouTubeRequestSettings settings = new YouTubeRequestSettings("StreamingVideos", devkey, username, password);// { Timeout = -1 };
            //settings.Timeout = -1;
            YouTubeRequest request = new YouTubeRequest(settings);

            Video newVideo = new Video();

            newVideo.Title = "TestTitle";
            newVideo.Description = "TestDescription";
            newVideo.Tags.Add(new MediaCategory("Comedy", YouTubeNameTable.CategorySchema));
            newVideo.Private = false;
            newVideo.YouTubeEntry.Private = false;

            newVideo.YouTubeEntry.MediaSource = new MediaFileSource(@"C:\Documents and Settings\aswinjose\Desktop\youtubeapp\vid-20130512-wa0004.mp4", "video/MOV");

            request.Upload(newVideo);

Original comment by videoswa...@gmail.com on 26 Nov 2013 at 11:00