Sunday 23 June 2013

C# Console app that displays twitter feed using Linq To Twitter (using Single User Authorization)


I recently had to add a twitter feed to my existing ASP.NET MVC 4 application. All I had to do was pull the last 10 tweets for a given user. It took me a while (shamefully, 3 hours) to get it working so I thought of writing a simple tutorial that explains how to pull a twitter feed for a console app using LINQ to Twitter.

LINQ to Twitter is an open source 3rd party LINQ Provider for the Twitter micro-blogging service. It uses standard LINQ syntax for queries and includes method calls for changes via the Twitter API

What took me long to figure out was the way twitter has implemented authentication using OAuth. Before you do anything, make sure you read the Learning to use OAuth document.

In my example, I used Single User Authorization. Single User Authorization is designed for scenarios where you'll only ever have one account accessing Twitter. i.e. if your Web site does periodic Twitter updates, regardless of user or you have a server that monitors general information. 

Before we begin coding, we'll need to set-up this authorization scheme on twitter & generate certain tokens as shown below:

Start by creating a twitter account that your application will be using to access Twitter. This is easy-peasy. Log on to https://twitter.com/ and setup your account. I've created a dummy account for this (_roehit).

Once your account is setup, navigate to https://dev.twitter.com and sign in with your twitter credentails. 

You now need to create an application. This can be done at https://dev.twitter.com/apps by clicking "Create a new application".



You need to enter your application details. You need a Name, Description & a Website (Your application's publicly accessible home page). You can add a Callback URL but its not really required. (Note: The name can't include the word "twitter".)



Remember to agree to the terms and conditions.

You should now get directed to the application page. By default, the first tab ("Details" tab) is visible. You must click the "Api Keys" tab and then click the "Create my access token" button (you will need to scroll down). This in turn generates the access tokens (you may need to refresh the page). Your Keys and Access Tokens should now be available for use.







Once created, navigate to the "OAutth tool" tab to view your OAuth Settings. We will need the generated tokens for our applications. (Note: My tokens are crossed out to maintain their integrity.)

Take note of the following tokens as we will need these later:
  • Consumer key
  • Consumer secret
  • Access token
  • Access token secret


Now we begin coding. In this example we've created a simple C# console application.

Start by creating a new project. Choose the "Console Application" template. 

Use NuGet to add the linqtotwitter package to our application. 



And now add the code shown below:
/// <summary>
/// Controls the flow of the program.
/// </summary>
/// <param name="args">The args.</param>
static void Main(string[] args)
{
    // This is a super simple example that
    // retrieves the latest tweets of a given 
    // twitter user.

    // SECTION A: Initialise local variables
    Console.WriteLine("SECTION A: Initialise local variables");

    // Access token goes here .. (Please generate your own)
    const string accessToken = "Access token goes here .. (Please generate your own)";
    // Access token secret goes here .. (Please generate your own)
    const string accessTokenSecret = "Access token secret goes here .. (Please generate your own)";

    // Api key goes here .. (Please generate your own)
    const string consumerKey = "Api key goes here .. (Please generate your own)";
    // Api secret goes here .. (Please generate your own)
    const string consumerSecret = "Api secret goes here .. (Please generate your own)";

    // The twitter account name goes here
    const string twitterAccountToDisplay = "roeburg"; 


    // SECTION B: Setup Single User Authorisation
    Console.WriteLine("SECTION B: Setup Single User Authorisation");
    var authorizer = new SingleUserAuthorizer
    {
        CredentialStore = new InMemoryCredentialStore
        {
            ConsumerKey = consumerKey,
            ConsumerSecret = consumerSecret,
            OAuthToken = accessToken,
            OAuthTokenSecret = accessTokenSecret
        }
    };

    // SECTION C: Generate the Twitter Context
    Console.WriteLine("SECTION C: Generate the Twitter Context");
    var twitterContext = new TwitterContext(authorizer);

    // SECTION D: Get Tweets for user
    Console.WriteLine("SECTION D: Get Tweets for user");
    var statusTweets = from tweet in twitterContext.Status
                        where tweet.Type == StatusType.User &&
                                tweet.ScreenName == twitterAccountToDisplay &&
                                tweet.IncludeContributorDetails == true &&
                                tweet.Count == 10 &&
                                tweet.IncludeEntities == true
                        select tweet;

    // SECTION E: Print Tweets
    Console.WriteLine("SECTION E: Print Tweets");
    PrintTweets(statusTweets);
    Console.ReadLine();
}

