Linqtotwitter Automatic User Login

Feb 9, 2015 at 2:30 PM
Hi,

I have a wpf windows application(desktop). And I would like to automatic authorize any user, since they will provide user and password. I understand that there are a lot of examples showing the pin based authorization. But that is not what I am looking for. I want simple as that:
var authorizer = new Authorizer(email, password);
var linq = new LinqToTwitter.Context(authorizer);
If that is not possible, something like this:
   Authorizer = new PinAuthorizer {
                                CredentialStore = new InMemoryCredentialStore {
                                        ConsumerKey = ConsumerKey,
                                        ConsumerSecret = ConsumerSecret,
                                        ScreenName = Name
                                }
                        };

MyWebControl.Navigate(new Uri(authorizer.AuthLink));
Then I can get the html and search for the pin code. But your class is returning a delegate, and I dont know how to work with it.

Thanks.
Feb 10, 2015 at 10:16 PM
Edited Feb 10, 2015 at 10:18 PM
I found the answer:

If you need to directly connect with user name and password, you will need XAuthentication, which must be directly asked for twitter company.

They code below will grab the pin automatically after the user typed his password and clicked to authorize the application. It also contains it owns webcontrol.

Wpf Window:

XAML CODE:

<controls:MetroWindow x:Class="Social.Desktop.TwitterAuthorizer"
                      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                      xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"
                      TitleCaps="False"
                      BorderBrush="{DynamicResource BlackColorBrush}"
                      BorderThickness="1"
                      Title="Requisitando Autorização para o Twitter" Height="600" Width="600" Loaded="Window_Loaded"
                      Style="{DynamicResource CleanWindowStyleKey}" WindowStartupLocation="CenterOwner">
    <Grid Margin="10,15,10,10">
        <WebBrowser Name="MainBrowser" LoadCompleted="MainBrowser_OnLoadCompleted"/>
    </Grid>
</controls:MetroWindow>

C# CODE BEHIDE

using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Navigation;
using System.Windows.Threading;
using LinqToTwitter;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;

public partial class TwitterAuthorizer : MetroWindow
        {
                public string Email { get; set; }

                private const string Div = "<div id=\"oauth_pin\">";
                private const string ConsumerKey = @"Your Consumer Key";
                private const string ConsumerSecret = @"Your Consumer Key Secret";

                private static PinAuthorizer Authorizer { get; set; }

                public TwitterAuthorizer(string email)
                {
                        Email = email;
                        InitializeComponent();
                }

                private async Task Authorize()
                {
                        try {
                                Authorizer = new PinAuthorizer {
                                        CredentialStore = new InMemoryCredentialStore {
                                                ConsumerKey = ConsumerKey,
                                                ConsumerSecret = ConsumerSecret,
                                                ScreenName = Name
                                        },
                                        PreFillScreenName = Name,
                                        GoToTwitterAuthorization = page => Navigate(page)
                                };
                                await Authorizer.BeginAuthorizeAsync();
                        }
                        catch (Exception ex) {
                                throw new Exception(ex.ToString(), ex);
                        }
                }

                private void Navigate(string page)
                {
                        Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => {
                                page += "&force_login=true" + "&screen_name=" + Email;
                                MainBrowser.Navigate(new Uri(page));
                        }));
                }

                private async void Window_Loaded(object sender, RoutedEventArgs e)
                {
                        await Authorize();
                }

                private string GetPin()
                {
                        dynamic doc = MainBrowser.Document;
                        if (doc == null) return string.Empty;

                        var content = (mshtml.IHTMLDocument3) doc;
                        string htmlText = content.documentElement.innerHTML;

                        var index = htmlText.LastIndexOf(Div, StringComparison.Ordinal) + Div.Length;
                        var snip = htmlText.Substring(index);
                        return Regex.Replace(snip, "(?s)[^0-9]*([0-9]+).*", "$1").Trim();
                }

                private async void MainBrowser_OnLoadCompleted(object sender, NavigationEventArgs e)
                {
                        var pin = GetPin();
                        if (pin.Length > 6) {
                                MainBrowser.Visibility = Visibility.Hidden;
                                await Authorizer.CompleteAuthorizeAsync(pin);
                                CheckCredentials();
                        }
                }

                private void CheckCredentials()
                {
                        if (string.IsNullOrEmpty(Authorizer.CredentialStore.OAuthToken) ||
                            string.IsNullOrEmpty(Authorizer.CredentialStore.OAuthTokenSecret)) {
                                ShowErrorMessage();
                                return;
                        }
                        AddAuthorizedUser();
                }

                private void AddAuthorizedUser()
                {
                        bool error = false;
                        try {
                                using (var data = new LocalDatabase()) {
                                        data.AddNewUser(new LocalUser {
                                                ScreenName = Authorizer.CredentialStore.ScreenName,
                                                Email = Email,
                                                AccessToken = Authorizer.CredentialStore.OAuthToken,
                                                AccessTokenSecret = Authorizer.CredentialStore.OAuthTokenSecret,
                                                AccountType = LocalUserAccountType.Twitter,
                                                Id = Authorizer.CredentialStore.UserID.ToString()
                                        });
                                }
                        }
                        catch (Exception) {
                                error = true;
                        }
                        if (error) {
                                ShowErrorMessage();
                        }
                        else {
                                ShowConfirmationMessage();
                        }
                }

                private async void ShowConfirmationMessage()
                {
                        var mySettings = new MetroDialogSettings {
                                AffirmativeButtonText = "Continuar",
                                ColorScheme = MetroDialogColorScheme.Theme
                        };
                        await this.ShowMessageAsync("Olá!",
                                "Tudo pronto, sua autorização foi concedida com sucesso. Clique em continuar para prosseguir",
                                MessageDialogStyle.Affirmative, mySettings);
                        Close();
                }

                private async void ShowErrorMessage()
                {
                        var mySettings = new MetroDialogSettings {
                                AffirmativeButtonText = "Tudo bem, entendi.",
                                ColorScheme = MetroDialogColorScheme.Theme
                        };
                        await this.ShowMessageAsync("Olá!",
                                "Nos desculpe, mas não foi possível conseguir sua autorização. Tente novamente mais tarde!",
                                MessageDialogStyle.Affirmative, mySettings);
                        Close();
                }