Cannot get the Silverlight Demo to work

Sep 13, 2011 at 10:41 AM

Hi

I am trying to run and debug the Silverlight demo since I need to do something similiar for WPF.

I have inserted the ConsumerKey/Secret in the FriendsStatusQuery page, and when I get to this code to validate my credentials 

 

        public void ProcessRequest(HttpContext context)
        {
            string url = PrepareUrl(context);

            if (context.Request.HttpMethod == "GET")
            {
                var req = WebRequest.Create(url) as HttpWebRequest;
                req = SetCookies(req, context.Request);
                req = SetHeaders(req, context.Request.Headers);

                using (WebResponse resp = req.GetResponse())
                {
                    using (var respStream = resp.GetResponseStream())
                    using (var respReader = new StreamReader(respStream))
                    {
                        string respString = respReader.ReadToEnd();
                        context.Response.Write(respString);
                    }
                }
            }
its failing on the WebResponse resp = req.GetResponse() with a 401 error Unauthorized.  I have double checked that the ConsumerKey/Secret are correct.

Do I need to do something else to get this to work?

Thanks

Johann

Coordinator
Sep 13, 2011 at 2:28 PM

Hi Johann,

A few things to check:

  1. Step through Silverlight code to make sure you set credentials in the right place.
  2. Drill down into exception results to see if the Twitter response provides more information.
  3. Hook up Fiddler2, Firebug, or F12 Tools to see the response from Twitter.
  4. Try the same credentials in a Console demo to ensure they work.
  5. Try the query at different times, just in case Twitter is having temporary problems.
  6. I haven't tested Silverlight in the latest source code check-in, so you might want to make sure you're using the latest full release or NuGet release.
  7. Sometimes there's caching issues with Silverlight and I work around them by (1) shutting down all VS Web Servers (via task bar), (2) deleting all files from the class library bin, (3) rebuilding the class library, and (4) rebuilding the Web app.  i.e. What if your app was built before adding credentials and VS uses the cached version even after you add credentials to the source code?

401's are tough to debug, but hopefully these tips will help.

Joe

Sep 13, 2011 at 2:42 PM

Hi Joe

I decided to take another route, and extract the OAuth code in a new WPF window, so that I can debug and see what's happening, and will actually use this window for my project.

However when I try this code :-

 

 

            m_pinAuth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = "myConsKey",
                    ConsumerSecret = "myConsSecret"
                },
                UseCompression = true,
                GoToTwitterAuthorization = pageLink =>
                    Dispatcher.BeginInvoke(new Action(() => WebBrowser.Navigate(new Uri(pageLink))))
            };

 

I am getting the following error 

{"Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.":"System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"}

Since its a WPF application, I do not have this reference added in the project.  

Is there a different code from Silverlight to WPF?

Coordinator
Sep 13, 2011 at 2:56 PM

Silverlight is LinqToTwitterAg.dll.  Everything else is LinqToTwitter.dll.

Joe

Sep 14, 2011 at 8:45 AM

Hi Joe

I am still getting the same problem with WPF.  When using LinqToTwitter.dll, the project does not compile, while using LinqToTwitterAg.dll does compile, but throws the 

{"Could not load file or assembly 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' or one of its dependencies. The system cannot find the file specified.":"System.Windows, Version=2.0.5.0, Culture=eutral, PublicKeyToken=7cec85d7bea7798e"}

This is my XAML

<Window x:Class="WpfTwitterAuth.MainWindow"       

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"       

Title="MainWindow" Height="640" Width="480">   

<Grid>       

<Grid.RowDefinitions>           

<RowDefinition Height="*" />           

<RowDefinition Height="Auto" />           

<RowDefinition Height="Auto" />       

</Grid.RowDefinitions>       

<WebBrowser Grid.Row="0" Name="WebBrowser" />       

<StackPanel Grid.Row="1" Name="PinPanel" Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Top">           

<Label Name="label2" VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,10,0,0" Width="37" Content="Pin:" />           

<TextBox Name="PinTextBox" VerticalAlignment="Top" Margin="5" Width="120" />           

<Button Content="Submit" Height="23" Name="PinButton" Margin="5" VerticalAlignment="Top" Width="75" Click="PinButton_Click" />       

</StackPanel>       

<StackPanel Grid.Row="2" HorizontalAlignment="Center" Name="FriendsPanel" Visibility="Collapsed">           

<Button Content="Show friends" Height="23" Name="FriendsButton" Width="85" Margin="5" Click="FriendsButton_Click" />           

<DataGrid AutoGenerateColumns="True" Name="FriendsDataGrid" Margin="5" />       

</StackPanel>

    </Grid></Window>

And my .cs

        private TwitterContext m_twitterCtx = null;
        private PinAuthorizer m_pinAuth = null;

        public MainWindow()
        {
            InitializeComponent();
            DoPinAuth();
        }

        private void DoPinAuth()
        {
            m_pinAuth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = "mykey",
                    ConsumerSecret = "mysecret"
                },
                UseCompression = true,
                GoToTwitterAuthorization = pageLink =>
                    Dispatcher.BeginInvoke(new Action(() => WebBrowser.Navigate(new Uri(pageLink))))
            };

            m_pinAuth.BeginAuthorize(resp =>
                Dispatcher.BeginInvoke(new Action(() =>
                                                 {
                                                     switch (resp.Status)
                                                     {
                                                         case TwitterErrorStatus.Success:
                                                             break;
                                                         case TwitterErrorStatus.TwitterApiError:
                                                         case TwitterErrorStatus.RequestProcessingException:
                                                             MessageBox.Show(
                                                                 resp.Error.ToString(),
                                                                 resp.Message,
                                                                 MessageBoxButton.OK);
                                                             break;
                                                     }
                                                 })));

            m_twitterCtx = new TwitterContext(m_pinAuth, "https://api.twitter.com/1/", "https://search.twitter.com/");
        }


        private void PinButton_Click(object sender, RoutedEventArgs e)
        {

        }

        private void FriendsButton_Click(object sender, RoutedEventArgs e)
        {

        }

I cannot find out what the problem is

Can you point me to some WPF OAuth samples or tutorials in the LinqToTwitter community?

THanks

Sep 14, 2011 at 9:46 AM

Hi Joe

I found my problem!  Had to include the 4.0Binaries

Now it works thanks

Sep 14, 2011 at 2:11 PM

Hi Joe

So now everything is compiling and running well, however when I run this in the WPF :-

        private void DoPinAuth()
        {
            var auth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = "key",
                    ConsumerSecret = "secret"
                },
                UseCompression = true,
                GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
                GetPin = () =>
                {
                    // this executes after user authorizes, which begins with the call to auth.Authorize() below.
                    Console.WriteLine("\nAfter you authorize this application, Twitter will give you a 7-digit PIN Number.\n");
                    Console.Write("Enter the PIN number here: ");
                    return Console.ReadLine();
                }
            };

            auth.Authorize();

            using (var twitterCtx = new TwitterContext(auth, "https://api.twitter.com/1/", "https://search.twitter.com/"))
            {
                //Log
                twitterCtx.Log = Console.Out;

                // LINQ to Twitter query goes here
            }
        }

This returns auth.IsAuthorized and so I can get the tokens. 
However this :- 

        private void DoPinAuth1()
        {
            m_pinAuth = new PinAuthorizer
            {
                Credentials = new InMemoryCredentials
                {
                    ConsumerKey = "key",
                    ConsumerSecret = "secret"
                },
                UseCompression = true,
                GoToTwitterAuthorization = pageLink =>
                    Dispatcher.BeginInvoke(new Action(() => WebBrowser.Navigate(new Uri(pageLink))))
            };

            m_pinAuth.BeginAuthorize(resp =>
                Dispatcher.BeginInvoke(new Action(() =>
                                                 {
                                                     switch (resp.Status)
                                                     {
                                                         case TwitterErrorStatus.Success:
                                                             break;
                                                         case TwitterErrorStatus.TwitterApiError:
                                                         case TwitterErrorStatus.RequestProcessingException:
                                                             MessageBox.Show(
                                                                 resp.Error.ToString(),
                                                                 resp.Message,
                                                                 MessageBoxButton.OK);
                                                             break;
                                                     }
                                                 })));

            m_twitterCtx = new TwitterContext(m_pinAuth, "https://api.twitter.com/1/", "https://search.twitter.com/");
        }


        private void PinButton_Click(object sender, RoutedEventArgs e)
        {
            string pin = PinTextBox.Text;

            m_pinAuth.CompleteAuthorize(
                PinTextBox.Text,
                completeResp => Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    switch (completeResp.Status)
                                    {
                                        case TwitterErrorStatus.Success:
                                            FriendsPanel.Visibility = Visibility.Visible;
                                            break;
                                        case TwitterErrorStatus.TwitterApiError:
                                        case TwitterErrorStatus.RequestProcessingException:
                                            MessageBox.Show(
                                                completeResp.Error.ToString(),
                                                completeResp.Message,
                                                MessageBoxButton.OK);
                                            break;
                                    }
                                })));


        }
never returns the .IsAuthorized and thus it never returns any tokens.
Is there anything wrong with the second example?
I much prefer the second option if it works
Thanks