Geeks With Blogs
Joe Mayo

Yesterday, Microsoft launched Visual Studio 2013 (VS2013), their newest version of their Integrated Development Environment (IDE). Along with this launch was several announcements that included a partnership with Xamarin and lifting of Portable Class Library (PCL) and .NET NuGet library licensing restrictions. In addition to these announcements, Xamarin released Xamarin Studio 4.2 and associated Android and iOS toolsets, which have recently supported async and now have full support for PCL.

Given that LINQ to Twitter v3.0 supports both async and PCL, the stars seem to be aligned for support on Xamarin platforms. In this post I’ll show you how to add the LINQ to Twitter (PCL) DLL to a Xamarin.Android project. You’ll also see how to incorporate NuGet packages into a project, created with the Xamarin VS2013 plugin. Finally, you’ll see how to perform async queries with LINQ to Twitter.

Note: If you haven’t used the Xamarin tools before, visit the Xamarin site,download the free version, and do the Getting Started tutorial.

Creating a Xamarin.Android Project

When installing Xamarin, you get a plug-in for VS2013 that sets up project templates and other useful tools. I’ll be using VS2013, but you can also use Xamarin Studio, which is a nice tool too.

To get started, open VS2013 and select File | New | Project. You’ll see the New Project window below.

SNAGHTML16b4b19f

Under Installed Templates, Visual C#, Android, you see some new templates. Select Android Application, name the project L2TDemo, specify any file location you want, and click OK. That generates the following project:

SNAGHTML16b8f905

This project has two items to modify: Main.axml, for the UI, and Activity1.cs, which is like the main controller that starts off work.

Next, you need to add a reference to LINQ to Twitter. As of this writing, LINQ to Twitter v3.0 beta is available for download from http://bit.ly/1bLzr88 only available in source code form. Therefore, you should download the assemblies LINQ to Twitter Source Code, open the LinqToTwitterPcl.sln solution file (requires VS2013), build the code, and create a reference to the LinqToTwitterPcl.dll assembly. You now have a reference to a 3rd party PCL assembly.

In addition to LINQ to Twitter, you need references to the new HttpClient PCL libraries. Therefore, you can either use the assemblies downloaded with LINQ to Twitter or go to NuGet, by selecting Manage NuGet Packages from the References context menu, type HttpClient into the search box, and Install the Microsoft HTTP Client Libraries. You now have references to Microsoft licensed PCL assemblies.

SNAGHTML16e377cd

In the future, LINQ to Twitter v3.0 will be available on NuGet and have dependencies on the Microsoft HTTP client libraries, allowing a much smoother experience.

Defining the UI

If you open Main.axml, you’ll see a visual designer, but you can click the Source tab, at the bottom left of the designer, to see the associated XML. Change the XML to look like this:


    
    

This XML will display an EditText to accept a search term, a Button to initiate a Twitter search, and a ListView to display the tweets returned from the search. Each row of the ListView will hold a tweet and there needs to be a template to determine the layout of each tweet. Create the following template by adding a new item to the Resources/Layout folder (at the same place as Main.axml), named TweetListItem.axml:


    
        
        
    

This creates a template on each row that contains the user’s screen name and their tweet. There’s data that binds to this template, which is called  a Tweet, which you should create by adding a new class to the project named Tweet:

    public class Tweet
    {
        public ulong StatusID { get; set; }

        public string ScreenName { get; set; }

        public string Text { get; set; }
    }

To keep things simple, this demo just shows ScreenName and Text. The next section shows how to bind tweets to the UI.

Binding Tweets

In Xamarin.Android, you can use an Adapter to match tweets with UI templates. This demo creates a class named TweetAdapter that derives from a Xamarin class named BaseAdapter. Here’s the TweetAdapter class in it’s entirety:

    public class TweetAdapter : BaseAdapter
    {
        readonly List tweets;
        readonly Activity activity;

        public TweetAdapter(Activity activity, List tweets)
        {
            this.activity = activity;
            this.tweets = tweets;
        }

        public override int Count
        {
            get { return tweets.Count; }
        }

        public override Java.Lang.Object GetItem(int position)
        {
            return null;
        }

        public override long GetItemId(int position)
        {
            return (long)tweets[position].StatusID;
        }

        public override View GetView(int position, View convertView, ViewGroup parent)
        {
            Tweet tweet = tweets[position];

            var view = convertView ?? activity.LayoutInflater.Inflate(
                Resource.Layout.TweetListItem, parent, false);
            var screenName = view.FindViewById(Resource.Id.ScreenName);
            var userTweet = view.FindViewById(Resource.Id.Tweet);

            screenName.Text = tweet.ScreenName;
            userTweet.Text = tweet.Text;

            return view;
        }
    }

The constructor accepts references to the calling Activity and a list of tweets to display. Besides the other overrides to implement BaseAdapter, the GetView is particularly interesting. The ListView referencing this Adapter (explained later) calls GetView for each record to bind. The specific record the ListView is currently working on is sent as the position parameter.

