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.
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
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
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.
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
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
Step 7
Then Step 2/3 allows you to indicate Are you developing a commercial integration? so select No for this Question
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
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
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…
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
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.
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…
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
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
Step 17
From the Menu choose View and then 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
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
Step 22
After the Application has started it should be showing the first ten newest albums on Spotify in the Application
Step 23
To Exit the Application select the Close button in the top right of the Application