How to use Google Data API in ASP.NET MVC. Part 2 – YouTube

Posted: May 25th, 2010 | Author: | Filed under: ASP.NET, ASP.NET MVC, C#, Web Services | Tags: , , , | 8 Comments »

YouTube Data APIPreviously on this series, I had talked about  How to use Google Data API in ASP.NET MVC to interact with Google Analytics. In this second part I’m going to show you how to store and retrieve videos on/from YouTube using Google Data API and YouTube API.

YouTube is the largest and most popular video sharing website and since Google has acquired it and integrated its API into GData it’s been an ultimate choice for developers to choose it as a safe and powerful backend for their videos.

I should mention that there are two types of YouTube APIs for developers:

  1. The Data API which lets you incorporate YouTube functionality into your own application or website. You can perform searches, upload videos, create playlists, and more.
  2. The Player APIs which give you control over YouTube video playback on your website. Configure basic settings, drive the player interface, or even build your own player controls.

One may add the third Custom Player to the list above but indeed it’s not an API.

In our tutorial we will go through the first item: Data API; the second is left for JS and AS developers and maybe Pedram would write about it!

Well, let’s go!

I’ll divide my blog post main content into two seperate topics: Storing Videos and Retrieving Video.

Storing Videos on YouTube

First of all your have to prepare required tools to interact with YouTube Data API. Here’s what you would do:

  1. Sign up for a developer key. You will also need your Google account username and password.
  2. Download YouTube SDK.

After installing YouTube SDK, reference the following assemblies in your project:

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.YouTube;
using Google.GData.Extensions.MediaRss;
using Google.YouTube;

Whenever you want to send/receive data to/from YouTube you should authenticate yourself (your application) against it. The following helper method first checks if there is already an authenticated request object in Session and use it for the current request as well, otherwise it will create a new YouTubeRequest using the YouTubeRequestSettings which we provide:

public static YouTubeRequest GetRequest()
{

    var request = HttpContext.Current.Session["YTRequest"] as YouTubeRequest;

    if (request == null)

    {

        var settings = new YouTubeRequestSettings("SampleWebApp", "NA",
                              ConfigurationManager.AppSettings["YouTubeAPIDeveloperKey"],
                              ConfigurationManager.AppSettings["YouTubeUsername"],
                              ConfigurationManager.AppSettings["YouTubePassword"]);

        request = new YouTubeRequest(settings);

        HttpContext.Current.Session["YTRequest"] = request;

    }

    return request;

}

Now we are ready to create a view to let the end user browse his video file and upload it to YouTube:

<%
    var youTubeRequest = GetRequest();
    var newVideo = new Video { "VideoTitle", Description = "VideoDescription" };

    newVideo.Media.Categories.Add(new MediaCategory("All")); // You can assign any category here.

    newVideo.Keywords = "samplekeyword";
    newVideo.YouTubeEntry.Private = false;

    var token = youTubeRequest.CreateFormUploadToken(newVideo);
    var postUrl = token.Url;
    var tokenValue = token.Token;
%>

<% if ((bool)ViewData["UploadError"])
{%>
    <%= "Error uploading the video!" %>
<%} %>

<form action="<%= postUrl %>?nexturl=http://localhost/upload/success" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="hidden" name="token" value="<%= tokenValue %>" />
    <input type="submit" value="Upload!" />
</form>

The code above consisted of two parts; first we create a YouTubeRequest object (using the helper method which we built before) and then we prepare the required YouTube Video object which contains our video meta data information. One thing I’ve experienced using this Video object is that you MUST specify a MediaCategory and also some Keywords; otherwise you will receive a bad request error.  After assigning the required properties to our Video object, we need to request a token value. A token is used by YouTube API to recognize your request and prevent duplicate requests. This token provide us with a Url property that would be used to post uploaded file to. We’ve also implemented a simple error handling section to show a friendly error message if uploading process failed. The second part of the code shows an HTML <form> tag that lets you upload a video file. Action value is our “postUrl” variable which we created before plus a nextUrl query string value – the page which you want to return back to when the upload process is completed.

When you uploaded a video successfully you would be automatically redirected to the page which you specified in nextUrl query string value. YouTube API sends back some information along with this nextURL. You will receive Video ID (something like “mLw7ySQFuV4″) and an integer Status Code. If Status Code doesn’t equal 200 it means something went wrong and you should return a friendly error message and ask your user try again; otherwise, upload process has been successful. The action method behind “/success” URL is shown below:

public ActionResult Success(int status, string id)

{

    if (status != 200) // Upload was not successful. Checking the status code.

    {

        ViewData["UploadError"] = true;

        return RedirectToAction("Upload");

    }

    // Now you should store uploaded video information using your Data Access layer / Repository.
    // This is the place in which you should set Video ID returned back to this action from YouTube API.
    // This ID (in form of XXXXXXXXXXX) will be used to retrieve a video to edit or play.

   return RedirectToAction("Manage");

}