/// <summary>
/// Prints the tweets.
/// </summary>
/// <param name="statusTweets">The status tweets.</param>
/// <exception cref="System.NotImplementedException"></exception>
private static void PrintTweets(IQueryable<Status> statusTweets)
{
    foreach (var statusTweet in statusTweets)
    {
        Console.WriteLine(string.Format("\n\nTweet From [{0}] at [{1}]: \n-{2}",
            statusTweet.ScreenName,
            statusTweet.CreatedAt,
            statusTweet.Text));
                
        Thread.Sleep(1000);
    }
}

This should now display the last 10 tweets for the specified user.

A copy of the project is available at http://1drv.ms/NPUIVW (download the Linq2Twitter zip). This is a Visual Studio 2013 Console Application with a target framework of .NET 4.5.1 using LinqToTwitter package verison 3.0.2.

Disclaimer: The code shown above is quite crude & includes no error handling of any sort. This is just to give you a starting point. You can extend the functionality as you desire.





Wednesday 5 June 2013

ASP.NET MVC: Error after switching on compilation of views

Its always a good idea to compile your Razor views. The reason being that errors within a view file are not detected until run time.

To let you detect these errors at compile time, ASP.NET MVC projects now include an MvcBuildViews property, which is disabled by default. To enable this property, open the project file and set the MvcBuildViews property to true, as shown in the following example:



After enabling MvcBuildViews I started seeing unseemly errors like so:

error ASPCONFIG: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level.  This error can be caused by a virtual directory not being configured as an application in IIS.

I couldn't figure it out but a colleague soon pointed out the following resource: http://stackoverflow.com/questions/5161511/mvc3-strange-error-after-switching-on-compilation-of-views

Turns out that this problem occurs when there is web project output (templated web.config or temporary publish files) in the obj folder. The ASP.NET compiler used isn't smart enough to ignore stuff in the obj folder, so it throws errors instead.

The fix was a modification to the MVC Project File as shown below:



Under the <Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'"> node, add the following :

<ItemGroup>
  <ExtraWebConfigs Include="$(BaseIntermediateOutputPath)\**\web.config" />
  <ExtraPackageTmp Include="$([System.IO.Directory]::GetDirectories(&quot;$(BaseIntermediateOutputPath)&quot;, &quot;PackageTmp&quot;, System.IO.SearchOption.AllDirectories))" />
</ItemGroup>
<Delete Files="@(ExtraWebConfigs)" />
<RemoveDir Directories="@(ExtraPackageTmp)" />

Tuesday 4 June 2013

Deploying an ASP.NET MVC Application using Powershell


Personally, I'm not a big fan of batch files. Don't get me wrong, while batch files are super cool at getting things done, I personally prefer the flexibility that powershell provides.

The script shown below can be used as a template to automate the website deployment process.

I have however assumed that you have MVC installed on the machine. If you do not, then you will need to add the dlls necessary to bin deploy MVC. 
There are a set of assemblies you’ll need to include with your application for it to run properly, unless they are already installed in the Global Assembly Cache (GAC) on the server. Have a look at http://haacked.com/archive/2011/05/25/bin-deploying-asp-net-mvc-3.aspx
The script leverages the appcmd utility. You need to be mindful that:
  • When running the script, you may need to set your execution policy.
  • When running this script using other automated deployment environments you may only have access to the command line so you can invoke it like so:
cmd /c powershell -ExecutionPolicy "UnRestricted" .\ApplicationDeployment.ps1 \\Path\To\Binaries\Folder 

A copy of the sample file is available here ... http://sdrv.ms/11UZKW7