Helper Twitter avec ASP.NET Web Pages

par Tom FitzMacken

Important

Les helpers Twitter sont obsolètes. Pour connaître les derniers outils d’engagement de Twitter pour les sites web, consultez Vue d’ensemble de Twitter pour les sites web.

Cette rubrique et cette application montrent comment ajouter un helper Twitter à votre projet WebMatrix 3. Il contient le code d’assistance Twitter et montre comment appeler les méthodes d’assistance.

Ce code pour le fichier Twitter.cshtml a été développé par Tian Pan de Microsoft.

Versions logicielles utilisées dans le tutoriel

  • pages Web ASP.NET (Razor) 3

Ce tutoriel fonctionne également avec pages Web ASP.NET 2.

Introduction

Cette rubrique montre comment ajouter une assistance Twitter à votre application et utiliser la syntaxe Razor pour appeler les méthodes d’assistance. Twitter Helper facilite l’intégration de boutons et de widgets Twitter dans votre application. Pour utiliser un widget Twitter, tel que le chronologie d’un utilisateur ou les résultats de recherche d’un hashtag, vous devez d’abord créer le widget sur Twitter. Après avoir créé votre widget, vous recevez un ID de widget. Vous transmettez cet ID de widget en tant que paramètre lors de l’appel des méthodes d’assistance qui affichent le widget.

Cette rubrique a été écrite pour la version 1.1 de l’API Twitter. En ajoutant directement le code d’assistance Twitter à votre projet, vous pouvez mettre à jour le code d’assistance si l’API Twitter change.

Pour plus d’informations sur l’installation de WebMatrix, consultez Présentation de pages Web ASP.NET 2 - Prise en main.

Ajouter Twitter Helper à votre projet

Pour ajouter Twitter Helper, commencez par ajouter un dossier nommé App_Code à votre projet. Ensuite, créez un fichier nommé Twitter.cshtml.

dossier App_Code

Remplacez le code par défaut dans Twitter.cshtml par le code suivant.

@* This Twitter helper is compatible with version 1.1 of the Twitter API. *@

@using System.Globalization

@* For more about the twitter follow button, please visit
   https://dev.twitter.com/docs/follow-button *@
@helper FollowButton(
            string userName,
            bool showCount = false,
            bool showUserName = true,
            bool largeButton = false,
            bool optOutOfTailoring = false,
            string language = "",
            bool alignLeft = true)
{
    var showCountAttribute = new HtmlString(showCount ? "" : "data-show-count=\"false\"");
    var showUserNameAttribute = new HtmlString(showUserName ? "" : "data-show-screen-name=\"false\"");
    var largeButtonAttribute = new HtmlString(largeButton ? "data-size=\"large\"" : "");
    var optOutOfTailoringAttribute = new HtmlString(optOutOfTailoring ? "data-dnt=\"true\"" : "");
    var languageAttribute = new HtmlString(!language.IsEmpty() && !language.Equals("en", StringComparison.OrdinalIgnoreCase) ? String.Format(CultureInfo.InvariantCulture, " data-lang=\"" + HttpUtility.HtmlAttributeEncode(language) + "\"") : "");
    var alignAttribute = new HtmlString(alignLeft ? "" : "data-align=\"right\"");
    <a href="https://twitter.com/@HttpUtility.UrlEncode(userName)" class="twitter-follow-button" @showCountAttribute @showUserNameAttribute @largeButtonAttribute @optOutOfTailoringAttribute @languageAttribute @alignAttribute>Follow @@@userName)</a>
    <script>!function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https'; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = p + '://platform.twitter.com/widgets.js'; fjs.parentNode.insertBefore(js, fjs); } }(document, 'script', 'twitter-wjs');</script>
}

