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

Manage YouTube using C# and Youtube API 1.6

, 7 Jan 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
I describe some of the things about Youtube video feeds

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)

Share

About the Author

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

Comments and Discussions

 
QuestionSystem.Net.WebException: The request was aborted: The request was canceled PinmemberJesusjenifer3-May-13 20:27 
GeneralMy vote of 5 Pinmembernaren19914-Apr-13 19:31 
QuestionComment Error Pinmembervi van hung26-Feb-13 16:15 
QuestionAccessing Demo Project without developer key PinmemberShashank_198712-Jul-12 18:55 
Bugsome error Pinmemberspacevector24-May-12 1:10 
GeneralRe: some error Pinmemberrealmct18-Sep-12 23:15 
GeneralMy vote of 5 PinmemberPravin Patil, Mumbai18-Oct-11 20:50 
QuestionError uploading a video Pinmembermoussafir927-Sep-11 4:32 
AnswerRe: Error uploading a video PinmemberAjit Hegde22-Sep-11 2:40 
QuestionNice Pinmemberkvt1120-Jul-11 18:09 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

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