C# YouTube : Google API





This week we had the opportunity to do some integration with YouTube for one of our clients - upload, edit, remove and displaying videos all in the "comfort" of their own website.

Initially we thought that we will probably need to do this using raw calls etc to YouTube (which we'd probably wrap into some sexy reusable classes), but luckily Google did all the work for us already via their data API - in a few lines of code one can for example upload a video to YouTube (like you will see in the following post).

Before you continue, you need to download the Google Data API (if you didn't already) and register for a YouTube developer key, you'll also need a username and password to access YouTube.

Lets jump into some code...

You'll need to add the following Google API references to your solution.



The following namespaces (located within the added references) are required:

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


Next you need to create an instance of the YouTubeRequestSettings class to which we pass all the settings required to connect to YouTube:

 
YouTubeRequestSettings settings = new YouTubeRequestSettings("applicationName", "developerKey", "userName", "passWord");
 

Upload a video to YouTube

 
YouTubeRequest request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = "Test";
newVideo.Tags.Add(new MediaCategory("Animals", YouTubeNameTable.CategorySchema));
newVideo.Description = "Testing Testing Testing";
newVideo.YouTubeEntry.Private = false;
newVideo.YouTubeEntry.MediaSource = new MediaFileSource("C:\\test.wmv", "video/x-ms-wmv");
request.Upload(newVideo);
 

In the preceding snippet we pass our settings instance to a YouTubeRequest to which we pass a video using its Upload method.

Notice the Tags collection to which we add a MediaCategory - we're required to add our video to at least one category, a list of available categories can be found here.

When uploading large files to YouTube it might be prudent to set the YouTubeRequest's timeout, like see in the following piece of code.

 
((GDataRequestFactory)request.Service.RequestFactory).Timeout = 9999999;
 

List your uploaded videos

 
public IEnumerable<Video> ListMyVideos()
{
    YouTubeRequest request = new YouTubeRequest(settings);
    YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultUploads);
    Feed<Video> feed = request.Get<Video>(query);
    return feed != null ? feed.Entries : null;
}
 

In the snippet above we essentially create a simple query that returns all the videos the current logged in user (via YouTubeRequestSettings) uploaded to YouTube.

Get a video

 
public Video GetMyVideo(string uploader, string videoID)
{
    YouTubeRequest request = new YouTubeRequest(settings);
    Uri uri = new Uri(String.Format("http://gdata.YouTube.com/feeds/api/users/{0}/uploads/{1}", uploader, videoID));
    return request.Retrieve<Video>(uri);
}
 

In the preceding snippet we pass our YouTube username (minus its domain) and the ID of the video we wish to retrieve (you can get a list of videoID's in the snippet ahead of this one).

The video object returned by the Retrieve method (on the request), contains all kinds of useful information about the retrieved video e.g. length of the video, links to generated thumbnails etc.

Remove a video

 
public void Remove(Video video)
{
    YouTubeRequest request = new YouTubeRequest(settings);
    request.Delete(video);
}
 

To remove your video from YouTube is quite simple, simply pass the video retrieved from the GetVideo method (like seen in this post) to the Remove method seen above.

Update a video

 
public void Update(Video video, string title, string description)
{         
    YouTubeRequest request = new YouTubeRequest(settings);
    video.Title = title;
    video.Description = description;
    request.Update(video);
}
 

Similar to the Remove method, we simply pass our retrieved video to the YouTubeRequest object.

Display a video

Displaying a video is probably the easiest part in the whole process - in the past we used object/embed tags, but I noticed that YouTube migrated to iframes like seen in the following snippet.

 
<iframe title="YouTube video player" width="640" height="390" src="http://www.youtube.com/embed/somevideoID" frameborder="0" allowfullscreen></iframe>
 

Note: You can disable "related videos", by passing rel=0 to the url in the iframe eg. http://www.youtube.com/embed/somevideoID?rel=0 or even default it to HD by passing hd=1 to the url eg. http://www.youtube.com/embed/somevideoID?hd=1.

Above that, there is tons of customizations & settings we can set within YouTube itself for our uploaded videos - disabling comments, visibility (private / public / unlisted) etc.

Have fun...

Additional Reading
Developer's YouTube Guide for .NET




Post/View comments
 

C# : Custom configuration section



Generally when we develop applications using .NET, we use our app/web.config as a place where we expose certain settings to our application(s) (its even possible to encrypt it for those who dare or feel the higher calling to use it to store sensitive information).

Your config file will likely look something like this:
 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="1" value="a" />
    <add key="2" value="b" />
    <add key="3" value="c" />
  </appSettings>
</configuration>
 

Next we'll wack a reference to the system.configuration assembly into our application, which will allow us to access our settings via the ConfigurationManager - like seen in the following image.



Now we can always simply use the general appSettings section to store some rudimentary settings, but what if we wish to create a separate appSettings section specific to our company for example?

In the following snippet we do exactly that, we add a new section called "Company.appSettings", using one of the default section handlers, observe:
 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="Company.appSettings" type="System.Configuration.NameValueFileSectionHandler" />
  </configSections>
  <Company.appSettings>
    <add key="1" value="a" />
    <add key="2" value="b" />
    <add key="3" value="c" />
  </Company.appSettings>
  <appSettings />
</configuration>
 

Programmatically we'll access the newly added section like this:
 
NameValueCollection settings = ConfigurationManager.GetSection("Company.appSettings") as NameValueCollection;
if (settings != null)
{
	foreach (string key in settings)
	{
		Console.WriteLine("{0} : {1}", key, settings[key]);
	}
}
 

An alternative to using notation like Company.appSettings is that you can instead separate your custom sections using the sectionGroup node like so:
 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="Company">
      <section name="appSettings" type="System.Configuration.NameValueFileSectionHandler" />
    </sectionGroup>
  </configSections>
  <Company>
    <appSettings>
      <add key="1" value="a" />
      <add key="2" value="b" />
      <add key="3" value="c" />
    </appSettings>
  </Company>
  <appSettings />
</configuration>
 

Accessing the settings from code will look something like this:
 
NameValueCollection settings = ConfigurationManager.GetSection("Company/appSettings") as NameValueCollection;
 

This is obviously not the limit to the customization possibilities - you might have seen/used the following settings in your config file when setting up .NET for sending mail:
 
<system.net>
  <mailSettings>
    <smtp>
      <network host="smtp.somehost.net" />
    </smtp>
  </mailSettings>
</system.net>
 

It is quite easy to create our own custom section similar to what we see in the preceding snippet.

The following snippet will give you a quick idea on how to create your own custom section, note inherited classes ConfigurationSection and ConfigurationElement.

 
using System;
using System.Configuration;
 
namespace Sections
{
    public class XSection : ConfigurationSection
    {
        [ConfigurationProperty("x", DefaultValue = false, IsRequired = false)]
        public Boolean X
        {
            get
            {
                return (Boolean)this["x"];
            }
            set
            {
                this["x"] = value;
            }
        }
 
        [ConfigurationProperty("y")]
        public YElement Y
        {
            get
            {
                return (YElement)this["y"];
            }
            set
            {
                this["y"] = value;
            }
        }
    }
 
    public class YElement : ConfigurationElement
    {
        [ConfigurationProperty("y1", DefaultValue = "value", IsRequired = false)]
        public String Y1
        {
            get
            {
                return (String)this["y1"];
            }
            set
            {
                this["y1"] = value;
            }
        }
 
        [ConfigurationProperty("y2", IsRequired = true)]
        public Int32 Y2
        {
            get
            {
                return (Int32)this["y2"];
            }
            set
            {
                this["y2"] = value;
            }
        }
    }
}
 

The custom section will look something like this in your config file:
 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="XSection" type="Sections.XSection, ConsoleApplication1"  allowLocation="true"
        allowDefinition="Everywhere" />
  </configSections>
  <XSection x="true">
    <y y1="test1" y2="10" />
  </XSection>
</configuration>
 

In order to access the custom node from code, you need to do the following:
 
Sections.XSection xsection = ConfigurationManager.GetSection("XSection") as Sections.XSection;
if (xsection != null)
{
    Console.WriteLine(xsection.X);
    Console.WriteLine(xsection.Y.Y1);
    Console.WriteLine(xsection.Y.Y2);
}
 

There is a lot of other options also available, like the configurationcollection attribute - which allows us to add collections as settings to our config files - be sure to read the additional reading at the bottom of the page.

Additional Reading:
http://msdn.microsoft.com/en-us/library/2tw134k3.aspx
http://msdn.microsoft.com/en-us/library/system.configuration.configurationcollectionattribute.aspx




Post/View comments
 
First 6 7 8 9 10 11 12 13 14 15 Last / 65 Pages (130 Entries)

Latest Posts

MS SQL: Parameter Sniffing


2012-05-21 22:38:48

Be the best stalker you can be


2011-12-13 22:33:54

Top 5 posts

Moving items between listboxes in ASP.net/PHP example


Move items between two listboxes in ASP.net(C#, VB.NET) and PHP
2008-06-12 17:07:43

Simple WYSIWYG Editor


Creating a WYSIWYG textbox for your website is actually quite simple.
2007-02-01 12:00:00

C# YouTube : Google API


Post on how to integrate with YouTube using the Google Data API
2011-03-12 08:37:51

Populate a TreeView Control C#


Populate a TreeView control in a windows application.
2009-08-27 16:01:03

Cross Browser Issues: Firefox Word Wrapping


Firefox word wrapping issues
2008-06-09 09:51:21