Export (0) Print
Expand All

Sample Music Client Using .NET

The following code demonstrates a simple, end-to-end scenario in C# and .NET for obtaining an access token for the Xbox Music Service, obtaining a second token, and then querying the service for information about an artist.

Dn546687.note(en-us,IEB.10).gifNote

HttpWebRequest is used in the following code example, because this is a synchronous console application. In an asynchronous application, other methods would be preferred. For an example, see Sample Music Client Using Windows Runtime.

  using System;
  using System.Collections.Generic;
  using System.Collections.Specialized;
  using System.IO;
  using System.Linq;
  using System.Net;
  using System.Net.Http;
  using System.Net.Http.Headers;
  using System.Text;
  using System.Text.RegularExpressions;
  using System.Threading.Tasks;
  using System.Web;

  namespace XboxMusicAPIRestTest
  {
      class Program
      {
          static void Main(string[] args)
          {
              string service = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";
              string clientId = "myClient";
              string clientSecret = "REDACTED";
              string clientSecretEnc = System.Uri.EscapeDataString(clientSecret);
              string token = null;
              string tokenEnc = null;
              HttpWebRequest request = null;
              HttpWebResponse response = null;

              // NOTE http. not https here!
              string scope = "http://music.xboxlive.com";
              string scopeEnc = System.Uri.EscapeDataString(scope);

              // Obtain first token
              string grantType = "client_credentials";
              string postData = "client_id=" + clientId + "&client_secret=" + clientSecretEnc + "&scope=" + scopeEnc + "&grant_type=" + grantType;
              string responseString = SendRequest("POST", service, postData);
              token = ExtractTokenFromJson(responseString);
              tokenEnc = HttpUtility.UrlEncode(token);

              // Make Music database request
              request = (HttpWebRequest)WebRequest.Create("https://music.xboxlive.com/1/content/music/search?q=daft+punk&accessToken=Bearer+" + tokenEnc);
              request.Method = WebRequestMethods.Http.Get;
              request.Accept = "application/json";
              using (response = (HttpWebResponse)request.GetResponse())
              {
                  using (var sr = new StreamReader(response.GetResponseStream()))
                  {
                      responseString = sr.ReadToEnd();
                  }
              }

              // Dump database response to console
              Console.WriteLine(responseString);
              Console.WriteLine("\nPress any key to exit.");
              Console.ReadKey();
          }
        

          static string ExtractTokenFromJson(string json)
          {
              string token = null;
              Match match = Regex.Match(json, ".*\"access_token\":\"(?<;token>;.*?)\".*", RegexOptions.IgnoreCase);
              if (match.Success)
              {
                  token = match.Groups["token"].Value;
              }
              return token;
          }


          static string SendRequest(string method, string service, string postData)
          {

              string responseString = null;
              HttpWebRequest request = (HttpWebRequest)WebRequest.Create(service);

              UTF8Encoding encoding = new UTF8Encoding();
              byte[] data = encoding.GetBytes(postData);

              request.Method = method;
              request.ContentType = "application/x-www-form-urlencoded";
              request.ContentLength = data.Length;

              using (Stream stream = request.GetRequestStream())
              {
                  stream.Write(data, 0, data.Length);
              }

              using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
              {
                  responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
              }
              return responseString;
          }

      }
  }

Community Additions

Show:
© 2014 Microsoft