Click here to Skip to main content
15,886,199 members
Articles / Desktop Programming / WPF

Catel - Part 5 of n: Building a WPF example application with Catel in 1 hour

Rate me:
Please Sign up or sign in to vote.
4.84/5 (21 votes)
28 Jan 2011CPOL27 min read 99.5K   3.5K   37  
This article explains how to write a real-world application using Catel.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using SocialMediaStream.UI.Windows;
using TweetSharp;

namespace SocialMediaStream.Providers.Twitter
{
    /// <summary>
    /// Social media provider for Twitter.
    /// </summary>
    public class TwitterProvider : SocialMediaProviderBase
    {
        #region Constants
        private const string ConsumerKey = "nsQMpd8qSUodHVox4NtEA";

        private const string ConsumerSecret = "iFVUiIQQMt89Dywi2VeIrWgJWBuB44Dv9qnPeQvw";

        private const string RequestTokenUrl = "https://twitter.com/oauth/request_token";

        private const string AccessTokenUrl = "https://twitter.com/oauth/access_token";

        private const string AuthorizeUrl = "https://twitter.com/oauth/authorize";
        #endregion

        #region Fields
        private readonly TwitterService _twitterService = new TwitterService(ConsumerKey, ConsumerSecret);
        private OAuthRequestToken _requestToken;
        private OAuthAccessToken _accessToken;
        #endregion

        #region Constructor & destructor
        /// <summary>
        /// Initializes a new instance of the <see cref="TwitterProvider"/> class.
        /// </summary>
        public TwitterProvider()
            : base("Twitter")
        {
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets a value indicating whether this instance has an access token.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance has an access token; otherwise, <c>false</c>.
        /// </value>
        private bool HasAccessToken { get { return _accessToken != null; } }
        #endregion

        #region Methods
        /// <summary>
        /// Gets the last 10 updates.
        /// </summary>
        /// <returns>
        /// 	<see cref="IEnumerable{ISocialMediaEntry}"/> containing all the updates.
        /// </returns>
        public override IEnumerable<ISocialMediaEntry> GetLast10Updates()
        {
            List<ISocialMediaEntry> updates = new List<ISocialMediaEntry>();

            if (Connect())
            {
                try
                {
                    //IEnumerable<TwitterStatus> tweets = _twitterService.ListTweetsOnHomeTimeline(10);
                    IEnumerable<TwitterStatus> tweets = _twitterService.ListTweetsOnFriendsTimeline(10);
                    foreach (var tweet in tweets)
                    {
                        var entry = ConvertTwitterStatusToSocialMediaEntry(tweet);
                        if (entry != null)
                        {
                            updates.Add(entry);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }
            }

            return updates;
        }

        /// <summary>
        /// Converts the twitter status object to social media entry.
        /// </summary>
        /// <param name="entryAsTwitterStatus">The entry as twitter status.</param>
        /// <returns>
        /// New <see cref="ISocialMediaEntry"/> or <c>null</c> if the item could not be constructed.
        /// </returns>
        private ISocialMediaEntry ConvertTwitterStatusToSocialMediaEntry(TwitterStatus entryAsTwitterStatus)
        {
            Bitmap photo = GetBitmapFromUrl(entryAsTwitterStatus.Author.ProfileImageUrl);
            string author = entryAsTwitterStatus.Author.ScreenName;
            string message = entryAsTwitterStatus.Text;
            DateTime timestamp = entryAsTwitterStatus.CreatedDate;
            string url = string.Format("http://www.twitter.com/{0}", entryAsTwitterStatus.User.ScreenName);

            return new SocialMediaEntry(photo, author, message, timestamp, url, Name);
        }

        /// <summary>
        /// Connects this instance to twitter.
        /// </summary>
        /// <returns><c>true</c> if successful; otherwise <c>false</c>.</returns>
        private bool Connect()
        {
            if (!HasAccessToken)
            {
                try
                {
                    _requestToken = _twitterService.GetRequestToken();
                    Uri logInUrl = _twitterService.GetAuthenticationUrl(_requestToken);
                    AuthenticationWindow authWindow = new AuthenticationWindow(logInUrl.ToString(), ValidateLogin);
                    return authWindow.ShowDialog() ?? false;
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Validates the login.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="source">The source.</param>
        /// <returns>
        /// 	<c>true</c> if successful; otherwise <c>false</c>.
        /// </returns>
        private bool ValidateLogin(string url, string source)
        {
            if (url.ToLower().StartsWith("https://api.twitter.com/oauth/"))
            {
                // Pin is stored like this:
                //<div id="oauth_pin">
                //  1234567
                //</div>
                const string PinIdentifier = "<div id=oauth_pin>";

                try
                {
                    source = source.ToLower();
                    if (source.Contains(PinIdentifier))
                    {
                        // Extract the pin
                        int pinStart = source.IndexOf(PinIdentifier) + PinIdentifier.Length;
                        int pinEnd = source.IndexOf("</div>", pinStart);
                        string pin = source.Substring(pinStart, pinEnd - pinStart).Trim();

                        _accessToken = _twitterService.GetAccessToken(_requestToken, pin);
                        _twitterService.AuthenticateWith(_accessToken.Token, _accessToken.TokenSecret);
                        return true;
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    return false;
                }
            }

            return false;
        }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions