Click here to Skip to main content
Click here to Skip to main content

Manage YouTube using C# and Youtube API 1.6

By , 7 Jan 2011
 

Introduction

This is my first article. So please guide me to correct my mistakes.

This code shows how to access Youtube from desktop. Here you can perform same actions that can be done in Youtube. Here I used YouTube API 1.6. Please download the same version. In the latest version, you will get some error when running the code.

Using the Code

This is a client application which interacts with Youtube using Youtube API 1.6 .NET client library. In this article, I will explain about authentication, video feeds, displaying feeds and pagination.

Basic Requirements

  1. .NET 2.0 runtime
  2. Youtube API 1.6 SDK
  3. Developer key (you can get it from http://code.google.com/apis/youtube/dashboard/)
  4. Video player to play the video. You can use Windows media player or flash player. Here I used shockwave player to play the video.

After downloading and installing the Youtube SDK, go to Installed location and you will find the DLLs that you need to get started in the distribution's Redist sub directory. Then open your IDE and add reference to the DLLs (i.e., Google.Gdata.Client.dll, Google.Gdata.Extensions.dll, Google.Gdata.Youtube.dll).

Then, import the following namespaces:

using Google.GData.Extensions;
using Google.GData.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.YouTube

1: Authentication

To access Youtube from client application, first you need to authenticate yourself. The following code shows how to check whether the username and password are incorrect or not.

YouTubeService service = new YouTubeService();
service.setUserCredentials(textBox1.Text , maskedTextBox1.Text);
//textbox1 contains username and maskedTextBox1 contains password
try{
service.QueryClientLoginToken();}
catch(System.Net.WebException e){MessageBox.Show(e.Message);}

To check the username and password, you need to create an instance of YouTubeService. Constructor of the class contains 3 overloaded methods. Once the object is created, then use setUserCredentials method to assign the username and password. Then call QueryClientLoginToken(). This method returns a string (token) that authenticates the user if the user credentials are correct. Else, it will throw System.Net.WebException.

The token can also be used for further implementation of project. But in this project, I used it to check whether the username and password are correct or not. Then I passed it to the next window form to display feeds and search results.

I used Client Login Authentication for querying.

To use clientlogin authentication, you must give correct username and password. Check the below code:

yousettings= new YouTubeRequestSettings("YouManager",devkey,username,password);
yourequest=new YouTubeRequest(yousettings);

The above code performs client login authentication. To perform every action, you need the Instance of YouTubeRequest class. To create the instance, you need to pass settings, i.e., instance of YoutubeRequestSettings class. To create a setting, you need to pass application name, developer key, username and password to the constructor. This setting can be used for YouTubeRequest class. When you make a query, you need this instance of YouTubeRequest. It will throw an exception if settings are incorrect.

2: Youtube Video Feeds

Youtube video feed is a regularly updated summary of videos along with other details like author, comments for videos, view count, etc. of the videos. In our application, we use video feeds to fetch the data. There are many types of feeds provided by Youtube API. They are Video feed, related videos feed, Video responses feed, Standard feed, Users favorite feed, Playlist feed.

General Syntax of Youtube video feeds:

Video feed: "http://gdata.youtube.com/feeds/api/videos/videoID" Video ID represents a particular video. This URL returns a particular video entry.

Related Videos Feed: "http://gdata.youtube.com/feeds/api/videos/videoID/related". Every video entry consists related video entries.

Responses feed: "http://gdata.youtube.com/feeds/api/videos/videoID/responses".

Standard Feeds: Standard feeds contain lists of videos that either reflect YouTube user behavior, such as top-rated and most viewed video feeds, or were selected by YouTube staff, such as recently featured and mobile video feeds. Many of these feeds are shown on the Videos tab of the YouTube website. Standard feeds are updated every few minutes.

http://gdata.youtube.com/feeds/api/standardfeeds/regionID/feedID_CATEGORY_NAME?time=timeID

In the above URL, you can see regionID. Region ID is used to get specific videos of countries. If you enter region id as JP, you will get videos from Japan only. feedID specifies about type of feed, i.e., it may be top rated or most viewed, etc. category name is used to get videos from a particular category, i.e., comedy, sports, etc. timeID is used to get videos for specific time, i.e., it may be today, this week, this month or all time. And it is not necessary to mention regionID, time or category name. But feedID is necessary.

User's favorite feed: "http://gdata.youtube.com/feeds/aspi/users/default/favorites" - This link is used when you want to access or modify the entries of user.

"http://gdata.youtube.com/feeds/aspi/users/username/favorites" - This link is used when you want to access another users entries.

User's Playlist Feed: "http://gdata.youtube.com/feeds/api/users/default/playlist" - This displays playlist information. This link is used to modify the playlist data.

"http://gdata.youtube.com/feeds/api/users/username/playlist" - This link is used to access another users playlists.

3: Displaying Feeds

To display video feeds, first we need feedURL (discussed above). In the project, I used GetfeedUrl function to get feedurl for standard feeds.

string tempUrl,tfeedUrl,ttimeUrl,tcatUrl;
tempUrl = "http://gdata.youtube.com/feeds/api/standardfeeds/";
tfeedUrl=tcatUrl =ttimeUrl = "";
switch (feed)
{
case 0:tfeedUrl="top_rated";break;
case 1: tfeedUrl = "top_favorites";break;
case 2: tfeedUrl = "most_viewed";break;
case 3: tfeedUrl = "most_popular";break;
case 4: tfeedUrl = "most_recent";break;
case 5: tfeedUrl = "most_discussed";break;
case 6: tfeedUrl = "most_responded";break;
case 7: tfeedUrl = "recently_featured";break;
}
switch (cat)
{
case 0: tcatUrl = "";break;
case 1: tcatUrl = "_Autos";break;
case 2: tcatUrl = "_Comedy";break;
case 3: tcatUrl = "_Education";break;
case 4: tcatUrl = "_Entertainment";break;
case 5: tcatUrl = "_Film";break;
case 6: tcatUrl = "_Howto";break;
case 7: tcatUrl = "_Music";break;
case 8: tcatUrl = "_News";break;
case 9: tcatUrl = "_People";break;
case 10: tcatUrl = "_Sports";break;
}
switch (time)
{
case 0: ttimeUrl = "?time=today";break;
case 1: ttimeUrl = "?time=this_week";break;
case 2: ttimeUrl = "?time=this_month";break;
case 3: ttimeUrl = "";break;
}
tempUrl = tempUrl + tfeedUrl + tcatUrl + ttimeUrl;
feedUrl = tempUrl;

The above code is used to get the feedUrl. I used combo boxes to get the category feedtype and time. Example: I want to get videos from today's top rated videos, then feed URL will be like this:

tempUrl="http://gdata.youtube.com/feeds/api/standardfeeds/"

tfeedUrl="top_rated" , tcatUrl="" and ttimeUrl="?time=today". Now feedurl is 
tempurl+tfeedurl+tcaturl+ttimeurl. 
i.e. "http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?time=today".

Once you get the feedurl, now you can display the feeds using the URL. The following code shows how to display using feedUrl.

//

Feed<video> videofeed = yourequest.Get<Video>(new Uri(feedUrl));DisplayFeed();

public void DisplayFeed()
{
lvcount = 0;
lvDisplay.Items.Clear();
foreach (Video entry in videofeed.Entries)
{
ListDisplay(entry);
videocount++;
}
} 

To display feed, first you need to create object of feed. Then you can assign video feeds by using get method. Here, you use the YouTubeRequest object to call get method. The display feed function is used to display the feeds. The Feed<video> object is a collection of videos. It contains a maximum of 25 videos. Hence, you need to display videos by using iterator entry. In this project, I used Listview to display the video entries. ListDisplay(entry) function is used to display each video entry. The image below shows the display in listview control. The below diagram shows the listview display.

youmanager.png

With the help of for loop, we pass a video object to the ListDisplay() function. ListDisplay function is used to display the contents of video. Every video object contains the following information. Title, Average rating, View count, Description, Author, VideoID, Commands count, medial location, thumbnail location, etc. Every video feed consists of 25 video entries maximum. Hence, I created a string array of size 25 to store these details. When the user clicks on the list item, other things are displayed.

To play video click on thumbnail, it passes videoId to shockwave object used to play the videos.

url+="&autoplay=1";

The above code can be used to play the video in autoplay mode. Here URL is taken from 1st entry of medialocation.

foreach (Google.GData.YouTube.MediaContent mediaContent in video.Contents)
{ 
if (i == 1)break;
medialocations[lvcount] = mediaContent.Url;i++;
} 

The above code is used to get medialocation. Similarly, thumbnails can be taken using MediaThumbnail object as an iterator.

Displaying feeds is easy but displaying Playlist information is slightly different. To display the contents of playlist, first you need to get playlist id.

int i = 0;playlistfeed = request.GetPlaylistsFeed(user);
foreach (Playlist pl in playlistfeed.Entries)
{
if (i == cmbSubService.SelectedIndex)
{
p = pl;
break;
}
i++;
}
string[] temp = p.Id.Split(':');
int ind = temp.GetUpperBound(0);
feedUrl = "http://gdata.youtube.com/feeds/api/playlists/"+temp[ind]+"?v=2";
videofeed = request.Get<Video>(new Uri(feedUrl));DisplayFeed();

The above code shows how to display the playlist contents. playlistfeed contains the list of playlists of a particular user. Then using iterator, we can get each playlist. Here cmbSubservice is combobox. Once you get a particular playlist from playlistfeed, you need to store playlist id in a string using split method. Here ind specifies the id of playlist in string array generated by split function. Then you can create the feedUrl. Once you get the feedUrl, you can get the contents using videofeed and DisplayFeed() function displays the playlist contents. Before calling DisplayFeed() function, you must check whether the playlist contains any videos. videofeed.totalresults will give the information about number of video entries. You can use it to check the playlist before calling DisplayFeed() function.

Uri Url = new Uri("http://gdata.youtube.com/feeds/api/videos/" + videoID);
Video video = yourequest.Retrieve<Video>(Url);
Feed<Comment> comment = yourequest.GetComments(video);
rtComents.Text = "";
foreach (Comment c in comment.Entries)
{
rtComents.Text += c.Content + "\n";
} 

The above code is used to display the comments for specific videos. First, you need to create a video URL. Next, create a video object. To receive comments, you need to create comment feed object using Getcomments(video) function. It is a collection of comments, hence you need Comment object as iterator to display the comments.

4: Pagination

Every feed contains only 25 videos. Hence, if you want to view more videos, you need to navigate through the pages. To make this happen, we need to use start-index feature of the feedUrl. If you didn't mention start-index in feedUrl, by default it is zero. Hence it can be used to display the other pages of feedUrl.

sindex += 25;
if (feedUrl.Contains('?'))
{
tempUrl = feedUrl + "&start-index=" + sindex.ToString();
}
else
{
tempUrl = feedUrl + "?start-index=" + sindex.ToString();
}
videofeed = yourequest.Get<Video>(new Uri(tempUrl));
DisplayFeed();

The above code shows how to navigate to the next page. Here sindex variable stores videofeed.start-index, i.e., the first page. List display uses 25 video entries. Hence when you click on next page sindex needs to be incremented by 25. Then it needs to be added to the feedUrl. Once it is added, videofeed stores the next set of videos. Using display feed method, we can display the next set of videos.

To navigate to previous page, just negate the sindex.

To jump to the specific page, use the below code:

sindex = i * 25 + 1;

Here sindex stores the start index. 25 means 25 videos displayed in a page. i represents the page number to jump.

References

History

  • 7th January, 2011: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ajit Hegde
Software Developer Freelancer
India India
Member
I completed my engineering in 2010.. Then i am working as freelancer.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionSystem.Net.WebException: The request was aborted: The request was canceledmemberJesusjenifer3 May '13 - 20:27 
Hi, I have already written code which is 50% of yours.i.e only for uploading purpose.It is working upto 10MB.More than that size it will System.Net.WebException: The request was aborted: The request was canceled this exception only.   Hence i have used your code.I am getting same...
GeneralMy vote of 5membernaren19914 Apr '13 - 19:31 
Really a nice article for beginners..
QuestionComment Errormembervi van hung26 Feb '13 - 16:15 
Hi Ajit Hegde, Thanks for sharing project Manage Youtube. When running the program, I get an error with the 3rd comment. Maybe problem is Captcha, now I want to get captcha.But when Debug captcha = null.   GDataRequestException : Execution of request failed:...
QuestionAccessing Demo Project without developer keymemberShashank_198712 Jul '12 - 18:55 
Hi Ajit, First of all thanks for this wonderful article. I have a query, that in the demo zip file, which is attached as part of this article, I am able to login and fetch feeds without giving any developer key. Can you please tell me, that how can I achieve this? TIA.
Bugsome errormemberspacevector24 May '12 - 1:10 
run the You Manager.exe,then i sign in. when i press the search button,i get a problem. the error tip as follow:     有关调用实时(JIT)调试而不是此对话框的详细信息, 请参见此消息的结尾。   ************** 异常文本 ************** Google.GData.Client.GDataRequestException: Execution of request failed:...
GeneralRe: some errormemberrealmct18 Sep '12 - 23:15 
I met the same problem and don't know what happen @@ Dose anyone can help me to solve this problem?   Thanks a lot Mark
GeneralMy vote of 5memberPravin Patil, Mumbai18 Oct '11 - 20:50 
Very nice article...
QuestionError uploading a videomembermoussafir927 Sep '11 - 4:32 
when I try to upload using the youtube api I get , a JIT error tells me , that the request is denied any help please?
AnswerRe: Error uploading a videomemberAjit Hegde22 Sep '11 - 2:40 
Why dont you post error message you are getting?
QuestionNicememberkvt1120 Jul '11 - 18:09 
Thanks a lot for posting. I had difficulties using the API, now its clear. However when creating an object of feed class I am getting nullreference exception.
GeneralRe: Nicememberkvt1126 Jul '11 - 17:49 
Hi..I forgot to give the developer key. It was always null. Now your code works beautifully. Thanks..cheers
Bugupload errormemberaboutjayesh5 Jul '11 - 22:49 
while uploading got following error...   Execution of request failed: http://uploads.gdata.youtube.com/feeds/api/users/default/uploads   plz help to fix it...
GeneralRe: upload errormemberAjit Hegde6 Jul '11 - 3:16 
Have you checked your username and password for youtube... Can you tell me what kind of error you get..?
QuestionHow can I contact you personally?memberOrenRose24 Jun '11 - 20:45 
I got something I would like to discuss with you...
Generalmessagemembermaster123web7 Jun '11 - 0:58 
how can I download video in this program?
GeneralRe: messagememberAjit Hegde19 Jun '11 - 17:47 
I think downloading video from youtube is not leagal..but you can do that by accessing the flash contents.
GeneralPlay/Pausemembertopromania1 Jun '11 - 3:48 
The tutorial is great, but i need to implement custom play/pause/seek. Any ideas how i can do that?
GeneralMy Vote of 5memberRaviRanjankr13 Mar '11 - 7:28 
WOW! I came to know about this article while answering a question. I recommend you article for taking help its a Excellent Article thanks for Share it
QuestionUpload errormemberTaltum8 Feb '11 - 2:53 
Hello,   When i tray to uplad a video to youtube, after 100 secons always give me the next error message:   "Execution Of Request Failed: http://uploads.gdata.youtube.com/feeds/api/users/default/uplodas"   How can i fix it?   I´m using .net, Youtube SDK (1.7)  ...
AnswerRe: Upload errormemberAjit Hegde9 Feb '11 - 1:50 
Hi   check your username and password for youtube account and youtube request setting.   Thank you
GeneralFull screenmemberalchemystic19 Jan '11 - 11:43 
do you have any ideea how can I play in full screen the video?
GeneralRe: Full screenmemberAjit Hegde20 Jan '11 - 17:08 
use windows media player instead of shock-wave object
GeneralShockwaveFlash problemmemberalchemystic14 Jan '11 - 21:15 
it works for me, but when i try to click on other thumbnails to play another movie the ShockwaveFlash does not load the other clip. Here is my code:   Uri Url = new Uri("http://youtube.com/v/" + videoIDs[selindex]); ShockwaveFlash1.LoadMovie(0, Url.ToString());   Thank you guys.
GeneralRe: ShockwaveFlash problemmemberAjit Hegde14 Jan '11 - 21:28 
Every video object contains a media location.   You must use it to play the video.   foreach (Google.GData.YouTube.MediaContent mediaContent in video.Contents) { if (i == 1) { break; } medialocations[lvcount] = mediaContent.Url; i++; }   Here...
GeneralRe: ShockwaveFlash problemmemberalchemystic15 Jan '11 - 2:45 
it works but in this case every time I play a clip a new YPlayer is created, i want to play using the same ShockwaveFlashObject. So I created a ShockwaveFlash object. When want to play in the first time the ShockwaveFlash object loads the...

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 7 Jan 2011
Article Copyright 2011 by Ajit Hegde
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid