2
votes

I have tried to search all to find out answer didn't find any solution. I am getting Exception while uploading video to youtube channel from youtube data v3. I have created keys for installed application. Even the video Title and its details is uploading fine. the only problem is that I get exception

Task is Cancelled. please See Stack Trace at the end for more info.

here is my code

  private async Task Run()
    {
        UserCredential credential;
        using (var stream = new FileStream("client_secret_766914936775-1ak2tk5e3u0krlbuu9rdip1sfa9u8k44.apps.googleusercontent.com.json", FileMode.Open, FileAccess.Read))
        {
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                // This OAuth 2.0 access scope allows an application to upload files to the
                // authenticated user's YouTube channel, but doesn't allow other types of access.
                new[] { YouTubeService.Scope.YoutubeUpload },
                "techno.1",
                CancellationToken.None
            );
        }

        YouTubeService youtubeService = new YouTubeService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "techno ",

        });



        var video = new Video();
        video.Snippet = new VideoSnippet();
        video.Snippet.Title = "Default Video Title";
        video.Snippet.Description = "Default Video Description";
        video.Snippet.Tags = new string[] { "tag1", "tag2" };
        video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
        video.Status = new VideoStatus();
        video.Status.PrivacyStatus = "unlisted"; // or "private" or "public"
        var filePath = @"abc.mp4"; // Replace with path to actual movie file.

        using (var fileStream = new FileStream(filePath, FileMode.Open))
        {
            var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
            videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
            videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

            await videosInsertRequest.UploadAsync();
        }
    }

    private void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
    {
        switch (progress.Status)
        {
            case UploadStatus.Uploading:
                Console.WriteLine("{0} bytes sent.", progress.BytesSent);
                break;

            case UploadStatus.Failed:
                Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
                break;
        }
    }

    private void videosInsertRequest_ResponseReceived(Video video)
    {
        Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
    }
}

I am getting uploadStatus.Failed videosInsertRequest_ProgressChange method.

I already tried to use this code

youtubeService.HttpClient.Timeout= TimeSpan.FromMinutes(60);

but timeout property is not available. its get only.

An error prevented the upload from completing. System.Threading.Tasks.TaskCanceledException: A task was canceled.
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Google.Apis.Upload.ResumableUpload1.d__94.MoveNext() in C:\Apiary\v1.20\google-api-dotnet-client\Src\Support\GoogleApis\Apis[Media]\Upload\ResumableUpload.cs:line 652 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Google.Apis.Upload.ResumableUpload1.d__91.MoveNext() in C:\Apiary\v1.20\google-api-dotnet-client\Src\Support\GoogleApis\Apis[Media]\Upload\ResumableUpload.cs:line 581 Error: A task was canceled.

2
You may try the other suggestion in this SO thread which it to download the JSON file. Rename the JSON file name to client_secrets.json and then save to bin/Debug ot bin/Release as same *.exe as directory. Also, maybe your network speed was slow as described in this related issue. - abielita
I tried with renaming and placing these files in bin/Release but didn't work. - Ahsan Muzafar

2 Answers

0
votes

Fifteen minutes is way too long for the timeout value. I use one minute.

youtubeService.HttpClient.Timeout = TimeSpan.FromMinutes(1);

It looks like the real problem is that you do not handle the returned error and resume the upload. See the sample program "ResumeableUpload.CS.Sample" at https://github.com/google/google-api-dotnet-client-samples The sample program shows how to handle resuming the upload after an error within the same instance and how to resume an upload if the program is restarted.

With a shorter timeout period and the code to resume the upload, your uploads will go much faster during times when the upload server is busy.

0
votes

At last, it worked

 youtubeService.HttpClient.Timeout = TimeSpan.FromMinutes(15.00);

I was giving TimeSpan in wrong way.