Tag Archives: Twitter

What can you do with a logic app? Part One – Send tweets at random intervals based on a defined data set

I thought I’d start another of my patented series’. This one is about finding interesting things that can be done with Azure Logic Apps.

Let’s say, for example, that you have something that you want to say; for example, if you were Richard Dawkins or Ricky Gervais, you might want to repeatedly tell everyone that there is no God; or if you were Google, you might want to tell everyone how .Net runs on your platform; or if you were Microsoft, you might want to tell people how it’s a “Different Microsoft” these days.

The thing that I want to repeatedly tell everyone is that I’ve written some blog posts. For this purpose, I’m going to set-up a logic app that, based on a random interval, sends a tweet from my account (https://twitter.com/paul_michaels), informing people of one of my posts. It will get this information from a simple Azure storage table; let’s start there: first, we’ll need a storage account:

Then a table:

We’ll enter some data using Storage Explorer:

After entering a few records (three in this case – because the train journey would need to be across Russia or something for me to fill my entire back catalogue in manually – I might come back and see about automatically scraping this data from WordPress one day).

In order to create our logic app, we need a singular piece of custom logic. As you might expect, there’s no randomised action or result, so we’ll have to create that as a function:

For Logic App integration, a Generic WebHook seems to work best:

Here’s the code:

#r "Newtonsoft.Json"
using System;
using System.Net;
using Newtonsoft.Json;
static Random _rnd;

public static async Task<object> Run(HttpRequestMessage req, TraceWriter log)
    log.Info($"Webhook was triggered!");
    if (_rnd == null) _rnd = new Random();
    string rangeStr = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "range", true) == 0)
    int range = int.Parse(rangeStr);
    int num = _rnd.Next(range - 1) + 1; 
    var response = req.CreateResponse(HttpStatusCode.OK, new
        number = num
    return response;

Okay – back to the logic app. Let’s create one:

The logic app that we want will be (currently) a recurrence; let’s start with every hour (if you’re following along then you might need to adjust this while testing – be careful, though, as it will send a tweet every second if you tell it to):

Add the function:

Add the input variables (remember that the parameters read by the function above are passed in via the query):

One thing to realise about Azure functions is they rely heavily on passing JSON around. For this purpose, you’ll use the JSON Parser action a lot. My advice would be to name them sensibly, and not “Parse JSON” and “Parse JSON 2” as I’ve done here:

The JSON Parser action requires a schema – that’s how it knows what your data looks like. You can get the schema by selecting the option to use a sample payload, and just grabbing the output from above (when you tested the function – if you didn’t test the function then you obviously trust me far more than you should and, as a reward, you can simply copy the output from below):

That will then generate a schema for you:

Note: if you get the schema wrong then the run report will error, but it will give you a dump of the JSON that it had – so another approach would be to enter anything and then take the actual JSON from the logs.

Now we’ll add a condition based on the output. Now that we’ve parsed the JSON, “number” (or output from the previous step) is available:

So, we’ll check if the number is 1 – meaning there’s a 1 in 10 chance that the condition will be true. We don’t care if it’s false, but if it’s true then we’ll send a tweet. Before we do that , though – we need to go the data table and find out what to send. Inside the “true” branch, we’ll add an “Azure Table Storage – Get Entities” call:

This asks you for a storage connection (the name is just for you to name the connection to the storage account). Typically, after getting this data, you would call for each to run through the entries. Because there is currently no way to count the entries in the table, we’ll iterate through each entry, but we’ll do it slowly, and we’ll use our random function to ensure that all are not sent.

Let’s start with not sending all items:

All the subsequent logic is inside the true branch. The next thing is to work out how long to delay:

Now we have a number between 1 and 60, we can wait for that length of time:

The next step is to send the tweet, but because we need specific data from the table, it’s back to our old friend: Parse JSON (it looks like every Workflow will contain around 50% of these parse tasks – although, obviously, you could bake this sort of thing into a function).

To get the data for the tweet, we’ll need to parse the JSON for the current item:

Once you’ve done this, you’ll have access to the parts of the record and can add the Tweet action:

And we have a successful run… and some tweets:

Windows 8 Shortcuts

Windows 8 is a great operating system, but sometimes, without knowing the shortcuts and apps available, it can be difficult to achieve even mundane tasks. Here’s some of the tools and tricks that I use.


I am the author of one of the apps mentioned below. I have no financial interest in Console OS.


Windows 8 mail app is definitely not as good as outlook. However, what people forget about when making this comparison is price:

Outlook is a commercial product and sells for just over £90 (that’s around $170 at the time of writing). Windows mail app is part of Windows 8. So it’s free.

If you want to beef it up a bit you can find some useful apps in the store. This one allows to to configure a mail template and associate that with a windows tile.


Many people these days run more than one monitor; especially with tablets. If you haven’t come across it yet, the magic key-combination here is Windows Key + Shift + Cursor Left or Windows Key + Shift + Cursor Right to move the current window to the next monitor.


Windows Key + S will allow you to search from anywhere; however, if you just press the Windows Key you’ll get taken to the start menu. From there you can just type and Windows should quickly find what you’re looking for.

When you’re done with an app, remember that moving away from the app, or even dragging it to close (finger at the top and the screen and swipe down) may not close the app. To do this, swipe down, but keep the app held at the bottom of the screen until the tile rotates: now it’s gone.

Copy and Paste

Admittedly, the store apps have a way to go with this. Complex text manipulation is difficult without a mouse, and whichever platform you choose, you’ll be swearing at the screen as you try to select the area between a comma and the preceding text. Windows big let down here is that some of the time, press and hold doesn’t give you a cut/copy/paste context menu. However, it does give you a keyboard (all textboxes do). So, simply select Ctrl and X, C or V from there. Not perfect, but it works.

Killer Apps

By far my favourite app these days is One Note. Unfortunately (or maybe fortunately, depending on your point of view) for Microsoft, they’ve made it available on other platforms for free.

The Facebook and Twitter apps are quite good; however, I now just use internet explorer. Remember that a Surface Pro or a Surface Pro 2
tablet, or even something like this Asus) is effectively running a full OS, so you’re no longer restricted to what you can find apps for.

