Save and Display YouTube Videos on ASP.NET Website

About two months ago, a member in the asp.net forums asked a question regarding similar issue. For this purpose, I have prepared short article that shows how you can achieve this using ASP.NET Repeater (or similar) control, a database table with three columns and few code-lines to make this work.

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.

Download the complete source code:
C#.NET or VB.NET

Hope this blog post is useful to someone out there.

I am waiting for your feedback.

Regards,
Hajan

Published Monday, June 21, 2010 12:35 AM by hajan

Comments

# re: Save and Display YouTube Videos on ASP.NET Website

Monday, June 21, 2010 12:42 AM by winseealn@hotmail.com

Hajan,

Its a good article.

I want to create a blog on asp.net how to that? and what is the link to create a blog.?

# Twitter Trackbacks for Save and Display YouTube Videos on ASP.NET Website - Hajan's Blog [asp.net] on Topsy.com

Pingback from  Twitter Trackbacks for                 Save and Display YouTube Videos on ASP.NET Website - Hajan's Blog         [asp.net]        on Topsy.com

# re: Save and Display YouTube Videos on ASP.NET Website

Monday, June 21, 2010 2:36 AM by hajan

@winseealn,

Thank you for your feedback.

As per your question, please use the Feedback Forum in this asp.net community website. There are already open threads regarding the same question you have.

# re: Save and Display YouTube Videos on ASP.NET Website

Monday, June 21, 2010 4:31 AM by Mahendra

Good code for YouTube vedio display in .aspx page

# re: Save and Display YouTube Videos on ASP.NET Website

Monday, June 21, 2010 7:02 AM by habdulrauf

Nice and easy one.

# Save and Display YouTube Video Files on ASP.NET Website.

Monday, June 21, 2010 2:59 PM by Hajan's Blog

MKDOT.NET Trackbacks for Save and Display YouTube Video Files on ASP.NET Website.

# Save and Display YouTube Videos on ASP.NET Website - Hajan's Blog

Monday, June 21, 2010 10:14 PM by WebDevVote.com

You are voted (great) - Trackback from WebDevVote.com

# re: Save and Display YouTube Videos on ASP.NET Website

Tuesday, June 22, 2010 2:25 AM by Jalpesh P. Vadgama

Nice post buddy... Thanks for nice tip

# re: Save and Display YouTube Videos on ASP.NET Website

Tuesday, June 22, 2010 4:42 AM by hajan

Thank you all for your comments.

I really appreciate your feedback.

# re: Save and Display YouTube Videos on ASP.NET Website

Wednesday, June 23, 2010 9:07 PM by SaaS

thanks for the help!!

# re: Save and Display YouTube Videos on ASP.NET Website

Friday, June 25, 2010 3:59 AM by ivaneft

Very useful post hajan.

Good job :)

# re: Save and Display YouTube Videos on ASP.NET Website

Friday, July 23, 2010 2:05 AM by monishafriends

easy to understand...

thnks....

# re: Save and Display YouTube Videos on ASP.NET Website

Monday, July 26, 2010 7:59 AM by Tabrez

thanks for attachment of display vedio & store vedio in sqldatabase.

but when we upload more than 1 vedio it take more time in uploading vedio.

# re: Save and Display YouTube Videos on ASP.NET Website

Monday, July 26, 2010 8:53 AM by hajan

@Tabrez, are you speaking about uploading more than one video at a time? If so, probably you've modified the source code that I've uploaded with this blog. If thats correct, please post the part of the code you've modified, otherwise reply back with some more details like where it goes slower and I will make detailed review.

Thank you for your valuable feedback.

# re: Save and Display YouTube Videos on ASP.NET Website

Thursday, August 12, 2010 9:18 AM by Enes

Fala mnoguu

# re: Save and Display YouTube Videos on ASP.NET Website

Monday, October 11, 2010 8:53 AM by Avdhesh kumar

i got this codes. it's very helpful.my problem sloves this code.

Thanks sir

Avdhesh kumar

software developer

# re: Save and Display YouTube Videos on ASP.NET Website

Monday, November 01, 2010 10:40 AM by Sarabjeet Singh

AweSome tut Bro... awesome ... i was searching for such tut for my website.. and you provided just that i needed.. keep the good work up.. from Sarabjeet (INDIA)

# re: Save and Display YouTube Videos on ASP.NET Website

Saturday, December 04, 2010 9:29 AM by naga vara prasad

thanks a lot for giving the code

but while doing we must be careful at hl and fs

# re: Save and Display YouTube Videos on ASP.NET Website

Friday, December 24, 2010 7:05 AM by manojnavale0405

Nice yaar

# re: Save and Display YouTube Videos on ASP.NET Website

Wednesday, January 05, 2011 4:00 AM by neelam

Nice and clean code...

tahnx a ton.

# re: Save and Display YouTube Videos on ASP.NET Website

Tuesday, February 01, 2011 2:14 AM by abhishek

great ,thanks!

# re: Save and Display YouTube Videos on ASP.NET Website

Saturday, February 05, 2011 7:47 PM by jaspal singh

