Integrate Social Media: The YouTube Model

By Bill Hatfield  |  eMail Email    Print Print  Post a comment

The Heart of the Matter: The YouTube Model

As I mentioned earlier, models are most-often used to hold common data and pass that data from controllers to views and back again. Models are also used to provide helper classes to provide utility-like functions for the controller. Often these functions generate data and therefore fit the conceptual idea for a model nicely.

In this application, you’ll create a model that contains the meat of the Web API interaction.

Right-click on the Models folder in Solution Explorer and select Add / New Item… In the Add New Item dialog, click on the Code category along the left, then click the Class item in the middle. At the bottom, name the class YouTubeModels.cs and click Add. The class is opened showing a bare-bones class definition. Replace the code there with the code here.

using System.Threading.Tasks;
using Google.Apis.Services;
using Google.Apis.YouTube.v3;
using Google.Apis.YouTube.v3.Data;

namespace MvcApplication2.Models
{
    public class YouTubeVideo
    {
        public string ID { get; set; }
        public string Title { get; set; }
    }

    public class YouTubeHelper
    {
        public async Task SearchVideos()
        {
            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                ApiKey = "REPLACE ME",
                ApplicationName = this.GetType().ToString()
            });

            var searchListRequest = youtubeService.Search.List("id,snippet");
            searchListRequest.Q = "Visual Studio";
            searchListRequest.Type = "video";
            searchListRequest.RelevanceLanguage = "eng";
            searchListRequest.SafeSearch = SearchResource.ListRequest.SafeSearchEnum.Strict;
            searchListRequest.MaxResults = 30;
            searchListRequest.Order = SearchResource.ListRequest.OrderEnum.Date;
            
            var searchListResponse = await searchListRequest.ExecuteAsync();
            return searchListResponse;
        }
    }
}

 

Replace MvcApplication2 in this listing with the name you chose for your project. You must also replace the string “REPLACE ME” using the API Key you received from the Google API Console. This ends up being sent along with your request to Google so they know you’re authorized to use the API.

That’s a lot of code to dump on you all at once, so let me walk through it to make it clear what’s going on.

The using lines that point to Google.Apis provide access to the Google libraries we added with NuGet Manager. The YouTubeVideo class is used to pass around the two most important bits of information about any video – the unique ID of the video and the video’s title. You’ll see this put to use shortly.

The YouTubeHelper class is where the heavy lifting gets done. This class consists of only a single method: SearchVideos(). It accepts no parameters, but it does return something. But what, exactly? If you haven’t used the asynchronous features provided by the .NET Framework, this may look a bit strange to you.

        public async Task<SearchListResponse> SearchVideos()
                {

 

The async keyword is a special modifier that identifies this function as one that will execute asynchronously. That is, the system doesn’t wait for this function to complete before continuing on after it is called. And it’s a requirement that async functions return a Task-type object. However, since most people who create functions want the function to return their own value, Task has a generic implementation. That means that it accepts a data type when it’s created. That data type is then returned along with the Task. So in this case, an object of type SearchListResponse will be returned. This is a class from the Google.Apis libraries.

The next step is to define exactly how the search is to work.

            var searchListRequest = youtubeService.Search.List("id,snippet");
            searchListRequest.Q = "Visual Studio";
            searchListRequest.Type = "video";
            searchListRequest.RelevanceLanguage = "eng";
            searchListRequest.SafeSearch = SearchResource.ListRequest.SafeSearchEnum.Strict;
            searchListRequest.MaxResults = 30;
            searchListRequest.Order = SearchResource.ListRequest.OrderEnum.Date;

 

The first line creates a variable that will represent the request that’ll be sent. The “id,snippet” indicates that two pieces of information sent back for each search result – the unique ID of the video and an object of type Snippet which contains the title, description and other details about the video.

The rest is just defining properties on the search request.

  • Q contains the actual string to search for. In this case, we want videos that are related to Visual Studio.
  • Type indicates what we’re searching – in this case only videos, not channels or users.
  • RelevanceLanguage tells YouTube that we’d prefer English videos. This doesn’t completely filter out non-English videos if they are a good match, but simply prefers English.
  • SafeSearch is set to an enum which specifies that we only see strictly safe videos. (You never know!)
  • MaxResults determines the maximum number of videos returned.
  • Order indicates the sort-order of the returned videos – in this case, we want to see the most recent ones first.

These and other properties available give you a fine grained control of your search results.

The last lines finally ship the request off and receive the results back, returning them to the caller.

            var searchListResponse = await searchListRequest.ExecuteAsync();
            return searchListResponse;

 

As you see, the SearchListRequest object has a method which executes the query. Notice that its name implies that it works asynchronously. If so, how can we receive the results back before the return is executed? That’s what the await keyword does. It simply says, “Yes, I know you’re typically an asynchronous function, but if it’s all the same to you, I’ll just sit here and wait until you’re done.” Handy!

The only thing remaining is this thing called searchListResponse – what is it? How do you access its contents? Patience… all in good time.

All Hail the Controller!

You won’t need to create a new controller. The home controller will do just fine for our purposes. Open it and check out the Index() function. This is the one that gets executed when the user first arrives at this site. (Much like index.html does for simpler Web applications.)

First, at the top of the file, add a using clause that points to your model’s namespace.

using MvcApplication2.Models;

Of course you’ll need to replace MvcApplication2 with the name of your project.

Next, replace the Index()  function skeleton with this code.

        public async Task<actionresult> Index()
        {
            ViewBag.Message = "Productivity is in your hands.";

            var ytHelp = new YouTubeHelper();
            var videos = await ytHelp.SearchVideos();

            return View(videos);
        }</actionresult>

 

First, note that this is an async function returning a Task as you saw before. The rest is pretty simple. The ViewBag.Message is just used in the view to display text in the header.  The YouTubeHelper class is instantiated and then SearchVideos() is called.  Notice here, too, we are using the await keyword to just sit around until the usually-async function is finished. Once it is, we have our videos and pass them along to the view associated with this Index() function.


Page 4 of 5

Previous Page
1 2 3 4 5
Next Page

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  • HTML5 eBook

    HTML5 ebook

    HTML5 is the new standard that is expected to take over the Web. New versions of browsers are already starting to support the advanced features. Learn why HTML5 is important and discover how to use start using it today.
  • Html5 Logo