Click here to Skip to main content
11,705,753 members (42,409 online)
Click here to Skip to main content

YouTube™ API for ASP.NET

, 21 Jul 2015 CPOL 258.8K 8.6K 174
Rate this:
Please Sign up or sign in to vote.
YouTube™ API for ASP.NET, AJAX-extended (C#).

DEMO: CLICK ON THE SAMPLE SCREENSHOT BELOW TO OPEN WebTV APP

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

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

Functional DEMO of the YouTube™ Player embedded in an ASP.NET web page, containing playlist w/daily updates and a set of navigation controls is available at [5].

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:

<%@ 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:

//****************************************************************************
// 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

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 (Views [6]). Currently 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 cumulative articles/tips views count in a range of 3 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 [7-11], 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
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
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): daily updates are implemented in current WebTV project [5]. Sample Demo screenshots of WebTV and selected Channels [7-11] are shown below.

Demo

This demo screenshot demonstrates the technique described above using GridView control's custom Template field. Click on the image-link below to open fully-functional WebTV app:

 

 
 

Top-100 Summertime Music Videos online channel, sample screenshots

 

 

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 [2]. Other controls provide additional navigation convenience (as in typical video player). The actual WebTV project also implements a scheduler that allows the items auto-progressing operational mode.

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. WebTV NY, powered by YouTube™ Embedded Video Player Extended API (C#)
  6. YouTube Top-100 of all time
  7. Best YouTube Classical Music Videos
  8. Bottle.IsNullOrEmpty(), Lounge Discussion
  9. Top-100 Summertime Music Videos (Online Channel)
  10. Top-100 Drinking Music Videos (Online Channel)
  11. Grammy Very Best (1959-2015) music videos (Online Channel)

License

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

Share

About the Author

DrABELL
President Infosoft International Inc
United States United States
Dr. A. Bell has 20+ years of Software and Electrical Engineering experience: Win/Web veteran, published 300+ articles and authored 37 inventions, credited for 10+ Enterprise level projects (>250k code lines); currently focused on .NET/WPF/C#, Javascript/jQuery, 'Big Data', AI, IoT and Mobile apps. Participated in App Innovation Contest (AIC 2102/2013) with several winning submissions. Sample projects/pubs follow:
  1. WebTV Project: Embedded YouTube Player (Goog #1 YouTube API for ASP.NET)
  2. Edumatter M12: School Math Calculators and Equation Solvers (contest winner)
  3. Engineering Calculator VOLTA-2013 (contest winner)
  4. Online 3 Fractions Calculator (#1 on Goog)
  5. Engineering Calculator VOLTA-814 for Windows
  6. Real-time NY Bus monitoring app
  7. Inflation Calculator
  8. PaydayNY-2015 Payroll Tax Calculator (Win)
  9. Multilingual Geocoder with Interactive Map
  10. Semantic Analyzer (Concordance Calculator)
  11. Prime Factoring Calculator

You may also be interested in...

Comments and Discussions

 
QuestionThank you Dr. for showing us the power of ASP.NET Pin
octapuslabs22-Jul-15 8:03
memberoctapuslabs22-Jul-15 8:03 
AnswerRe: Thank you Dr. for showing us the power of ASP.NET Pin
DrABELL22-Jul-15 9:07
professionalDrABELL22-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
professionalDrABELL19-Jul-15 1:11 
GeneralMy vote of 5 Pin
Humayun Kabir Mamun5-Feb-15 17:54
memberHumayun Kabir Mamun5-Feb-15 17:54 
GeneralRe: My vote of 5 Pin
DrABELL5-Feb-15 18:30
professionalDrABELL5-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
mentorMd. Marufuzzaman15-Aug-14 5:22 
Questionhow to upload video in youtube using javascript? Pin
amit_8320-Jan-14 18:13
memberamit_8320-Jan-14 18:13 
AnswerRe: how to upload video in youtube using javascript? Pin
DrABELL21-Jan-14 4:51
professionalDrABELL21-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
professionalDrABELL21-Aug-13 0:36 
GeneralMy vote of 5 Pin
John B Oliver8-May-13 12:05
memberJohn B Oliver8-May-13 12:05 
GeneralRe: My vote of 5 Pin
DrABELL8-May-13 13:14
memberDrABELL8-May-13 13:14 
GeneralMy vote of 5 Pin
TechnoGeek00114-Apr-13 23:03
memberTechnoGeek00114-Apr-13 23:03 
GeneralRe: My vote of 5 Pin
DrABELL15-Apr-13 1:15
memberDrABELL15-Apr-13 1:15 
GeneralNEW!! Embedded YouTube Player (WebTV project, Beta) Pin
DrABELL5-Jun-11 11:32
memberDrABELL5-Jun-11 11:32 
GeneralMy vote of 5 Pin
Mehedi_Hasan28-Oct-10 10:33
memberMehedi_Hasan28-Oct-10 10:33 
It help me to add you tube video on my developing site
Thanks.
GeneralRe: My vote of 5 Pin
DrABELL7-Dec-10 6:20
memberDrABELL7-Dec-10 6:20 
Generalsome query Pin
makhar22-Jul-10 17:47
membermakhar22-Jul-10 17:47 
GeneralRe: some query Pin
DrABELL7-Dec-10 6:32
memberDrABELL7-Dec-10 6:32 

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 | Terms of Use | Mobile
Web02 | 2.8.150819.1 | Last Updated 21 Jul 2015
Article Copyright 2009 by DrABELL
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid