Universal Windows Platform – Spotify

Spotify demonstrates how to display the ten newest released albums on Spotify

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once done start your favourite Web Browser such as Microsoft Edge and navigate to developer.spotify.com for the Spotify for Developers Website

spotify-site-developers

Step 3

Then on the Spotify for Developers Website select Dashboard then on the Your Dashboard Page choose Log In to sign in with a Spotify Account

spotify-site-create-and-manage

If you don’t have a Spotify account already you can use the Sign up for a free Spotify account here option on that page to get a Spotify account – you will already have one if you have a Spotify Subscription or already listen to their free music streaming service.

Step 4

Once you’ve signed in with a Spotify for the first time you will need to read through the Spotify Developer Terms of Service then once done select the I accept the Spotify Developer Terms of Service and then Accept the Terms to continue.

spotify-site-terms

Step 5

Once signed in with a Spotify Account and agreet to the Spotify Developer Terms of Service you’ll be taked to the Dashboard

spotify-site-dashboard

Step 6

Select the Create a Client Id then follow the steps for Create an App or Hardware Integration where Step 1/3 will be to enter an App or Hardware Name as Tutorial and App or Hardware Description as Tutorial then choose from What are you building? the Desktop option then select Next

spotify-site-dashboard-step-one

Step 7

Then Step 2/3 allows you to indicate Are you developing a commercial integration? so select No for this Question

spotify-site-dashboard-step-two

Step 8

Finally Step 3/3 needs you to read through, including any related links for the following questions I understand that this app is not for commercial use, I understand that I cannot migrate my app from non-commercial to commercial without permission and I understand and agree with Spotify’s Developer Terms of Service, Branding Guidelines, and Privacy Policy then choose Submit

spotify-site-dashboard-step-three

Step 9

Once created the Client Id which you will need to copy for later, then choose the Show Client Secret option to display the Client Secret which you will also need to copy for later and completes the process for signing up for the Spotify API

spotify-site-dashboard-added

The Client Id and Client Secret will need to copied and saved for later for use in the Application, they must be kept secret as they’re for use only with your Application.

Step 10

Then return to Visual Studio Community 2017 and from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 11

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project

vs2017-new-project-window

Step 12

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 13

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 14

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project

vs2017-add-new-item-library

Step 15

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls;
using Windows.Web.Http;
using Windows.Web.Http.Headers;

[DataContract]
public class Image
{
    [DataMember(Name = "url")]
    public string Url { get; set; }
}

[DataContract]
public class ExternalUrls
{
    [DataMember(Name = "spotify")]
    public string Spotify { get; set; }
}

[DataContract]
public class Item
{
    [DataMember(Name = "external_urls")]
    public ExternalUrls External { get; set; }
    [DataMember(Name = "images")]
    public List<Image> Images { get; set; }
    [DataMember(Name = "name")]
    public string Name { get; set; }
}

[DataContract]
public class Albums
{
    [DataMember(Name = "items")]
    public List<Item> Items { get; set; }
}

[DataContract]
public class Browse
{
    [DataMember(Name = "albums")]
    public Albums Albums { get; set; }
}

public class Library
{
    private const string client_id = "ClientId";
    private const string client_secret = "ClientSecret";
    private const string token_uri = "https://accounts.spotify.com/api/token";
    private const string request_uri = "https://api.spotify.com/v1/browse/new-releases";
    private const string request_param = "?limit=10";
    private const string grant_type = "grant_type";
    private const string client_credentials = "client_credentials";
    private const string token_regex = ".*\"access_token\":\"(.*?)\".*";
    private const string auth_basic = "Basic";
    private const string auth_bearer = "Bearer";

    private HttpClient _client = new HttpClient();
    private HttpResponseMessage _response = new HttpResponseMessage();
    private Browse _browse = new Browse();
    private string _token = null;

    private void Auth(string scheme, string value)
    {
        _client.DefaultRequestHeaders.Authorization =
        new HttpCredentialsHeaderValue(scheme, value);
    }

    private async Task<string> Token()
    {
        if (_token == null)
        {
            Auth(auth_basic, 
                Convert.ToBase64String(Encoding.ASCII.GetBytes($"{client_id}:{client_secret}")));
            _response = await _client.PostAsync(new Uri(token_uri),
                new HttpFormUrlEncodedContent(new Dictionary<string, string>() { { grant_type, client_credentials } }));
            _token = System.Net.WebUtility.UrlEncode(
            Regex.Match(await _response.Content.ReadAsStringAsync(),
            token_regex, RegexOptions.IgnoreCase).Groups[1].Value);
        }
        return _token;
    }

    public async void Init(ListView display)
    {
        Auth(auth_bearer, 
            await Token());
        _response = await _client.GetAsync(new Uri(request_uri + request_param));
        byte[] json = Encoding.Unicode.GetBytes(await _response.Content.ReadAsStringAsync());
        using (MemoryStream stream = new MemoryStream(json))
        {
            _browse = (Browse)new DataContractJsonSerializer(typeof(Browse)).ReadObject(stream);
        }
        display.ItemsSource = _browse?.Albums?.Items;
    }
}

While still in the Code View for Library.cs change “ClientId” to be the one created and copied from the Spotify for Developers Website e.g. 436c69656e744964 and change “ClientSecret” to be the one created and copied from the Spotify for Developers Website e.g. 436c69656e74536563726574

In the Library.cs there are using statements to include the necessary functionality. There is then Classes to represent the various types of Object that will be returned by the Spotify API – Image which is for Images, ExternalUrls for links back to Spotify, then there’s Item which will be for items in the Albums Class returned in the Browse Object. The Library Class contains const values to be used when calling the API the client_id and client_secret values will be set to those needed by the Spotify API and there are Members for the HttpClient and HttpResponseMessage to connect and recieve messages from the API. There is an Auth Method to authenticate with the API to provide the Client Id and Client Secret which will return a Token to be used with subsequent authenticated calls to the Spotify API. The Token Method is used to obtain the token for other calls to use which is done in the Init Method to get the Ten Newest Released Albums from Spotify and display these in a ListView by setting them to its ItemsSource.

Step 16

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

Step 17

From the Menu choose View and then Designer

vs2017-view-designer

Step 18

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<ListView Name="Display">
	<ListView.ItemTemplate>
		<DataTemplate>
			<StackPanel Orientation="Horizontal">
				<Image Margin="10" Height="75" Width="75" Source="{Binding Images[0].Url}"/>
				<HyperlinkButton Content="{Binding Name}" NavigateUri="{Binding External.Spotify}" VerticalAlignment="Center"/>
			</StackPanel>
		</DataTemplate>
	</ListView.ItemTemplate>
	<ListView.ItemContainerStyle>
		<Style TargetType="ListViewItem">
			<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
		</Style>
	</ListView.ItemContainerStyle>
</ListView>

The first block of XAML the main user interface of the Application, this features a ListView with its ItemTemplate set to a DataTemplate made up of a StackPanel with an Image which is Databound to the Url of one of the Images and a HyperlinkButton which has its NavigateUri set to the External.Spotify Link and the Content set to the Name of the Item.

Step 19

From the Menu choose View and then Code

vs2017-view-code

Step 20

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

protected override void OnNavigatedTo(NavigationEventArgs e)
{
	library.Init(Display);
}

Below the MainPage() Method an instance of the Library Class is created. The OnNavigatedTo Event Handler will call the Init Method in the Library Class.

Step 21

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 22

After the Application has started it should be showing the first ten newest albums on Spotify in the Application

ran-spotify

Step 23

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s