Home > other >  How to convert code YouTube API from Console to WPF [closed]
How to convert code YouTube API from Console to WPF [closed]

Time:09-26

I have code worked fine in Console but i tried convert it to WPF c# but i didn't success. I tried porting each part to WPF and I found out the code below (2nd code I quoted below) when I convert it to WPF it doesn't work Please help me. How to it work fine in WPF c# This is my code:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Threading;
    using System.Threading.Tasks;
    
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Services;
    using Google.Apis.Upload;
    using Google.Apis.Util.Store;
    using Google.Apis.YouTube.v3;
    using Google.Apis.YouTube.v3.Data;
    
    namespace ConsoleApp2
    {
        
        internal class PlaylistUpdates
        {
            public string PrivacyStatus { get; private set; }
    
            [STAThread]
            static void Main(string[] args)
            {
                Console.WriteLine("YouTube Data API: Playlist Updates");
                Console.WriteLine("==================================");
    
                try
                {
                     //new PlaylistUpdates().Run().Wait();
                    //new PlaylistUpdates().RunUpload().Wait();
                    new PlaylistUpdates().Editvideo().Wait();
                    
                }
                catch (AggregateException ex)
                {
                    foreach (var e in ex.InnerExceptions)
                    {
                        Console.WriteLine("Error: "   e.Message);
                    }
                }
    
                Console.WriteLine("Press any key to continue...");
                Console.ReadKey();
            }

            private async Task Editvideo()
            {
                UserCredential credential;
                using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows for read-only access to the authenticated 
                        // user's account, but not other types of account access.
                        new[] { YouTubeService.Scope.YoutubeReadonly },
                        "user",
                        CancellationToken.None,
                        new FileDataStore(this.GetType().ToString())
                    );
                }
    
                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = this.GetType().ToString()
                });
    
                var channelsListRequest = youtubeService.Channels.List("contentDetails");
                channelsListRequest.Mine = true;
    
                // Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
                var channelsListResponse = await channelsListRequest.ExecuteAsync();
    
                foreach (var channel in channelsListResponse.Items)
                {
                    // From the API response, extract the playlist ID that identifies the list
                    // of videos uploaded to the authenticated user's channel.
                    var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;
    
                    Console.WriteLine("Videos in list {0}", uploadsListId);
    
                    var nextPageToken = "";
                    while (nextPageToken != null)
                    {
                        var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet,status");
                        playlistItemsListRequest.PlaylistId = uploadsListId;
                        playlistItemsListRequest.MaxResults = 50;
                        playlistItemsListRequest.PageToken = nextPageToken;
    
                        // Create a new, private playlist in the authorized user's channel.
                        var newVideo = new Video();
                        newVideo.Snippet = new VideoSnippet();
                        newVideo.Id = "6obQQde1X3A";
                        newVideo.Snippet.Title = "My Title";
                        newVideo.Snippet.Description = "My Description";
                        newVideo.Snippet.Tags = new string[] { "tag 1", "tag 2", "tag 3" };
                        newVideo.Snippet.CategoryId = "22";
                        newVideo.Status = new VideoStatus();
                        newVideo.Status.PrivacyStatus = "public";
                        newVideo = await youtubeService.Videos.Update(newVideo,"Id,snippet,status").ExecuteAsync();
    
                        Console.WriteLine("Change video details OK ....");
     
                        // Retrieve the list of videos uploaded to the authenticated user's channel.
                        var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
    
                        foreach (var playlistItem in playlistItemsListResponse.Items)
                        {
                        Console.WriteLine("{0} ({1})", playlistItem.Snippet.Title, playlistItem.Snippet.ResourceId.VideoId);
                        }
    
                        nextPageToken = playlistItemsListResponse.NextPageToken;
                    }
                }
            }
    }
    
    }

If i remove this code below. It worked fine!

// Create a new, private playlist in the authorized user's channel.
                        var newVideo = new Video();
                        newVideo.Snippet = new VideoSnippet();
                        newVideo.Id = "6obQQde1X3A";
                        newVideo.Snippet.Title = "My Title";
                        newVideo.Snippet.Description = "My Description";
                        newVideo.Snippet.Tags = new string[] { "tag 1", "tag 2", "tag 3" };
                        newVideo.Snippet.CategoryId = "22";
                        newVideo.Status = new VideoStatus();
                        newVideo.Status.PrivacyStatus = "public";
                        newVideo = await youtubeService.Videos.Update(newVideo,"Id,snippet,status").ExecuteAsync();
    
                        Console.WriteLine("Change video details OK ....");