@* For more about the tweet button, please visit https://dev.twitter.com/docs/tweet-button *@
@helper TweetButton(string url = "",
            string tweetText = "",
            bool showCount = true,
            string via = "",
            string recommend = "",
            string hashtag = "",
            bool largeButton = false,
            bool optOutOfTailoring = false,
            string language = "")
{
    var urlAttribute = new HtmlString(url.IsEmpty() ? "" : String.Format(CultureInfo.InvariantCulture, " data-url=\"" + HttpUtility.HtmlAttributeEncode(url) + "\""));
    var tweetTextAttribute = new HtmlString(tweetText.IsEmpty() ? "" : "data-text=\"" + HttpUtility.HtmlAttributeEncode(tweetText) + "\"");
    var showCountAttribute = new HtmlString(showCount ? "" : "data-show-count=\"false\"");
    var viaAttribute = new HtmlString(via.IsEmpty() ? "" : "data-via=\"" + HttpUtility.HtmlAttributeEncode(via) + "\"");
    var recommendAttribute = new HtmlString(recommend.IsEmpty() ? "" : "data-related=\"" + HttpUtility.HtmlAttributeEncode(recommend) + "\"");
    var hashtagAttribute = new HtmlString(hashtag.IsEmpty() ? "" : "data-hashtags=\"" + HttpUtility.HtmlAttributeEncode(hashtag) + "\"");
    var largeButtonAttribute = new HtmlString(largeButton ? "data-size=\"large\"" : "");
    var optOutOfTailoringAttribute = new HtmlString(optOutOfTailoring ? "data-dnt=\"true\"" : "");
    var languageAttribute = new HtmlString(!language.IsEmpty() && !language.Equals("en", StringComparison.OrdinalIgnoreCase) ? String.Format(CultureInfo.InvariantCulture, " data-lang=\"{0}\"", HttpUtility.HtmlAttributeEncode(language)) : "");
    <a href="https://twitter.com/share" class="twitter-share-button" @urlAttribute @tweetTextAttribute @showCountAttribute @viaAttribute @recommendAttribute @hashtagAttribute @largeButtonAttribute @optOutOfTailoringAttribute @languageAttribute>Tweet</a>
    <script>!function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https'; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = p + '://platform.twitter.com/widgets.js'; fjs.parentNode.insertBefore(js, fjs); } }(document, 'script', 'twitter-wjs');</script>
}

@helper TimeLine(string userName,
            string widgetId,
            string theme = "",
            string linkColor = "",
            string language = "",
            int? tweetLimit = null,
            string relatedUsers = "",
            string ariaPolite = "",
            int? width = null,
            int? height = null,
            string title = "Tweets")
{
    var themeAttribute = new HtmlString(theme.IsEmpty() ? "" : "data-theme=\"" + theme + "\"");
    var linkColorAttribute = new HtmlString(linkColor.IsEmpty() ? "" : "data-link-color=\"" + linkColor + "\"");
    var languageAttribute = new HtmlString(!language.IsEmpty() && !language.Equals("en", StringComparison.OrdinalIgnoreCase) ? String.Format(CultureInfo.InvariantCulture, " data-lang=\"{0}\"", HttpUtility.HtmlAttributeEncode(language)) : "");
    var relatedUsersAttribute = new HtmlString(relatedUsers.IsEmpty() ? "" : "data-related=\"" + relatedUsers + "\"");
    var ariaPoliteAttribute = new HtmlString(ariaPolite.IsEmpty() ? "" : "data-aria-polite=\"" + ariaPolite + "\"");
    <a class="twitter-timeline" href="https://twitter.com/@userName" width="@width.ToString()" height="@height.ToString()" data-widget-id="@HttpUtility.HtmlEncode(widgetId)" @themeAttribute @linkColorAttribute @languageAttribute data-tweet-limit="@tweetLimit.ToString()" @relatedUsersAttribute @ariaPoliteAttribute>@title</a>
    <script>!function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https'; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = p + "://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); } }(document, "script", "twitter-wjs");</script>
}

@helper Profile(string userName,
            string widgetId,
            string theme = "",
            string linkColor = "",
            string language = "",
            int? tweetLimit = null,
            string relatedUsers = "",
            string ariaPolite = "",
            int? width = null,
            int? height = null)
{
    @Twitter.TimeLine(userName, widgetId, theme, linkColor, language, tweetLimit, relatedUsers, ariaPolite, width, height, "Tweets by @" + HttpUtility.HtmlEncode(userName));
}

@helper Faves(string userName,
            string widgetId,
            string theme = "",
            string linkColor = "",
            string language = "",
            int? tweetLimit = null,
            string relatedUsers = "",
            string ariaPolite = "",
            int? width = null,
            int? height = null)
{
    @Twitter.TimeLine(userName + "/favorites", widgetId, theme, linkColor, language, tweetLimit, relatedUsers, ariaPolite, width, height, "Favorite Tweets by @" + HttpUtility.HtmlEncode(userName));
}

@helper List(string userName,
            string list,
            string widgetId,
            string theme = "",
            string linkColor = "",
            string language = "",
            int? tweetLimit = null,
            string relatedUsers = "",
            string ariaPolite = "",
            int? width = null,
            int? height = null)
{
    @Twitter.TimeLine(userName + "/" + list, widgetId, theme, linkColor, language, tweetLimit, relatedUsers, ariaPolite, width, height, "Tweets from @" + HttpUtility.HtmlEncode(userName) + "/" + HttpUtility.HtmlEncode(list));
}

@helper Search(string query,
            string widgetId,
            string theme = "",
            string linkColor = "",
            string language = "",
            int? tweetLimit = null,
            string relatedUsers = "",
            string ariaPolite = "",
            int? width = null,
            int? height = null)
{
    @Twitter.TimeLine("search?q=" + HttpUtility.UrlEncode(query), widgetId, theme, linkColor, language, tweetLimit, relatedUsers, ariaPolite, width, height, "Tweets about \"" + HttpUtility.HtmlEncode(query) + "\"");
}

Appeler des méthodes Twitter à partir de vos pages web

L’exemple suivant montre comment utiliser les méthodes Twitter Helper à partir d’une page de votre projet. Dans votre projet, vous souhaiterez remplacer les valeurs de paramètre par des valeurs qui correspondent à vos besoins. Vous pouvez utiliser les ID de widget fournis pour explorer le fonctionnement des méthodes, mais vous souhaiterez générer vos propres widgets pour votre projet.

Tous les paramètres indiqués ci-dessous ne sont pas requis. Les paramètres facultatifs sont utilisés pour personnaliser l’affichage du bouton ou du widget. Par exemple, le bouton Suivre nécessite uniquement le nom d’utilisateur à suivre, mais l’exemple montre comment inclure le nombre d’abonnés et comment spécifier la taille du bouton et la langue.

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Show the Twitter Helper</title>
    </head>
    <body>
        <h1>Twitter Buttons and Widgets</h1>

        <h2>1. Follow Button</h2>
        <p>@Twitter.FollowButton(userName: "aspnet", showCount: true, largeButton: false, language: "es")</p>

        <h2>2. Tweet Button</h2>
        <p>@Twitter.TweetButton(url: "http://www.asp.net/mvc", largeButton: true, hashtag: "awesome")</p>
        
        <h2>3. User Timeline (Profile)</h2>
        <p>@Twitter.Profile("aspnet", "370310677673422848")</p>

        <h2>4. Favorites</h2>
        <p>@Twitter.Faves("Microsoft", "372486349795753984")</p>

        <h2>5. List</h2>
        <p>@Twitter.List("MS_Consumer_Bands", "Microsoft", "372485258974748672")</p>

        <h2>6. Search</h2>
        <p>@Twitter.Search("#asp.net", "370310477957435392")</p>
    </body>
</html>

Afficher les résultats

Le code ci-dessus génère les boutons et widgets suivants. Ces boutons et widgets sont entièrement fonctionnels, et non des captures d’écran. Le bouton Suivre s’affiche en espagnol, car le paramètre de langue a été défini sur es.

Bouton Suivre

Follow @aspnet)<script>!function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https'; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = p + '://platform.twitter.com/widgets.js'; fjs.parentNode.insertBefore(js, fjs); } }(document, 'script', 'twitter-wjs');</script>

Bouton Tweet

Tweet<script>!function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https'; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = p + '://platform.twitter.com/widgets.js'; fjs.parentNode.insertBefore(js, fjs); } }(document, 'script', 'twitter-wjs');</script>

Chronologie utilisateur (profil)

Tweets by @aspnet<script>!function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https'; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = p + "://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); } }(document, "script", "twitter-wjs");</script>

Favoris

Favorite Tweets by Microsoft<script>!function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https'; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = p + "://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); } }(document, "script", "twitter-wjs");</script>

List

Tweets from @Microsoft/MS\_Consumer\_Bands<script>!function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https'; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = p + "://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); } }(document, "script", "twitter-wjs");</script>

Tweets sur « #asp.net »<script>!function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0], p = /^http:/.test(d.location) ? 'http' : 'https'; if (!d.getElementById(id)) { js = d.createElement(s); js.id = id; js.src = p + "://platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs); } }(document, "script", "twitter-wjs");</script>