Tutoriaux
Récemment, on ma demandée d'extraire dynamiquement et d'afficher une liste de vidéo en provenance d'un compte prévis de YouTube dans une application ASP.NET. Si vous vous êtes dit tout de suite qu'il est bien simple de faire cela grâce au feed RSS alors vous vous êtes trompé. En effet, le fil RSS n'est pas très bien structuré afin d'afficher ce que nous voulons facilement. Par exemple, le temps ou bien la note du vidéo sont sous dans le même bloc XML. Voyons donc comment extraire correctement ces informations.
Pour commencer, visiter le site YouTube API Tools et télécharger "Google Data API SDK". Une fois installé récupéré les fichiers suivants dans le projet démo et copier les dans le répertoire de votre solution ASP.NET;
- Google.GData.Client.dll
- Google.GData.Extensions.dll
- Google.GData.YouTube.dll
Enregistrez-vous afin d'obtenir une clé développeur. Ceci est très important, car sans cette clé, il vous sera impossible que votre application fonctionne correctement.
Dans votre projet, importer les librairies nécessaires;
using Google.GData.Client; using Google.GData.Extensions; using Google.GData.Extensions.MediaRss; using Google.YouTube; using Google.GData.YouTube;
Voici donc ensuite le code source utilisé et commenté pour vous;
private string YouTubeChampionshipChannel;
private string YouTubeClientID;
private string YouTubeDeveloperKey;
public string YouTubeMovieID;
public DataTable dtVideoData = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
//Nom du compte YouTube
YouTubeChampionshipChannel = "NomDuCompte";
//Clé développeur
YouTubeClientID = "test";
YouTubeDeveloperKey = "testabc123";
CreateVideoFeed();
//Assigné le premier vidéo YouTube lors du Page_Load
if (String.IsNullOrEmpty(YouTubeMovieID))
{
YouTubeMovieID = dtVideoData.Rows[0]["VideoID"].ToString();
lblDescription.Text = dtVideoData.Rows[0]["Description"].ToString();
}
}
private void CreateVideoFeed()
{
YouTubeRequestSettings settings = new YouTubeRequestSettings("MotoGP Channel", YouTubeClientID, YouTubeDeveloperKey);
YouTubeRequest request = new YouTubeRequest(settings);
// Lien vers le Fil RSS des vidéo
string feedUrl = String.Format("http://gdata.youtube.com/feeds/api/users/{0}/uploads?orderby=published", YouTubeChampionshipChannel); ;
dtVideoData.Columns.Add("Title");
dtVideoData.Columns.Add("Description");
dtVideoData.Columns.Add("DateUploaded");
dtVideoData.Columns.Add("Ratings");
dtVideoData.Columns.Add("NoOfComments");
dtVideoData.Columns.Add("VideoID");
dtVideoData.Columns.Add("Duration");
DataRow drVideoData;
Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
// Récupération des vidéos et de leurs informations
foreach (Video videoEntry in videoFeed.Entries)
{
drVideoData = dtVideoData.NewRow();
drVideoData["Title"] = videoEntry.Title;
drVideoData["Description"] = videoEntry.Description;
drVideoData["DateUploaded"] = videoEntry.Updated.ToShortDateString();
drVideoData["Ratings"] = videoEntry.YouTubeEntry.Rating.Average.ToString();
drVideoData["NoOfComments"] = videoEntry.CommmentCount.ToString();
drVideoData["VideoID"] = videoEntry.YouTubeEntry.VideoId;
drVideoData["Duration"] = videoEntry.YouTubeEntry.Duration.Seconds.ToString();
dtVideoData.Rows.Add(drVideoData);
}
repVideoList.DataSource = dtVideoData;
repVideoList.DataBind();
}
protected void repVideoList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView drVideo = (DataRowView)e.Item.DataItem;
LinkButton showVideo = (LinkButton)e.Item.FindControl("btnShowVideo");
Literal title = (Literal)e.Item.FindControl("Title");
Literal description = (Literal)e.Item.FindControl("Description");
Literal ratings = (Literal)e.Item.FindControl("Ratings");
Literal noOfComments = (Literal)e.Item.FindControl("NoOfComments");
Literal duration = (Literal)e.Item.FindControl("Duration");
showVideo.CommandArgument = drVideo["VideoID"].ToString();
title.Text = drVideo["Title"].ToString();
description.Text = drVideo["Description"].ToString();
ratings.Text = drVideo["Ratings"].ToString();
noOfComments.Text = drVideo["NoOfComments"].ToString();
duration.Text = drVideo["Duration"].ToString();
}
}
protected void repVideoList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
YouTubeMovieID = e.CommandArgument.ToString();
if (YouTubeMovieID == e.CommandArgument.ToString())
{
lblDescription.Text = ((Literal)e.Item.FindControl("Description")).Text;
}
}
Pour ce qui est de l'affichage, j'ai insérer un contrôle "repeater" sur la page :
<asp:Repeater ID="repVideoList" runat="server" OnItemDataBound="repVideoList_ItemDataBound" OnItemCommand="repVideoList_ItemCommand"> <HeaderTemplate> <table> </HeaderTemplate> <ItemTemplate> <tr> <td> <asp:LinkButton ID="btnShowVideo" runat="server">Voir le Video</asp:LinkButton><br> <strong><asp:Literal ID="Title" runat="server"></asp:Literal></strong><br /> <asp:Literal ID="Description" runat="server"></asp:Literal><br /> Rating: <asp:Literal ID="Ratings" runat="server"></asp:Literal><br /> Comments: <asp:Literal ID="NoOfComments" runat="server"></asp:Literal><br /> Duration: <asp:Literal ID="Duration" runat="server"></asp:Literal><br /> </td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater>Ainsi qu'un contrôle HTML objet afin d'afficher le vidéo sélectionné et un label pour la description;
<object width="480" height="385" style="float: left; clear: both; margin-bottom: 10px;"> <param name="movie" value="http://www.youtube.com/v/<%=YouTubeMovieID %>&hl=en&fs=1&rel=0"></param> <param name="allowFullScreen" value="true"></param> <param name="allowscriptaccess" value="always"></param> <embed src="http://www.youtube.com/v/<%=YouTubeMovieID %>&hl=en&fs=1&rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed> </object>
<asp:Label ID="lblDescription" runat="server"></asp:Label>
Vu: 870
Commentaires (2)

...
Par Administrator , juin 15, 2009
Par Administrator , juin 15, 2009
En effet, une erreur c'est glissé dans le code. J'ai oublié de déclarer les variables suivantes tout juste avant le page_load :
private string YouTubeChampionshipChannel;
private string YouTubeClientID;
private string YouTubeDeveloperKey;
public string YouTubeMovieID;
public DataTable dtVideoData = new DataTable();
Voyez plus, haut, le code a été corrigé.
private string YouTubeChampionshipChannel;
private string YouTubeClientID;
private string YouTubeDeveloperKey;
public string YouTubeMovieID;
public DataTable dtVideoData = new DataTable();
Voyez plus, haut, le code a été corrigé.
Ecrivez un commentaire
Navigation
Connexion
Publicités
MeilleursPrix.ca
|
|
















Ne manque-t-il pas quelque chose ?
J'obtiens de nombreuses alertes du genre :
Erreur1Le nom 'YouTubeChampionshipChannel' n'existe pas dans le contexte actuel
Erreur2Le nom 'YouTubeClientID' n'existe pas dans le contexte actuel
Pourtant, les dll sont bien référencées...
Pourriez-vous mettre les sources en téléchargement svp ?