Wednesday, October 19, 2011

Save and Display YouTube Videos on ASP.NET Website


As we already know, YouTube shares the HTML <object /> which can be embedded in any web site by simple copy/paste of the html for each video file.
A sample example of the html for embedding YouTube video is as follows
   1: <object width="640" height="385">
   2: <param name="movie" value="http://www.youtube.com/v/jpiU5Y8luOQ&hl=en_US&fs=1&"></param>
   3: <param name="allowFullScreen" value="true"></param>
   4: <param name="allowscriptaccess" value="always"></param>
   5: <embed src="http://www.youtube.com/v/jpiU5Y8luOQ&hl=en_US&fs=1&" 
   6:        type="application/x-shockwave-flash" 
   7:        allowscriptaccess="always" 
   8:        allowfullscreen="true" 
   9:        width="640" 
  10:        height="385">
  11: </embed>
  12: </object>
There are three standard <params> and the embed tag which is important to make this work properly. Anyway, you should not concern much about this because you will use a standard format of this HTML object example that will be generated automatically in your website. You should pay attention a bit more on the format of the YouTube URL link, which is as follows:
http://www.youtube.com/v/<video-file-id>&hl=en_US&fs=1
where hl is the hosted language and fs if is 1 will allow the full screen button to shows up, 0 will disallow.
We can leave the hl and fs query string parameters by default. The only part in the url string we should care about is the <video-file-id>.
Someone would ask, why paying attention to the ID of the video, when user can simply paste the link in a ASP.NET text box and just display it as it is. Well, the problem is that user can enter url while he/she was searching in related items or even in different cases when the youtube link does not have the same format, which cannot be embedded as it is, so we need to get the video id and put it in a url link with standard format. Usually, the URLs instead of showing /v/<video-id>, these are shown as v=<video-id> which does not show correctly the video link when embedded to the html object shown previously.

Let’s start with the ASP.NET part.
First of all, drag and drop ASP.NET Repeater control from the Data Controls. Also you will need SqlDataSource, but of course, you may use any other data sources or even bind the data control even programmatically in code-behind.
Here is the sample ASPX code I have created so far:
<html xmlns="http://www.w3.org/1999/xhtml" >
<
head id="Head1" runat="server">
<
title></title>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:TextBox ID="TextBox1" runat="server" Width="461px"></asp:TextBox>
<
asp:Button ID="btnAddLink"
runat="server" Text="Add Link" onclick="btnAddLink_Click" />
</
div>
<
asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<
ItemTemplate>
<
object width="480" height="385"><param name="movie" value='<%#DataBinder.Eval(Container.DataItem, "url") %>'></param>
<
param name="allowFullScreen" value="true"></param>
<
param name="allowscriptaccess" value="always"></param>
<
embed src='<%#DataBinder.Eval(Container.DataItem, "url") %>' type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385">
</
embed>
</
object>
<
br />
</
ItemTemplate>
</
asp:Repeater>
<
asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MySampleDBConnectionString %>"
SelectCommand="SELECT [url], [description], [id] FROM [YouTubeVideos]">
</
asp:SqlDataSource>
</
form>
</
body>
</
html>

Short explanation:
1. I have created one TextBox which will be used to enter the YouTube URL link (in any format which comes from the YouTube video service)
2. Button which will be used for inserting the link into database.
3. There is Repeater control with ItemTemplate containing the HTML tags for embedding the video with <%# DataBinder.Eval(Container.DataItem, “url”) %> which will contain the URL tag retrieved from database.
4. SqlDataSource with ConnectionString pointing to MS SQL Server database where connection string is in the Web.config file. You can create new connection string using the SqlDataSource Wizards or by typing it manually (if you are experienced to do that so).
If you have noticed in the SqlDataSource, there is a SelectCommand which selects three columns ([url], [description] and [id]) from table with name [YouTubeVideos]. Here is the SQL Script to create the sample database table which I am using in this article:
CREATE TABLE YouTubeVideos --creates table where we will save YouTube Videos(
id int not null primary key identity(1,1),
url varchar(1000) not null,
[description] text)
  
The last thing, which we always leave it for the end, is the C#.NET / VB.NET code.
Here we have the code behind the Add Link Button click event, method to extract the ID of the video using Regular Expression and method to check for Duplicate videos in DB.
First, do not forget to add the following directives
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;

- Function to get the YouTube Video ID
private string GetYouTubeID(string youTubeUrl)
{
//RegEx to Find YouTube ID
Match regexMatch = Regex.Match(youTubeUrl, "^[^v]+v=(.{11}).*",
RegexOptions.IgnoreCase);
if (regexMatch.Success)
{
return "http://www.youtube.com/v/" + regexMatch.Groups[1].Value +
"&hl=en&fs=1";
}
return youTubeUrl;
}
I have found this method on the following website: here
The code behind the Add Link button click event is as follows:
protected void btnAddLink_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MySampleDBConnectionString"].ToString());
string url = TextBox1.Text;
if (url.Contains("youtube.com"))
{
string ytFormattedUrl = GetYouTubeID(url);

if (!CheckDuplicate(ytFormattedUrl))
{
SqlCommand cmd = new SqlCommand("INSERT INTO YouTubeVideos ([url]) VALUES ('" + ytFormattedUrl + "')", con);
using (con)
{
con.Open();
int result = cmd.ExecuteNonQuery();
if (result != -1)
{
Repeater1.DataBind();
}
else { Response.Write("Error inserting new url!"); }
}
}
else { Response.Write("This video already exists in our database!"); }
}
else
{
Response.Write("This URL is not a valid YOUTUBE video link because it does not contain youtube.com in it");
}
}
and at end, I have created method to check whether the video exists or not
public bool CheckDuplicate(string youTubeUrl)
{
bool exists = false;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MySampleDBConnectionString"].ToString());
SqlCommand cmd = new SqlCommand(String.Format("select * from YouTubeVideos where url='{0}'",youTubeUrl), con);

using (con)
{
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
exists = (dr.HasRows) ? true : false;
}

return exists;
}
Mainly, thats it.
You can format the apperance of the html inside the Repeater control, which is very flexible for customized HTML.