Learn more about different status codes here.

I recommend you split your upload operation into two steps: first let the end user enter video meta data like title, description, tags, etc. and store them in your database then ask him to upload and attach the video file to this record. This way it’s easy to track video properties state when an error accures and you have to show back the upload view again.

Congratulations! You uploaded and stored your first video onYouTube from inside your application using YouTube API.

Retrieving a Video from YouTube

Now you have a real video under the account that you have used to authenticate against YouTube. Two other common scenarios you may want to implement are editing an existing video (either changing meta data information or replacing the video file with a new one) and the second is playing that video.

In both scenarios we should retreive the video object first. Logic behind this, is similar to what we’ve implemented to create a new video entry with a some minor differences:

var youTubeRequest = YouTubeHelper.GetRequest();

var videoEntryUrl = new Uri(string.Format("http://gdata.youtube.com/feeds/api/users/{0}/uploads/{1}",

        ConfigurationManager.AppSettings["YouTubeUserId"], youTubeId));

var youTubeVideo = youTubeRequest.Retrieve<Google.YouTube.Video>(videoEntryUrl);

Now you have the existing Video object ready and can change its meta data information or create a new token value to upload a new video file.

Playing the video (using YouTube pre-built player) is very easy as well. Just pass Video ID to Play action method and retrieve it from YouTube as shown in the code above; then pass it to the respected view:

public ActionResult Play(string youTubeId)

{

    var youTubeRequest = YouTubeHelper.GetRequest();

    var videoEntryUrl = new Uri(string.Format("http://gdata.youtube.com/feeds/api/users/{0}/uploads/{1}",

            ConfigurationManager.AppSettings["YouTubeUserId"], youTubeId));

    var youTubeVideo = youTubeRequest.Retrieve<Google.YouTube.Video>(videoEntryUrl);

    return View(youTubeVideo);

}

Final step is using the model in a view page. I have used popular SWFObject to ebmed YouTube player in my view:

<script type="text/javascript">

    var params = { allowScriptAccess: "always" };

    var atts = { id: "myytplayer" };

    swfobject.embedSWF("http://www.youtube.com/v/<%= Model.VideoId %>?enablejsapi=1&playerapiid=ytplayer",

        "ytapiplayer", "625", "556", "8", null, null, params, atts);

</script>

You’re done!

Please note that I have tried to simplify all steps and customize everything for an ASP.NET MVC app scenario and in real world scenarios your should provide your end user with more features and customization options.


8 Comments on “How to use Google Data API in ASP.NET MVC. Part 2 – YouTube”

  1. 1 Tweets that mention How to use Google Data API in ASP.NET MVC. Part 2 – YouTube « Mahdi Taghizadeh -- Topsy.com said at 10:53 pm on May 25th, 2010:

    [...] This post was mentioned on Twitter by Tobin Titus, Lee Dumond. Lee Dumond said: Cool article about using the YouTube API in ASP.NET MVC http://bit.ly/a1ZuJO [...]

    [WORDPRESS HASHCASH] The comment’s server IP (74.112.128.30) doesn’t match the comment’s URL host IP (74.112.128.10) and so is spam.

  2. 2 Mehdi Mousavi said at 11:37 am on May 27th, 2010:

    Well done!
    Keep up the good work.

  3. 3 Emmanuel Morales said at 9:50 pm on May 27th, 2010:

    “If Status Code equals 200 it means something went wrong…”. I think you mean if it doesn’t equal 200. Thanks for sharing.

  4. 4 Mahdi Taghizadeh said at 8:08 pm on May 28th, 2010:

    @Emmanuel:
    Thank you for your attention. I fixed it.

  5. 5 Morteza said at 2:36 pm on June 8th, 2010:

    Thanks for the article. It really helped.
    I was getting an error message and could not get it to work until I found that this line is causing the grief:
    newVideo.Media.Categories.Add(new MediaCategory(“All”));

    There is no category called: “All” and this causes an exception. instead you can use: “Film”

    for a list of categories please refer to YouTube upload video page.

  6. 6 Sachin said at 10:56 am on June 15th, 2010:

    You have done well. Its very helpful. But can you add one thing more which will be more helpful for a fresher who wants to learn. Please mention the page extention which you are using to code. that mean on which type of page you are coding (like .aspx,.asmx, .cs)

  7. 7 Mahdi Taghizadeh said at 11:45 am on June 15th, 2010:

    I’ve used MVC pattern for this tutorial. What you’re talking about refers to WebForms method. Please read more about these two topics to understand the difference between them.

  8. 8 manish said at 2:34 pm on January 31st, 2012:

    how to get private video


Leave a Reply

  •