The GetView implementation binds the current tweet to the View for the current row in the ListView. The code gets the data by indexing into the list of tweets (passed to the constructor) with the position parameter. The view is defined by TweetListItem and assigned to the view variable. With a reference to the TweetListItem View, the code obtains references to both ScreenName and Tweet in the view, assigning the references to screenName and userTweet variables, respectively. Since both screenName and userTweet reference TextView instances, the code needs to access their Text properties and assign the corresponding values from the current tweet. That’s how the data from the list of tweets gets put into each row of the ListView.

Now you know what the UI is and how data binds to the UI, but you haven’t seen how how the UI knows to use that adapter. The next section shows how to make those assignments.

Coding Activity

When the program starts, it calls the OnCreated method in an Activity. The OnCreate is where you write code to initialize the UI. In the OnCreate of Activity1, replace the code with the following:

    public class Activity1 : Activity
    {
        public TextView SearchTerm { get; set; }

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            SearchTerm = FindViewById(Resource.Id.SearchTermEditText);
            SearchTerm.Text = "\"LINQ to Twitter\"";

            Button searchButton = FindViewById

This code initializes the SearchTerm, but you can change the text before clicking the button when the program runs. ButtonClick, shown below, is the callback where most of the program’s activity occurs:

        async void ButtonClick(object sender, EventArgs e)
        {
            try
            {
                var tweets = await GetTweetsAsync();

                var tweetList = FindViewById(Resource.Id.TwitterListView);
                tweetList.Adapter = new TweetAdapter(this, tweets);
            }
            catch (Exception ex)
            {
                // your code
            }
        }

The ButtonClick callback obtains a reference to TwitterListView, which displays tweets, and assigns an instance of TweetAdapter to the Adapter property. This is how the ListView knows which adapter to use to call GetView and bind data to each row.

The TweetAdapter takes an argument for the calling Activity and a list of tweets returned from a Twitter search. It gets the list of tweets by calling GetTweetsAsync, which is covered next.

An Async Search Query

In this section, we perform the actual Twitter API search using LINQ to Twitter. The important parts of the code are authorization, performing the query, and re-shaping the data. Remember to add a using declaration for System.Linq and LinqToTwitter. Here’s the GetTweetsAsync method that performs this work:

        async Task> GetTweetsAsync()
        {
            var auth = new ApplicationOnlyAuthorizer()
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey = "",
                    ConsumerSecret = "",
                },
            };
            await auth.AuthorizeAsync();

            var ctx = new TwitterContext(auth);

            var searchResponse = await
                (from search in ctx.Search
                 where search.Query == SearchTerm.Text
                 select search)
                .SingleAsync();

            var tweets =
                (from tweet in searchResponse.Statuses
                 select new Tweet
                 {
                     StatusID = tweet.StatusID,
                     ScreenName = tweet.User.ScreenNameResponse,
                     Text = tweet.Text
                 })
                .ToList();

            return tweets;
        }

The Authorizer used in this example is ApplicationOnlyAuthorizer. Since searches aren’t tied to a specific user, this Authorizer is ideal and gives you a better rate limit. You get your tokens for the CredentialStore by creating a new Twitter app at http://dev.twitter.com. These tokens are your secrets for allowing users to authorize with Twitter, so don’t post them online. Once you’ve initialized the Authorizer, await AuthorizeAsync and LINQ to Twitter will take care of the entire OAuth sequence for you.

Note: Remember to add exception handling logic because authorization errors are a common source of confusion, especially when just starting out with Twitter API programming. For help with authorization errors, please refer to the LINQ to Twitter FAQ.

Next, instantiate a TwitterContext, passing in a reference to the ApplicationOnlyAuthorizer instance. You’re now ready to perform a query.

There are a couple special parts of the query syntax that make it async: await and SingleAsync. The query has a preceding await keyword, which is necessary syntax for async calls. Also notice the SingleAsync operator appended to the query. In addition to SingleAsync, LINQ to Twitter includes SingleOrDefaultAsync, FirstAsync, FirstOrDefaultAsync, and ToListAsync operators. Now you have an async LINQ query for the Twitter API, improving your application’s performance and scalability.

Once the code gets the response back from Twitter, it uses a LINQ to Objects query to re-shape it into Tweet instances. This is the list of tweets that the TweetAdapter, discussed earlier, binds to the ListView.

That’s all of the code. Now, let’s see it in action.

See Droid Tweet

When you run the code, deploy the emulator and then execute the code. (see the Xamarin Getting Started guide on their site if you encounter difficulties). When the program runs, click the search button and you should see a list of tweets that contain “LINQ to Twitter” in their text. Here’s the program running on an emulator:

SNAGHTML173d45cb

Summary

Now you know how to use LINQ to Twitter with Xamarin.Android. You went through several steps to set up the Android project, create the UI, bind data, and perform a search query with LINQ to Twitter. Of special note is that you can now work with 3rd party and Microsoft PCL assemblies with ease.

 

@JoeMayo

Posted on Thursday, November 14, 2013 9:28 AM LINQ to Twitter , xamarin , android | Back to top

Copyright © Joe Mayo | Powered by: GeeksWithBlogs.net