This is my code in WPF

 private async Task Change_VideoDetails()
    {
        UserCredential credential;
        using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
        {
            credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                new[] { YouTubeService.Scope.YoutubeReadonly },
                "user",
                CancellationToken.None,
                new FileDataStore(this.GetType().ToString())
            );
        }

        var youtubeService = new YouTubeService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = this.GetType().ToString()
        });
        var channelsListRequest = youtubeService.Channels.List("contentDetails");
        channelsListRequest.Mine = true;
        // Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
        var channelsListResponse = await channelsListRequest.ExecuteAsync();

        foreach (var channel in channelsListResponse.Items)
        {
            // From the API response, extract the playlist ID that identifies the list
            // of videos uploaded to the authenticated user's channel.
            var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;

            //Console.WriteLine("Videos in list {0}", uploadsListId);

            var nextPageToken = "";
            while (nextPageToken != null)
            {
                var playlistItemsListRequest = youtubeService.PlaylistItems.List("Id,snippet,status");
                playlistItemsListRequest.PlaylistId = uploadsListId;
                playlistItemsListRequest.MaxResults = 50;
                playlistItemsListRequest.PageToken = nextPageToken;

                 var newVideo = new Video();
                newVideo.Snippet = new VideoSnippet();
                newVideo.Id = "6obQQde1X3A";
                txtLog.AppendText("\nWill change video details....."   newVideo.Id   );
                txtLog.ScrollToEnd();

                newVideo.Snippet = new VideoSnippet();
                newVideo.Id = "6obQQde1X3A";
                newVideo.Snippet.Title = "My Title";
                newVideo.Snippet.Description = "My Description";
                newVideo.Snippet.Tags = new string[] { "tag 1", "tag 2", "tag 3" };
                newVideo.Snippet.CategoryId = "22";
                newVideo.Status = new VideoStatus();
                newVideo.Status.PrivacyStatus = "public";
                newVideo = await youtubeService.Videos.Update(newVideo, "Id,snippet,status").ExecuteAsync();

                txtLog.AppendText("\nChanged video details ....."   newVideo.Id);
                txtLog.ScrollToEnd();

                // Retrieve the list of videos uploaded to the authenticated user's channel.
                var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();
                int line_count=0;
                foreach (var playlistItem in playlistItemsListResponse.Items)
                {
                    
                    line_count  = 1;
                    if (line_count == int.Parse(txtVideonumber.Text))
                    {
                        break;
                    }


                    //}   

                }

                nextPageToken = playlistItemsListResponse.NextPageToken;
            }
        }
    }

I used below code for run above code:

private void BtnChange_Click(object sender, RoutedEventArgs e)
    {
        Change_VideoDetails();
    }

I tried run debugger and my code is stopping at bellow code:

 newVideo = await youtubeService.Videos.Update(newVideo, "Id,snippet,status").ExecuteAsync();

I don't understand why it is stopping? Please help me solve it

CodePudding user response:

You must await an asynchronous method i.e. await the Task result:

// Since this is an event handler 'async void' is allowed. 
// Otherwise you must use 'async Task' or 'async Task<T>'
private async void BtnChange_Click(object sender, RoutedEventArgs e)
{
  await Change_VideoDetails();
}

Awaiting the Task is important to allow proper exception handling/behavior. If you don't await a Task then the exception will not propagate properly - the exception will be swallowed. This is because in an async method the exceptions are captured and placed on the Task object. When you await the Task, you allow the execption to propagate to the caller's context to finally hold your application or being handled in a catch block.

Your problem is difficult to solve for somebody that has no acces to your environment (including the Youtube account and authentication configuration).

First make sure that your debugger will break on all exceptions by enabling at least all CLR exceptions: select Debug/ Windows/Exception Setting in the main menu and check the "Common Language Runtime Exceptions" check box.

If still no exception is thrown in the debugger, remove the ExecuteAsync() to execute the operation synchronously. This way you can test if you encounter a deadlock. When it comes to async/await you must know that console apps, Asp.Net and Winforms/Wpf/UWP have a different behavior in certain aspects.

  • Related