Dynamically Output A List of YouTube Videos In ASP.NET

Published on
-
6 min read

I recently needed to dynamically display a list of YouTube video’s from a specific YouTube account. If you plan to output the list of video’s straight from the YouTube’s RSS feed into your .NET application don’t bother. The RSS feed is not structured in a nice enough format to output all the information you may need with ease. For example, video ratings, time, etc are all in the same XML block.

As you can see from the screenshot below, the ASP.NET page I created outputs all the information that you will probably want to show (if it doesn’t then it should give you a good starting point).

YouTubeReaderScreenshot

Before creating your own custom YouTube .NET application you will need to carry out two things:

  1. Go to the YouTube API Toolswebsite and download the “Google Data API SDK”. Once you have installed this on your computer. You will need to copy three dll’s from one of the sample projects:

    • Google.GData.Client.dll
    • Google.GData.Extensions.dll
    • Google.GData.YouTube.dll

    These dll's can be copied to your new project.

  2. Register a Developer Key. This is important! Without the developer key, your custom YouTube application will not work.

To create the page (above), copy the following code:

ASPX.CS Page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Extensions.MediaRss;
using Google.YouTube;
using Google.GData.YouTube;
using System.Text;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    private string YouTubeChampionshipChannel;
    private string YouTubeClientID;
    private string YouTubeDeveloperKey;
    public string YouTubeMovieID;
    public DataTable dtVideoData = new DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        //Pass User Name to the YouTube link
        YouTubeChampionshipChannel = "MotoGP";

        //Add the YouTube Developer keys.
        //Register a Developer Key at: http://code.google.com/apis/youtube/dashboard
        YouTubeClientID = "test";
        YouTubeDeveloperKey = "testabc123";

        CreateVideoFeed();

        //Assign the first video details on page load.
        if (String.IsNullOrEmpty(YouTubeMovieID))
        {
            YouTubeMovieID = dtVideoData.Rows[0]["VideoID"].ToString();
            lblDescription.Text = dtVideoData.Rows[0]["Description"].ToString();
        }

    }

    private void CreateVideoFeed()
    {
        YouTubeRequestSettings settings = new YouTubeRequestSettings("MotoGP Channel", YouTubeClientID, YouTubeDeveloperKey);
        YouTubeRequest request = new YouTubeRequest(settings);

        //Link to the feed we wish to read from
        string feedUrl = String.Format("http://gdata.youtube.com/feeds/api/users/{0}/uploads?orderby=published", YouTubeChampionshipChannel); ;
                
        dtVideoData.Columns.Add("Title");
        dtVideoData.Columns.Add("Description");
        dtVideoData.Columns.Add("DateUploaded");
        dtVideoData.Columns.Add("Ratings");
        dtVideoData.Columns.Add("NoOfComments");
        dtVideoData.Columns.Add("VideoID");
        dtVideoData.Columns.Add("Duration");

        DataRow drVideoData;

        Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));

        //Iterate through each video entry and store details in DataTable
        foreach (Video videoEntry in videoFeed.Entries)
        {
            drVideoData = dtVideoData.NewRow();

            drVideoData["Title"] = videoEntry.Title;
            drVideoData["Description"] = videoEntry.Description;
            drVideoData["DateUploaded"] = videoEntry.Updated.ToShortDateString();
            drVideoData["Ratings"] = videoEntry.YouTubeEntry.Rating.Average.ToString();
            drVideoData["NoOfComments"] = videoEntry.CommmentCount.ToString();
            drVideoData["VideoID"] = videoEntry.YouTubeEntry.VideoId;
            drVideoData["Duration"] = videoEntry.YouTubeEntry.Duration.Seconds.ToString();

            dtVideoData.Rows.Add(drVideoData);            
        }

        repVideoList.DataSource = dtVideoData;
        repVideoList.DataBind();
    }

    protected void repVideoList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DataRowView drVideo = (DataRowView)e.Item.DataItem;

            LinkButton showVideo = (LinkButton)e.Item.FindControl("btnShowVideo");
            Literal title = (Literal)e.Item.FindControl("Title");
            Literal description = (Literal)e.Item.FindControl("Description");
            Literal ratings = (Literal)e.Item.FindControl("Ratings");
            Literal noOfComments = (Literal)e.Item.FindControl("NoOfComments");
            Literal duration = (Literal)e.Item.FindControl("Duration");

            showVideo.CommandArgument = drVideo["VideoID"].ToString();
            title.Text = drVideo["Title"].ToString();
            description.Text = drVideo["Description"].ToString();
            ratings.Text = drVideo["Ratings"].ToString();
            noOfComments.Text = drVideo["NoOfComments"].ToString();
            duration.Text = drVideo["Duration"].ToString();

        }
    }
    protected void repVideoList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        // Pass the YouTube movie ID to flash
        YouTubeMovieID = e.CommandArgument.ToString();

        if (YouTubeMovieID == e.CommandArgument.ToString())
        {
            lblDescription.Text = ((Literal)e.Item.FindControl("Description")).Text;
        }

    }
}

ASPX Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="margin: 10px;">
        <div style="float: left; width: 300px; height: 400px; overflow: scroll;">
            <asp:Repeater ID="repVideoList" runat="server" OnItemDataBound="repVideoList_ItemDataBound"
                OnItemCommand="repVideoList_ItemCommand">
                <HeaderTemplate>
                    <table>
                </HeaderTemplate>
                <ItemTemplate>
                    <tr>
                        <td>
                            <asp:LinkButton ID="btnShowVideo" runat="server">Show Video</asp:LinkButton>
                            <br>
                            <strong>
                                <asp:Literal ID="Title" runat="server"></asp:Literal></strong>
                            <br />
                            <asp:Literal ID="Description" runat="server"></asp:Literal>
                            <br />
                            Rating: <asp:Literal ID="Ratings" runat="server"></asp:Literal>
                            <br />
                            Comments: <asp:Literal ID="NoOfComments" runat="server"></asp:Literal>
                            <br />
                            Duration: <asp:Literal ID="Duration" runat="server"></asp:Literal>
                            <br />
                            <br />
                        </td>
                    </tr>
                </ItemTemplate>
                <FooterTemplate>
                    </table>
                </FooterTemplate>
            </asp:Repeater>
        </div>
        <div style="float: left; margin-left: 15px;width:600px;2">
            <object width="480" height="385" style="float: left; clear: both; margin-bottom: 10px;">
                <param name="movie" value="http://www.youtube.com/v/<%=YouTubeMovieID %>&hl=en&fs=1&rel=0">
                </param>
                <param name="allowFullScreen" value="true"></param>
                <param name="allowscriptaccess" value="always"></param>
                <embed src="http://www.youtube.com/v/<%=YouTubeMovieID %>&hl=en&fs=1&rel=0" type="application/x-shockwave-flash"
                    allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed>
            </object>
            <div style="float: left;">
                <asp:Label ID="lblDescription" runat="server"></asp:Label>
            </div>
        </div>
    </div>
    </form>
</body>
</html>

This is just the beginning on what the YouTube API has to offer. For more information, visit the YouTube API website (http://code.google.com/apis/youtube/2.0/developers_guide_dotnet.html).

* Post Updated 18/06/2009 – You can output YouTube video’s via RSS feed *

Before you go...

If you've found this post helpful, you can buy me a coffee. It's certainly not necessary but much appreciated!

Buy Me A Coffee

Leave A Comment

If you have any questions or suggestions, feel free to leave a comment. Your comment will not only help others, but also myself.