it is help for me , very nice

# re: Save and Display YouTube Videos on ASP.NET Website

Thursday, March 17, 2011 12:54 PM by asp_loverrr

nice code

What do you mean by this

"^[^v]+v=(.{11}).*"

# re: Save and Display YouTube Videos on ASP.NET Website

Thursday, March 17, 2011 1:45 PM by aspx

nice code

what do you mean by this "^[^v]+v=(.{11}).*"

# re: Save and Display YouTube Videos on ASP.NET Website

Thursday, March 17, 2011 3:35 PM by hajan

@asp_loverrr, that's Regular Expressions that finds YouTube video ID from the given youtube URL string.

Example valid URL: www.youtube.com/.../jpiU5Y8luOQ&hl=en_US&fs=1

where 'jpiU5Y8luOQ' is the ID of the video file. The regular expression will ensure the video file id is found.

You can learn more about regular expressions here: www.regular-expressions.info/tutorial.html

Hope this helps.

# re: Save and Display YouTube Videos on ASP.NET Website

Sunday, March 27, 2011 2:12 AM by Gyan Prakash

Thanks.

Nice one.

# re: Save and Display YouTube Videos on ASP.NET Website

Sunday, March 27, 2011 8:57 AM by hajan

@Gyan, always welcome! :)

Please post your queries if you want to read something of your interestes... I will take care to write more about what you really want to read.

Regards,

Hajan

# re: Save and Display YouTube Videos on ASP.NET Website

Saturday, April 02, 2011 6:41 AM by hajan_likes

nice code

by the way is it possible to make it into thumbnail size with play button like in facebook?

# re: Save and Display YouTube Videos on ASP.NET Website

Tuesday, April 05, 2011 4:12 AM by Vivek Kumar

It's really helpful for me. Thank you so much

# re: Save and Display YouTube Videos on ASP.NET Website

Thursday, April 21, 2011 11:18 PM by isra

AWESOME <3

# re: Save and Display YouTube Videos on ASP.NET Website

Friday, April 29, 2011 5:26 AM by sandeep_patil

Thanks.

# re: Save and Display YouTube Videos on ASP.NET Website

Thursday, May 26, 2011 6:57 AM by KalipSSO

HOW DO WE USE THIS?

HOW DO I ADD THIS ON HTML OR PHP SITE?

# re: Save and Display YouTube Videos on ASP.NET Website

Thursday, May 26, 2011 7:28 AM by KalipSSO

how do i use this in a php page?

# re: Save and Display YouTube Videos on ASP.NET Website

Thursday, May 26, 2011 12:22 PM by hajan

Hi KalipSSO,

The post goal is to show solution in ASP.NET WebForms platform. So, doing this in PHP may differ a lot. Still, you should understand the code and make your own PHP functions. The HTML markup is pretty much the same, you just don't have Repeater control in PHP, therefore you will need to make your own for or foreach cycle to render data. Or, the last option would be to do this in ASP.NET ;)

Thanks,

Hajan

# 1600+ downloads of source code files

Saturday, June 04, 2011 5:28 PM by Hajan's Blog

For some of the blogs I have posted in the previous several months, I have included source code of the

# re: Save and Display YouTube Videos on ASP.NET Website

Saturday, June 18, 2011 12:06 AM by akin

usefull comments..

# re: Save and Display YouTube Videos on ASP.NET Website

Monday, July 25, 2011 2:53 AM by mangesh

please send me code how to display you tube videos in asp.net label control

# re: Save and Display YouTube Videos on ASP.NET Website

Saturday, July 30, 2011 2:41 PM by yokesh

awesome code really helped me a lot..............

thankx guys....

i have one doubt

Is it possible to make it into thumbnail size with  just play button like  in facebook

# re: Save and Display YouTube Videos on ASP.NET Website

Thursday, August 04, 2011 5:09 AM by hebsi

good................

# re: Save and Display YouTube Videos on ASP.NET Website

Friday, September 02, 2011 7:09 AM by vivek sahu

Thanks Nice artical

# re: Save and Display YouTube Videos on ASP.NET Website

Monday, September 05, 2011 7:30 AM by smith

Hi hajan can i get a coding regarding url extractor where it should not use a database and also it should extract the keywords related which i give as an input

# re: Save and Display YouTube Videos on ASP.NET Website

Monday, January 30, 2012 12:05 PM by karan

thnxxxxxxxxxxxx bro. u solve my big big problam... thank you so much.. for uploading this wonderful info..................once again thanxx alot

# re: Save and Display YouTube Videos on ASP.NET Website

Sunday, February 05, 2012 6:20 AM by karan

hi i need a title of description of video.. which i uploaded.. plz give me replay.....how i can get the title a and description///

# re: Save and Display YouTube Videos on ASP.NET Website

Sunday, February 05, 2012 10:58 AM by hajan

The post doesn't deal withy anything else than just extracting video for the given URL. There are some ways to extract title/description from the video, but I will need to write totally new blog post for that purpose... stay tuned...

Leave a Comment

(required) 
(required) 
(optional)
(required)