Click here to Skip to main content
15,607,524 members
Articles / Web Development / HTML5
Article
Posted 2 Oct 2009

Stats

211.7K views
11.1K downloads
183 bookmarked

YouTube™ API for ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.96/5 (46 votes)
21 Jul 2015CPOL6 min read
YouTube™ API for ASP.NET, AJAX-extended (C#).

Link to WebTV app based on YouTube API for ASP.NET

Fig. 1. Sample screenshot

Note: all images are included for Demo purpose only. Please do not copy/redistribute.

Introduction

Embedded Video Players, based either on Adobe Flash™, Microsoft Silverlight™ or pure HTML5 video technology can dramatically enhance web page aesthetics and overall user experience. This article demonstrates the coding technique for embedding the rather popular YouTube™ Video Player (which is built on the aforementioned Adobe Flash™) in ASP.NET web pages via an API written in C# and a Microsoft AJAX extension.

The project contains:

  • The default web page "Default.aspx" with the corresponding code-behind: both to be placed in the Application root directory (ASP.NET 2.0+).
  • Code module "YouTubeScriptGenerator.cs" to be placed in the App_Code directory.
  • AJAX library file (AjaxControlToolkit.dll) to be placed in the Bin directory

Background 

The Embedded Video Player is capable of streaming (playing back) the audio/video content, available from the www.youtube.com website (note:  subscription is not required in order to use this feature). The video item ID is encoded into a query string, looking like a random set of characters, for example: x_4CNvG1Q_M, with corresponding full address string: http://www.youtube.com/watch?v=x_4CNvG1Q_M (in particular sample presumably pointing to the video clip titled: “Anastasia Volochkova dancing to Adiemus by Karl Jenkins).

The easiest way to embed the YouTube™ Video Player is to go to the www.youtube.com website, select the item of interest, and then copy/paste the corresponding snippet, located in the text box marked “embed”, into your own web page, and Voila! YouTube™ site provides several customization options regarding the video player size (this includes standard settings specified as: 340x285, 445x364, 500x405, 660x525) and color palette selection. The ASP.NET YouTube™ API described in this article provides a much wider set of customization features.

Using the Code

The practical steps to embed the YouTube™ Video Player into an ASP.NET Web Page are as follows:

  1. Create or open an ASP.NET Web Site using either Microsoft Visual Studio (any edition) or the Visual Web Developer Express edition.
  2. Download the compressed (.zip) file. Extract the components into your web application directory.
  3. Set the embedded YouTube™ Video Player dimension: W/H.
  4. Customize the YouTube™ Video Player border options.
  5. Customize the YouTube™ Video Player startup settings:
    • First item to play
    • Autoplay mode
    • Starting the Video/Audio streaming at a predefined time.

Following are the code snippets corresponding to the demo ASPX web page with the associated code-behind module:

ASP.NET
<%@ 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">
<%@ Register assembly="AjaxControlToolkit" 
   namespace="AjaxControlToolkit" 
   tagprefix="cc1" %>
<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>DEMO | YouTube API for ASP.NET</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <asp:UpdatePanel ID="UpdatePanel1" 
                    runat="server" updatemode="Conditional" >
            <ContentTemplate> 
            <div>
                <!-- ALL CONTENT IS SHOWN FOR DEMO PURPOSE ONLY-->
                <asp:DropDownList ID="cmbPlaylist" 
                           runat="server" AutoPostBack="True">
                    <asp:ListItem Value="XP9tzWtLFus">Anastasia 
                                  Volochkova(Adiemus)</asp:ListItem>
                    <asp:ListItem Value="raRaxt_KM9Q">Sound Of Silence 
                                 (Masters of Chant)</asp:ListItem>
                </asp:DropDownList>
                <br /><br />
                <asp:Literal ID="Literal1" runat="server"></asp:Literal>
            </div>
            </ContentTemplate>
          </asp:UpdatePanel>
          
          <hr />
          <h3>Sample Demo: Anastasia Volochkova, Russian prima ballerina 
                                   dancing "Adiemus"</h3>
          <h4>Initial settings: 640x480, autoplay=0</h4>
          <hr />
          <h4>
              More Demo available at: <a href="www.webinfocentral.com" 
              target="_blank">www.webinfocentral.com</a>
          </h4>
          <hr />
        </form>
    </body>
</html>

The code-behind:

C#
//****************************************************************************
// Module           :   Default.aspx.cs
// Description      :   YouTube API for ASP.NET: code behind
// Developer        :   Alexander Bell (Infosoft International Inc)
// DateCreated      :   09/10/2009
// LastModified     :   09/12/2009
//****************************************************************************
// DISCLAIMER: This Application is provide on AS IS basis without any warranty
//****************************************************************************
//****************************************************************************
// TERMS OF USE     :   ALL YouTube CONTENT IS SHOWN AS DEMO SAMPLE ONLY
//                  :   You can use it at your sole risk
//****************************************************************************
using System;
public partial class _Default : System.Web.UI.Page 
{
    // player width
    private int _W = 640;
    // player height
    private int _H = 480;
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            #region Start mode customization via Web Query String
            int idx = 0;
            int auto = 0;
            string qry = "";
            // Autostart
            try {
                qry = "auto"; 
                qry = (Request.QueryString[qry] == null) ? "" : Request.QueryString[qry];
                if (qry != "") { auto = int.Parse(qry); }
            } catch { }
            // Item index
            try {
                qry = "item"; 
                qry = (Request.QueryString[qry] == null) ? "" : Request.QueryString[qry];
                if (qry != "") { idx = int.Parse(qry); }
            } catch { }
            #endregion
            // get value from the list for selected index
            cmbPlaylist.SelectedIndex = idx;
            // generate script on page load
            Literal1.Text = YouTubeScript.Get(cmbPlaylist.SelectedValue, auto, _W, _H);
        }
        else
        {
            // generate script on page postback
            Literal1.Text = YouTubeScript.Get(cmbPlaylist.SelectedValue, 0, _W, _H);
        }
    }
}

WebTV Project

The section above described powerful video streaming technology based on YouTube player embedded in ASP.NET web page. What's next? The logical extension would be adding a playlist controls and bing it to the underlying database. ASP.NET GridView control can perfectly fit the purpose: it allows creation of the templated field with advanced CSS styling [4,5] (other option would be implementing full-fleged MVC, but for such relatively simple task it seems an overkill). The possible implementation is shown below in sample screenshot.

Backend Database

The backend Database could be of any type. Its main Table should contain a mandatory VideoID field (unique key), which identifies the video item on YouTube (it's used as a web query parameter, for example:VidID=9bZkp7q19f0 corresponds to the most popular music-video of all time "Gangnam Style" by PSY). The other fields are optional, like: Title, Performer, Views, Likes, Duration, etc, so the generic video items Table creation schema may look like the following snippet:

Table 1. Video Items master table

Hide   Copy Code

SQL
CREATE TABLE VideoItems
(
  ID int NOT NULL PRIMARY KEY,
  VidID varchar(20) NOT NULL UNIQUE,
  Title nvarchar(255) NOT NULL,
   Performer nvarchar(255),
   Duration int,
   Views long,
   Likes long,
   Dislikes long
)

Adding Features to WebTV

The backend database linked to the Youtube Video Player provides plenty of room for further customization/extension. The first quite obvious 'data mining' extension would be sorting the items based on their popularity. Currently (note: corresponding to the year 2015) their are 2 'Gigamen' (Justing Bieber and PSY) with more that 1 billion views per a single video item and one recently added to the giga-club 'GigaLady' (Katy Perry). Most likely Taylor Swift will join the "Giga-club" some time soon (stay tune). A word to add: this astronomical popularity of music-video genre is sort of mind-boggling! With a sort of bitter irony, my Codeproject articles/tips cumulative views count in the range of 4 million put me in a category of just entry-level cat videos (so far, the most popular "Nyan Cat" video accounts for approx 122 mega-views). Playlist could be also customized by music genre, e.g. Classical music, etc, thus creating the video channels under topical umbrella as discussed in the following sub-chapter.

Adding Channels

Possible further extension of this video-streaming technology would be creating channels by adding two more Tables to the backend DB, in addition to master table of VideoItems described above:

Table 2. Video Channels
SQL
CREATE TABLE VideoChannels
(
  CID int NOT NULL PRIMARY KEY,
  Channel varchar(50) NOT NULL UNIQUE,
  Description nvarchar(255)
)
Table 3. Video Channels-Items join table
SQL
CREATE TABLE ChannelItems
(
  CVID int NOT NULL PRIMARY KEY,
  VidID varchar(20) NOT NULL,
  CID int NOT NULL,
  Position int NOT NULL,
  Comments nvarchar(255),
)

where VidID and CID and Foreign Keys linking the table to the master VideoItems and Channels tables, correspondingly. Also, Unique constraint could be added to composite (VidID, CID) index in order to avoid duplicate video items appear in the same channel. Position field specifies where the item should appear in the playlist (channel), so the corresponding SQL Select statement must include the ORDER BY [Position] clause.

As mentioned above, content of the channels can be dynamically updated on time basis (daily, weekly, monthly, etc).

Demo

This demo screenshot demonstrates the technique described above using GridView control's custom Template field.

 

 
Image 2   Image 3

Top-100 Summertime Music Videos online channel, sample screenshots

 

Image 4   Image 5

WebTV app w/daily scheduler, sample screenshots

Note: all images are included for Demo purpose only. Please do not copy/redistribute.

In screenshot images shown above, the section to the left contains embedded YouTube player: section to the right is made of GridView control linked to the app backend Database with functionality extended via Javascript. Other controls provide additional navigation convenience (as in typical video player).

Points of Interest

Smooth transition between video items is achieved by using the Microsoft AJAX extension: notice the UpdatePanel where resides the Literal1 control containing the corresponding JavaScript.

YouTube video playback customization

Other points of interest may include a video playback customization, related to the linked (not embedded) YouTube video items. These customization technique allows to:

  • Start video playback at specific position (set offset in minutes and second)
  • Specify the number of video re-plays (Loop)
  • Start the video playback in Full Screen Mode
  • Turn “Related Video” options ON/OFF
  • Set the Autoplay option
  • Set the Playback Video Quality

History

  • Updated with more customization options and YouTube stats on 08/01/2014
  • 04/30/2013 Time to switch to jQuery 2.0 (done)
  • 04/30/2013 Made this player HTML5-compatible (key changes: <iframe class='youtube-player' type='text/html' frameborder='0' id="player"></iframe> and the rest in jQuery derived from this).
  • 7/20/2015 The concept and implementation of WebTV Channels technical discussion has been added.

References

  1. YouTube™ Embedded Video Player: Extended API (C#)
  2. Click/select row in ASP.NET GridView or HTML table
  3. Nested GridView controls in ASP.NET: best practices
  4. Hyperlinked Images in ASP.NET GridView
  5. Bottle.IsNullOrEmpty(), Lounge Discussion

License

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


Written By
Engineer
United States United States
Dr. Alexander Bell (aka DrABell) is a seasoned full-stack Software (Win/Web/Mobile) and Data Engineer. He holds PhD in Electrical and Computer Engineering, authored 37 inventions and published 100+ technical articles; currently focused on Microsoft Azure Cloud and Android Mobile development projects. Alex participated in App Innovation Contests (AIC 2102/2013) w/multiple winning submissions. Sample apps/publications:

  1. HTML5/CSS3 graphic enhancement: buttons, inputs
  2. HTML5 Tables Formatting: Alternate Rows, Color Gradients, Shadows
  3. Azure web app: Engineering Calculator VOLTMATTER
  4. Azure: NYC real-time bus tracking app
  5. Quiz Engine powered by Azure cloud
  6. 'enRoute': Real-time NY City Bus Tracking Web App
  7. Advanced CSS3 Styling of HTML5 SELECT Element
  8. Aggregate Product function extends SQL
  9. YouTube™ API for ASP.NET

Comments and Discussions

 
Questionupdates Pin
kiquenet.com24-May-16 10:26
professionalkiquenet.com24-May-16 10:26 
QuestionThank you Dr. for showing us the power of ASP.NET Pin
George Tourtsinakis22-Jul-15 8:03
George Tourtsinakis22-Jul-15 8:03 
AnswerRe: Thank you Dr. for showing us the power of ASP.NET Pin
DrABELL22-Jul-15 9:07
DrABELL22-Jul-15 9:07 
QuestionNice Article Pin
Santhakumar Munuswamy @ Chennai18-Jul-15 22:48
professionalSanthakumar Munuswamy @ Chennai18-Jul-15 22:48 
AnswerRe: Nice Article Pin
DrABELL19-Jul-15 1:11
DrABELL19-Jul-15 1:11 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun5-Feb-15 17:54
Humayun Kabir Mamun5-Feb-15 17:54 
GeneralRe: My vote of 5 Pin
DrABELL5-Feb-15 18:30
DrABELL5-Feb-15 18:30 
SuggestionThough I'm not test it (UAT) yet but nice poset, I think <b><big></big>Tips/Tricks</b> section you may consider so far. Pin
Md. Marufuzzaman15-Aug-14 5:22
professionalMd. Marufuzzaman15-Aug-14 5:22 
Questionhow to upload video in youtube using javascript? Pin
amit_8320-Jan-14 18:13
professionalamit_8320-Jan-14 18:13 
AnswerRe: how to upload video in youtube using javascript? Pin
DrABELL21-Jan-14 4:51
DrABELL21-Jan-14 4:51 
GeneralMy vote of 5 Pin
BadassAlien20-Aug-13 22:37
professionalBadassAlien20-Aug-13 22:37 
GeneralRe: My vote of 5 Pin
DrABELL21-Aug-13 0:36
DrABELL21-Aug-13 0:36 
GeneralMy vote of 5 Pin
John B Oliver8-May-13 12:05
John B Oliver8-May-13 12:05 
GeneralRe: My vote of 5 Pin
DrABELL8-May-13 13:14
DrABELL8-May-13 13:14 
GeneralMy vote of 5 Pin
npdev1314-Apr-13 23:03
npdev1314-Apr-13 23:03 
GeneralRe: My vote of 5 Pin
DrABELL15-Apr-13 1:15
DrABELL15-Apr-13 1:15 
GeneralNEW!! Embedded YouTube Player (WebTV project, Beta) Pin
DrABELL5-Jun-11 11:32
DrABELL5-Jun-11 11:32 
GeneralMy vote of 5 Pin
Mehedi_Hasan28-Oct-10 10:33
Mehedi_Hasan28-Oct-10 10:33 
GeneralRe: My vote of 5 Pin
DrABELL7-Dec-10 6:20
DrABELL7-Dec-10 6:20 
Generalsome query Pin
makhar22-Jul-10 17:47
makhar22-Jul-10 17:47 
GeneralRe: some query Pin
DrABELL7-Dec-10 6:32
DrABELL7-Dec-10 6:32 

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

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