Auto Tweet C# Corner Articles Using Azure

In this article, we will see how we can spread knowledge and help the community to Tweet newly published articles on the C# Corner web site leveraging Azure capabilities. C# Corner is one of the greatest sources of knowledge and its user base proves it. Every day lots of articles, blogs, and the latest technology news are published by C# corner community members and to keep everyone updated, the C# corner team has already implemented an RSS Feed of articles. If you want to know details of the RSS feed and how it works – you can refer to this link.

We will be using RSS feeds of existing C# corner articles and using it to detect if any new article is published, if so then we will go ahead and tweet it.

For demo purposes, I have kept the workflow quite simple and it follows the steps below, 

  • A program keeps polling C# Corner articles' RSS Feed.
  • Maintains existing items in the feed inside a static C# list (in memory)
  • If it finds anything which is not contained in a list, it posts a tweet and saves it in list for next reference. 

Note that there could be numerous approaches to implement the polling however I have just kept it simple for our demo. You can choose to take a different approach such as keeping a list of already published articles in your database, Azure table storage etc.

This would have been a typical and ideal task for creating a windows service, however in the cloud world you can easily achieve it using Azure capabilities. You can either use web jobs or cloud service worker roles to do it. We will be taking approach of worker role for this article, since we have already seen web jobs in details.

Now since the application will be communicating to Twitter we will need to register our application in Twitter apps and get credentials for it.

Twitter Side

We will simply navigate and register our application by adding a new entry in it.

If you click on create new application, it asks you for some basic information, some of which you can edit later. Fill in all the details and click on create your Twitter application. I have named my application TwitterWorker and added it.

After the application is added, navigate to keys and access tokens tab and grab consumer key, consumer secret. These are needed for twitter API authentication. If you scroll down on the same page, you will see a button called Generate access token and secret. Click on it and note down your access token and token secret.

The entire process is already well documented here, you can refer to  it for your reference.

Azure and C# side

Now this is a fairly simple and known side, simply start Visual Studio and install Azure SDK, if you have it already installed then you will see cloud project templates. Select it and create Cloud Services project type.

Let’s name our project as Feed.Autotweet and add a worker role to it named Feed.Twitter.

Before going ahead, let me declare some nuget packages and assemblies we need to include in our worker role class library project. 

  • TweetSharp
  • System.Configuration.dll
  • System.ServiceModel.dll 

Once you are done with initial setup, open up app.config file and add below entries in app settings.

  1. <appSettings>  
  2.  <add key="ConsumerKey" value="xxxx" />  
  3.  <add key="ConsumerSecret" value="xxxx" />  
  4.  <add key="AccessToken" value="xxx-xxxx" />  
  5.  <add key="TokenSecret" value="xxxx" />  
  6. </appSettings>  

Initialize keys with correct values which we copies from twitter portal while registering the application. And source code is as below, it’s quite self-explanatory and I have added comments wherever necessary.

  1. public class WorkerRole : RoleEntryPoint  
  2. {  
  3.    private static List<string> existingArticles = new List<string>();  
  4.    private static string consumerKey = string.Empty;  
  5.    private static string consumerSecret = string.Empty;  
  6.    private static string accessToken = string.Empty;  
  7.    private static string tokenSecret = string.Empty;  
  8.   
  9.    private static string tweetText = "{0}-{1}";  
  10.       public override void Run()  
  11.    {  
  12.      Trace.TraceInformation("Feed.Twitter is running");  
  13.   
  14.      while (true)  
  15.      {  
  16.        // Parse C# Corner RSS Feed  
  17.        XmlReader reader = new MyXmlReader("http://www.c-sharpcorner.com/rss/latestcontentall.aspx");  
  18.        SyndicationFeed feed = SyndicationFeed.Load(reader);  
  19.        Rss20FeedFormatter rssFormatter = feed.GetRss20Formatter();  
  20.        XmlTextWriter rssWriter = new XmlTextWriter("rss.xml", Encoding.UTF8);  
  21.        rssWriter.Formatting = Formatting.Indented;  
  22.        rssFormatter.WriteTo(rssWriter);  
  23.        rssWriter.Close();  
  24.   
  25.        foreach (var feedItem in feed.Items)  
  26.        {  
  27.         // Check if tweet has been added for article, if it is new then tweet it.  
  28.   
  29.         if (!existingArticles.Contains(feedItem.Title.Text.ToLower().Trim()))  
  30.         {  
  31.           // Get keys from app.config  
  32.           consumerKey = ConfigurationManager.AppSettings["ConsumerKey"];  
  33.           consumerSecret = ConfigurationManager.AppSettings["ConsumerSecret"];  
  34.           accessToken = ConfigurationManager.AppSettings["AccessToken"];  
  35.           tokenSecret = ConfigurationManager.AppSettings["TokenSecret"];  
  36.   
  37.           // Twitter app authentication  
  38.           var service = new TwitterService(consumerKey, consumerSecret);  
  39.           service.AuthenticateWith(accessToken, tokenSecret);  
  40.   
  41.           SendTweetOptions sendTweet = new SendTweetOptions();  
  42.           string tweetUrl = feedItem.Links[0].Uri.ToString();  
  43.           string tweet = string.Format(tweetText, feedItem.Title.Text, tweetUrl);  
  44.           string tweetTitle = feedItem.Title.Text;  
  45.   
  46.           // Check if tweet lenght > 140 characters, shorten it if true.  
  47.           if (tweet.Length > 140)  
  48.           {  
  49.               tweetTitle = feedItem.Title.Text.Substring(0, 50) + "..";  
  50.           }  
  51.   
  52.               // Form tweet  
  53.               tweet = string.Format(tweetText, tweetTitle, tweetUrl);  
  54.               sendTweet.Status = tweet;  
  55.   
  56.               // Tweet  
  57.               service.SendTweet(sendTweet);  
  58.   
  59.               // Add article to existing items list.  
  60.               existingArticles.Add(feedItem.Title.Text.ToLower().Trim());  
  61.             }  
  62.            }  
  63.   
  64.             // Make thread sleep for 1 Hours.  
  65.             TimeSpan ts = new TimeSpan(1, 0, 0);  
  66.             Thread.Sleep(ts);         
  67.         }  
  68.   
  69.       }  

Class MyXmlReader.cs has been referred from this link. For demo purposes, we are polling C# Corner RSS Feed every 1 hour, you can keep this setting configurable and implement it for any other feed. This article is not focusing on creating and deploying Azure cloud services but it’s quite straightforward. You can take a look at detailed documentation here.

As of writing this, this is deployed on Azure and you can see all tweets on my twitter account.

 
 
Such tools might come in handy for Marketing managers, content publishers who need to keep their twitter handles up-to date with all the latest published content on their web sites e.g. news or organization achievements etc.
 
There is a huge scope to betterment of the source above and you can extend it to post article links with article owner's Twitter handle, posting tweets with media in the article etc and who knows --  it might be useful for our C# Corner Twitter handle manager to seamlessly post about new articles on this site.
 
Thanks for reading this, feel free to post your views or comments.