Send mail to the author(s) E-mail

# Monday, 20 April 2015
( Spotify )

Initial thoughts on his code

  • Tidy, and designed with lots of traditional comments
  • Async all the way (just use .Wait to make it sync)
  • Testable
    • HttpClient mocking out
  • ClientCredentialsAuthorizationApi
  • Caching
  • Defensive code checking for NullOrEmpty

Putting on a test Console App


Annoying that breakpoint is caught at top level.

Okay so I just need to break in VS!

| | # 
# Friday, 17 April 2015
( LSCC | Spotify )

Thanks to everyone who came last night - really appreciated the questions and laughter!!

The soundtrack before the talk was:


An Elvis impersonator, covering dead people.  I really like this album

The Talk  (main site – Amazon EC2) (test site - Azure) – Build / Test / Deploy to Azure


Code and presentation: (I’ll put the HQ videos up there this weekend)

Music Discussed

Where to Next?

Got some great questions on testing which is making me think of where next..

| | # 
# Tuesday, 14 April 2015
( Spotify )


Doing anything that needs authorisation fails.

| | # 
# Tuesday, 24 March 2015
( Async | Spotify )

Exploring how to call multiple webservices in parallel as many of the calls for Spotify can be made at the same time.

WebClient – since 1.1.  common methods for sending data to and receiving data from a resource identified by a URI. Simpler.
HttpWebRequest – since 1.1.  HTTP Specific implementation of WebRequest.  Allows more control
HttpClient – .NET45 or in Nuget.  Based on HttpWebRequest. Task oriented pattern for handling async requests..The benefits that HttpClient brings is with the standard classes like HttpResponseMessage, HttpRequestMessage, HttpContent and all the strongly typed headers


static void Main() { //explore async/await for when I do many API calls // what if there is an error? //Sync(); Async(); Console.WriteLine("done"); } static void Sync() { var stopWatch = new Stopwatch(); stopWatch.Start(); var url = ",0eFHYz8NmK75zSplL5qlfM,0lw68yx3MhKflWFqCsGkIs,0HcHPBu9aaF1MxOiZmUQTl,5eJTvSeghTKoqN3Ly4TqEf,1Dh27pjT3IEdiRG9Se5uQn,6AyUVv7MnxxTuijp4WmrhO"; for (int i = 0; i < 5; i++) { Console.WriteLine("Starting " + i); HttpWebRequest request = HttpWebRequest.CreateHttp(url); string text; using (var response = request.GetResponse()) { using (var sr = new StreamReader(response.GetResponseStream())) { text = sr.ReadToEnd(); } } Console.WriteLine("result of " + i + " " + text.Substring(0,400)); } stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:0}", ts.TotalMilliseconds); Console.WriteLine("Total: " + elapsedTime); } static void Async() { var stopWatch = new Stopwatch(); stopWatch.Start(); ServicePointManager.DefaultConnectionLimit = 50; const int n = 5; Task<string>[] tasks = new Task<string>[n]; for (int i = 0; i < n; i++) { tasks[i] = CallAPI(i); } Task.WaitAll(tasks); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:0}", ts.TotalMilliseconds); Console.WriteLine("Total: " + elapsedTime); } // Switch to HttpClient - .NET45.. static async Task<string> CallAPI(int i) { Console.WriteLine("CallAPI enter " + i); var url = ",0eFHYz8NmK75zSplL5qlfM,0lw68yx3MhKflWFqCsGkIs,0HcHPBu9aaF1MxOiZmUQTl,5eJTvSeghTKoqN3Ly4TqEf,1Dh27pjT3IEdiRG9Se5uQn,6AyUVv7MnxxTuijp4WmrhO"; HttpWebRequest request = HttpWebRequest.CreateHttp(url); string text; using (var response = await request.GetResponseAsync()) { using (var sr = new StreamReader(response.GetResponseStream())) { text = sr.ReadToEnd(); } } Console.WriteLine("CallAPI exit " + i + text.Substring(0,400)); return text; } – WebRequest will only make 2 calls to the same host – HTTP niceness!


Connection limit

Sync – 9.7s
1 – 9.7s
2 – 5.3s
3 – 3.7s
4 – 3.2s
5 -  3.1s
6 – 3.0s
10 – 2.4s
20 – 2.2s
50 – 2.2s

| | # 
# Wednesday, 04 March 2015
( Azure | Spotify )

Whilst at work (in Brighton) on a 50meg leased line

Huge performance difference in API query time (I think) between Azure in Western Europe and my local line.  I believe Spotify’s servers are in London so this would make sense to be slightly faster, however such a big difference doesn’t.

Azure Different Plans

Free website – no (as 185MB data limit)
Shared website – yes.. this is what this is on..costing approx 5UKP per month + 5UKP database?
B1 Small Instance – moved to that. 1 Core.  1.75GB RAM.  20UKP per month + 5UKP database?

Website in West Europe
B Basic - DB is West Europe (max size 2GB)

Spun up a
S1 Small Instance in Northern Europe
B Basic DB in Northern Europe

No massive difference coming from Northern Europe



Spotify Web API Speed Test Page

A page testing the speed of API calls to Spotify

229 :

461 :

615 :,3vLaOYCNCzngDf8QdBg2V1,3vLaOYCNCzngDf8QdBg2V1,3vLaOYCNCzngDf8QdBg2V1,3vLaOYCNCzngDf8QdBg2V1

987 :,1cvcW2kVGrN9tdyoaVjmf0,0m8wvW3WNm9D7J0KUlbf3h,1nojrwBYMmq5jY1gJYtywa,0lrBKnE4qQnr8VM56J3gow,4ttFaYVApnyblaGHNwGAf7,62Qu5QoNx3De0p5qQT0u7o,69UMMsDqpBwy7Dr2oZn2Ra,311yDc6Ow5WF8puYAAte1B,05IBZIkN7fdbiVCgGCJCWX,6Z9OaWRC8Bsb64OyhiZ49L,6GMHua20KrXo7MlfwbTWk1,40pk5HrcQ3TDP0KBP3KhfQ,6KZwPiN4oDTcvgtbHGr1A1,2zlXL0UVwQrH9FRFSvNOBg,5hNZOA0YJBq0bGYnWGSo5x,0QluVU5ReXs7oI1ZyS101F,6pJf6YRFeyj615gGq6yDnZ,777UeiexLMf1mFR42nSoR2,2qkxQSusZ6JXAzpnptVUo1

987 :

391 :

194 :


Work vs Azure

Test to see if it’s actually Spotify limiting me
pass the token?

Seems to make no difference passing a token

In fact, mostly faster without the token

I guess the next thing to do is try it somewhere else.  Amazon EC2?


EC2 is fast!

Azure VM - Slow

A1 Azure VM of it being painfully slow.  1.75GB RAM, 1 Core – seems I’m not along.

He went to a high perf cheaper SSD alternative

SQL stuff

D1 for SSD – creating 3.5GB RAM, 50GB SSD, 1core.. £78 per month?



Much faster (even on the micro instance).

Decided to register a domain name – using

| | # 
# Tuesday, 03 March 2015
( Spotify )

2.2 seconds on API calls is feeling slow.

“The TOS section you're asking about is to prevent people making automated tools that scrape the Spotify catalogue without user interaction. If you're writing a "normal" application and caching data from the Spotify APIs as a result of a user actually doing something like searching, browsing, etc etc you have no problems.”

| | # 
# Saturday, 28 February 2015
( Spotify )

Annoying that some of the album date times are not there:


Some dates are in different formats.. just deal with it in code/use release_date_precision



| | # 
( Spotify )


Very annoying that when I select “She Talk to Angels” above

  • Its the wrong album – I want the original, not the compilation..
    • Shake Your Money Maker (1990)
  • It will get the wrong date for the track (as its a compilation)

First thing to do is to get dates into the list of all Artists albums:

Find just Studio Albums

Filter on album_type: album  (so not single or compilation)
Filter out anything with no available markets?
Look at all tracks in all albums, and find earliest album it appears on?
Exclude: "[Collectors Edition]" and "(Collector's Edition)" etc..  Live?.. filter out Remastered?

album_type = single.. Muse

| | # 
( Spotify )

I gave an internal presentation on this side project.  It was great fun.  Some notes:

source: live on:

As a programmer, Bob comes to Dmusic, browses top tracks, and adds his favourite tracks which then get sync'd to his Spotify.

As a programmer, Alice comes back to Dmusic, logs in via Spotify, and adds tracks to her playlist via searching

This story isn’t quite working, but as an Admin I can add “Spotify Top Tracks” to the “Top Tracks” page

Some musical highlights:

And from me, the best Abba cover versions of all time!

| | # 
# Friday, 20 February 2015
( Spotify )



Firstly get playlist uploading for different users!

Each of these screens has button that says “Add” or “Remove”.. then goes to “My Playlist” which uploads it to Spotify


To get a button that doesn’t post, I need some form of Ajax.

<script src="~/Scripts/jquery-1.10.2.min.js"></script> <script type="text/javascript"> function addTrack(trackId) { $.get('@Url.Action("AddTrack","Home")', { trackId: trackId }, function (data) { $("#message").html(data); }); } </script> <button onclick="addTrack(12345)">Add</button> <div id="message"></div>

And controller:
public string AddTrack(string trackId) { return trackId + " added to my playlist"; }

| | # 
# Wednesday, 11 February 2015
( Spotify )


Next goal is to have tick boxes and a button that says add albums to my DavesMusic playlist.
Modelbinder is not returning my ViewModel back to the HttpPost method on the controller.  Possibly it is because I have class names the same as properties.
No not that – interesting issue. – This is a good post on getting a ViewModel working in MVC.  The issue was I wasn’t displaying and posting back the ViewModel data.

I can use Html.HiddenFor helper to pass back data – someone with the same issue. – a detailed explanation including passing back collections.

passback to the ID and checked or not – This worked

| | # 
# Monday, 02 February 2015
# Friday, 30 January 2015
( Spotify ) – hosting (free option) – source control – keep site alive and monitor
error handling?
google analytics? site visitors






/Me/Index – gets current logged in user profile (OAuth)

If not currently authorised redirect to
comes back to


Am designing my routing to follow Spotify’s API – lets go plural

/Browse/NewReleases ??


Was in the SpotifyCallback method

| | # 
# Monday, 26 January 2015
( Spotify )



/Home/SpotifyCallback – Includes his own http server – no authorization – useful! (spotify webapi) – setting up post and async

Can get an access token now!!

Using the access token to get data about the currently logged in user

url = ""; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", access_token); httpResponse = client.GetAsync(url); var result2 = httpResponse.Result.Content.ReadAsStringAsync().Result; //dynamic obj2 = JsonConvert.DeserializeObject(result2); var meReponse = JsonConvert.DeserializeObject<MeResponse>(result2);

Useful bit of dynamic code as it allowed me to see the json and convert it using into a MeResponse class.

HttpClient and HttpWebRequest

HttpClient uses HttpWebRequest as it’s transport library

“The benefits that HttpClient brings is with the standard classes like HttpResponseMessage, HttpRequestMessage, HttpContent and all the strongly typed headers” – possible useful.. a library for helping with Http calls and dealing with API’s

| | # 
# Friday, 23 January 2015
( Spotify )

“The Echo Nest has linked our IDs to Spotify”


The and Wikipedia entries seem to be the best

| | # 
# Thursday, 22 January 2015
( Spotify )


Related Artists – I’ve limited it to the top 7 (20 returned by default)

| | # 
# Wednesday, 21 January 2015
( Spotify )



So now I should make an /Album/Details/ link


| | # 
# Monday, 19 January 2015
( Spotify )

image – Calling the Spotify API, putting result into json2csharp, then looking at POCO in VS.

string url = ""; json = spotifyHelper.CallSpotifyAPIArtistTopTracks(stopWatchResult, id, ref url); var artistTopTracks = JsonConvert.DeserializeObject<ArtistTopTracks>(json); apiDebug = new APIDebug { APITime = String.Format("{0:0}", stopWatchResult.ElapsedTime.TotalMilliseconds), APIURL = url };

Passing a debug string by reference, so can easily get it returned

public string CallSpotifyAPIArtistTopTracks(StopWatchResult stopWatchResult, string artistCode, ref string url) { url = String.Format("{0}/top-tracks?country=GB", artistCode); var json = CallAPI(stopWatchResult, url); return json; }

However this is a smell:

“Basically its a way of getting another return value and should usually be avoided precisely because it means the method’s probably trying to do too much” Skeet.


var apiResult = spotifyHelper.CallSpotifyAPIArtistTopTracks(stopWatchResult, id); var artistTopTracks = JsonConvert.DeserializeObject<ArtistTopTracks>(apiResult.Json); apiDebug = new APIDebug { APITime = String.Format("{0:0}", stopWatchResult.ElapsedTime.TotalMilliseconds), APIURL = apiResult.Url };


public APIResult CallSpotifyAPIArtistTopTracks(StopWatchResult stopWatchResult, string artistCode) { var url = String.Format("{0}/top-tracks?country=GB", artistCode); var json = CallAPI(stopWatchResult, url); return new APIResult { Json = json, Url = url }; }
public class APIResult { public string Json { get; set; } public string Url { get; set; } }

Similar amounts of code, and is clearer.

Got previews working with preview_url!


| | # 
# Thursday, 15 January 2015
( Spotify ) – Muse

Not much more detail!

The details page of an Artist.. great images are the best bit!

Followers too are interesting vs popularity


Random  - Html Encoded
:2001 brings back 66,896 results.. from 0000:2001
:2014 brings back 672,262 results
:2014 no US 698,288 – 2,279,823 – 2,196,115

then get the total and pick a random offset between 1 and that total
&limit=1&offset=12345 – works doesn’t

That offset isn’t bringing back any data, but 12345 does.. found up to 100,000 brings back data

Implemented random from 0 to 100,000 offset.  Interesting!  API calls are slower (as am doing 3)..cut it to 2

next – implement back button on random…/Artist/Details/12345&showNextRandomLink=true

| | # 
# Wednesday, 14 January 2015
( Spotify )

Want to click on the image to get

  • More info on Muse
  • Full details of their albums

Go with /Artist/Details/123456



External_url – used in open in web spotify eg

Open directly – chrome knows about local spotify app:  spotify:artist:5M52tdBnJaKSvOpJGz8mfZ

| | # 
# Thursday, 08 January 2015
# Tuesday, 06 January 2015
( c# | JSON | Spotify )

Goal: Get API calls working to Spotify using a console app – c# importer (no auth)

Using a deprecated call

Interesting I’m getting 224 results back!

Can type in the Href and test have got the correct song back.

This old Metadata API, which is now deprecated (but still working).

Old API returning XML.
The Web API

JSON Formatter extension for Chrome
Interactive Console for exploring the API

  • Album
  • Artist
  • Track
  • Playlist

Exploring the json and viewing the image URL’s that are returned


An image of the band

Am using Newtonsoft’s JsonConvert.DeserializeObject<T> to get into a POCO:

Used the API to get a simple search going on the web.

Exploring the json returned results, finding that some artists return 3,4 or 0 images.  So put some simple view logic in to force display of 200 width.  And put in a sample default band (muse) on page load of


Offset and Limit

Limit default is 20, max is 50.


var stopWatch = new Stopwatch(); stopWatch.Start(); string json = CallSpotifyAPI(artistName); stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:0}",ts.TotalMilliseconds); ViewBag.APITime = elapsedTime;
TotalMilliseconds is handy.  Format makes sure no decimal points in the ms.

Timing code.  Next and previous buttons.  All GET requests now – form submits via querystring.  Title is different if no search.

| | # 
# Monday, 05 January 2015
( Spotify )


Very simple generated page (source is very simple)

| | # 
# Thursday, 01 January 2015
( Spotify )

Includes playlist searching

  • rock (good!)
  • party
  • 80
  • sleeping baby
  • guitar
  • workout
  • playlist
  • roadtrip
  • easy listening
  • running

love the way it can create playlists easily

Many calls to the Spotify API

Uses Echo Nest API to extract genre information

Spotify Web API to play tracks


| | # 
# Wednesday, 31 December 2014
( Spotify )

… lets your applications fetch data from the Spotify music catalog and manage user’s playlists… – 3 different OAuth2.0 flows:

  • Authorization Code flow
  • Client Credentials flow
  • Implicit Grant flow – several endpoints here

Many endpoints are open, however to access private data eg user profiles and playlists, and application must get the user’s permission: – authorisation

  • GET – retrieving resources
  • POST – creating resources
  • PUT – Changing/replacing resources
  • DELETE – Delete resources

Integration with Echo Nest - – lots of demos here

Auth Key


Name will be shown in the popup that asks the user for authorisation.

Add a redirect URI


ClientID – Unique identifier for my app.  not secret

Client Secret – the key that I will need to pass in secure calls to the Spotify Accounts and Web API services.

Installed node.js from

/* Load the HTTP library */ var http = require("http"); /* Create an HTTP server to handle responses */ http.createServer(function(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); }).listen(8888);

Saved this as server.js in c:\dev\test\spotify and ran: node server.js then

Connecting to the localhost webserver ran by node.

Cloned the example app repository from

npm install –g express
npm install –g request
npm install –g querystring

couldn’t get npm to work without the –g

Authorization Code Example

app.js – put in ClientID, Client Secret and Redirect URI.

npm install in the authorizationcode directory

node app.js




Search for an Artist Demo

Plays 30s too.

Dot Net Wrapper for Web API

uses an open service, which returns json:

| | # 
# Monday, 29 December 2014
( Spotify )

As part of a potential project, I’m spiking out what can be done with Spotify.


"Our Web API lets your applications fetch data from the Spotify music catalog and manage user’s playlists and saved music."

Uses OAuth2

Follow Button

Follow friends, artists and organisations





My Music, Artists, can see him

Then get a notification when he releases something on Spotify.. By email too.

Or go to the artists page in Spotify and just hit follow.

Open - Good Beatles covers here.

A webplayer, which spins up the Spotify client.

Spotify Play Button – Track (Song)

When a logged-in Spotify user clicks the button, the music will start playing in a Spotify client. (Which client depends on both the platform, and on the user account settings:

Play – Track

http link:

spotify uri: spotify:track:0mDHS1Q7HGtpgjYAyG2Svn


embed code: iframe src="" width="300" height="80" frameborder="0" allowtransparency="true">

Play – Album


Play – Playlist


iframe src="" width="300" height="380" frameborder="0" allowtransparency="true"

Only the first 200 tracks are displayed in a playlist.

Takes 10 minutes for updates to appear in this playlist

Multiple Tracks Player

iframe src=",

Looks like a playlist, but just hardcoded tracks

| | # 
# Sunday, 21 December 2014
( Spotify )

Ctl + right – next song
Ctrl + left – previous

Enter – play
Space – pause

Ctrl + L – search box

search on:


| | #