So, what’s missing

While writing this, one of my big annoyances was that there isn’t a WordPress app. Admittedly there are less games available for Windows, but I suppose there’s only so many permutations of Angry Birds you can write. If you want more, why not consider contributing to these guys who are trying to bridge the gap?

Finally, if you would like to see a particular application on WinRT, leave a comment, or contact me directly.

Loading a Twitter Feed in WinRT

Recently, Twitter in their wisdom, discontinued the support for atom feed.  I have a couple of programs that were interrogating this, and they all suddenly (and gracefully I might add) stopped working.

The changeover is not that straightforward, especially if you don’t want to use third party libraries.

Introduction and Caveat

What I’m trying to achieve with this post is to collate all the information that I’ve gathered into a single place, so that switching from the old atom Twitter search:

string atomTweetSearchURL = string.Format("http://search.twitter.com/search.atom?q={0}", searchText);

…to the new OAuth2 can be achieved without looking anywhere else.

This is based on a Windows Store app.  There are some features that will be specific to a Store App, but I have no reason to believe this wouldn’t be generally applicable (and possible in a similar fashion) outside of the RT environment.  Having said that, there are other resources more applicable if you have access to the full .NET framework.

Finally, I have made use of lots of internet help. Where possible, I’ll link the appropriate articles, but if I forget to, just assume that the code you see here was either directly taken, or adapted from something I found online.

A last point, if you use libraries such as Linq to Twitter and JSON.NET, you’ll make your life easier; personally, I wanted to do this without a third party library.

Twitter Configuration

Previously, the URL above would allow you to simply interrogate the Twitter stream and Twitter didn’t need to know about who you were. That is now replaced. You don’t necessarily need to log-in as a user, you can use Application Only Identification. To set this up, visit https://apps.twitter.com/app/new


Only the first three boxes are required information. If you are developing a Windows 8 App then the Website can be a deep link to your application; for example, mine was here:


Once you click on the button to create a new app:


You will be provided with a Key and a Secret. These are long strings of numbers and letters that will identify your app.

JSON Helpers

We’ll be dealing in JSON. As such, you need to be able to serialise and de-serialise JSON data. The first thing to do is to create a helper class such as follows:

    class JSonSerialiserHelper

        public static T Deserialize<T>(string json)
            var _Bytes = Encoding.Unicode.GetBytes(json);
            using (MemoryStream _Stream = new MemoryStream(_Bytes))
                var _Serializer = new DataContractJsonSerializer(typeof(T));
                return (T)_Serializer.ReadObject(_Stream);

        public static string Serialize(object instance)
            using (MemoryStream _Stream = new MemoryStream())
                var _Serializer = new DataContractJsonSerializer(instance.GetType());
                _Serializer.WriteObject(_Stream, instance);
                _Stream.Position = 0;
                using (StreamReader _Reader = new StreamReader(_Stream)) 
                { return _Reader.ReadToEnd(); }

You’ll also need to deal with dates, so add this, too:

        internal static DateTime ConvertDate(string dateIn)
            // http://blog.kevinyu.org/2012/07/handling-json-in-net.html
            const string Const_TwitterDateTemplate = "ddd MMM dd HH:mm:ss +ffff yyyy";
            DateTime createdAt = DateTime.ParseExact(dateIn, Const_TwitterDateTemplate, new System.Globalization.CultureInfo("en-GB"));

            return createdAt;

Obviously if you’re not in Britain you may wish to change the culture.

Get a Token

There is now a two step authentication; it works like this:
1. Send your application details (key and secret) to Twitter and get an Authorisation Token
2. Use the token to search Twitter with your criteria

The Key and Secret are what you obtained above when you registered your app; the code below should get you a token with that information:

        // http://stackoverflow.com/questions/22733283/twitter-oauth2-using-winrt
        private async Task<TwitAuthenticateResponse> TwitterOAuth(string key, string secret)
            var client = new HttpClient();
            var uri = new Uri("https://api.twitter.com/oauth2/token");

            var encodedConsumerKey = WebUtility.UrlEncode(key);
            var encodedConsumerSecret = WebUtility.UrlEncode(secret);
            var combinedKeys = String.Format("{0}:{1}", encodedConsumerKey, encodedConsumerSecret);
            var utfBytes = System.Text.Encoding.UTF8.GetBytes(combinedKeys);
            var encodedString = Convert.ToBase64String(utfBytes);

            client.DefaultRequestHeaders.Add("Authorization", string.Format("Basic {0}", encodedString));

            var data = new List<KeyValuePair<string, string>> 
                new KeyValuePair<string, string>("grant_type", "client_credentials") 

            var postData = new FormUrlEncodedContent(data);

            var response = await client.PostAsync(uri, postData);
            TwitAuthenticateResponse authenticationResponse;
            using (response)
                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                    throw new Exception("Error.  Authentication Failed.");

                var content = await response.Content.ReadAsStringAsync();
                authenticationResponse = JSonSerialiserHelper.Deserialize<TwitAuthenticateResponse>(content);
                if (authenticationResponse.token_type != "bearer")
                    throw new Exception("Wrong result type.  Authentication failed.");

                return authenticationResponse;

TwitAuthenticateResponse looks like this:

    public class TwitAuthenticateResponse
        public string token_type { get; set; }
        public string access_token { get; set; }        

If you call that, you should have a valid token:

var auth = await TwitterOAuth("key", "secret");

Now the search

Now you have the authentication, you can use that to call the search; here’s the code:

        // http://stackoverflow.com/questions/23671600/using-a-token-to-search-on-twitter-with-oauth2
        private async Task<string> SearchTwitter(string accessToken, string srchStr)
            var client = new HttpClient();
            var searchUrl = string.Format("https://api.twitter.com/1.1/search/tweets.json?q={0}", srchStr);
            var uri = new Uri(searchUrl);

            client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", accessToken));

            HttpResponseMessage response = await client.GetAsync(uri);
            string content = await response.Content.ReadAsStringAsync();

            return content;

And here’s the call:

string srch = await SearchTwitter(auth.access_token, searchText);

What to do with the results?

Okay – you can use JSON.NET as mentioned before; however, here’s a way to do it without.

First, you need to declare some classes to hold the data:

    public class TwitSearchResult
        public StatusClass[] statuses { get; set; }


    public class TwitUser
        public string ScreenName { get; set; }

    public class StatusClass
        public string text { get; set; }
        public string source { get; set; }
        public TwitUser user { get; set; }
        public string created_at { get; set; }

Finally, use the helper classes above to deserialise what you get back:

            TwitSearchResult srchResult = JSonSerialiserHelper.Deserialize<TwitSearchResult>(srch);


The final top level call now looks like this:

            var auth = await TwitterOAuth("key", "secret");
            string srch = await SearchTwitter(auth.access_token, searchText);

            TwitSearchResult srchResult = JSonSerialiserHelper.Deserialize<TwitSearchResult>(srch);


Like I said before, if I’ve used your code and not credited you then it’s not intentional. My aim was just to get all this into a single place for future reference. If you’d like me to reference anything that isn’t referenced then contact me or leave a message.