ERMO logo ERMO Puzzle Available for

How to integrate Xbox Live API in UWP games

Thanks to the Xbox Live Creators Program, the Xbox Live services are available to any developer who wants to code on the UWP platform.

We joined the program and we’re very happy we published ERMO. Being a UWP game, ERMO runs nicely on any Windows10 device, included the Xbox One.

Now we want to share our experience with the Xbox Live SDK and write a detailed How-To showing all the steps required to deal with the Xbox Live API. In other words, lots of monospace characters will follow.

UWP supports many languages to code with, but mostly C++, C# and Javascript.

Because ERMO is written (mostly) in Typescript, a superset of JS, all snippets included in this post is written in Javascript. It’s very easy to adapt them to C# or C++. Maybe the promise stuff isn’t directly translable, just use the async paradigm in C# or create_task in C++.

At least, we hope you will get the core idea behind the code.

XboxLive Creators supported features

Actually, under the banner of the Creators Program, a developer can leverage the following Xbox Live features:

  • Identity authentication
  • Profile and SocialGraph querying
  • Leaderboard/Stats management

Other features, like basic presence and social feed, are automatically managed by the service, with no keystroke by the developer. The full list on the documentation.

In this post, we focus on features developers have to actively code against the SDK, the subset available with the Creators Program.

Outline

Import Xbox Live SDK

Like all Windows based development, NuGet is the way to go to import SDKs, libs and any other dependency. The easiest way is to use the integrated NuGet interface in Visual Studio. A free version of Visual Studio is available as Community Edition.

To import XboxLive SDK, right click on the References node under the project root and chose Manage NuGet Packages.... It’s available under the Project menu too. NuGet Package Manager

Pick the Microsoft.Xbox.Live.SDK.WinRT.UWP and install it. Then wait for the huge download to complete.

At the time of this post, the latest SDK version is 2017.8.x. All code examples and API calls refer to that version.

Xbox Live Authentication

The mandatory first step to access all XboxLive services is to authenticate the user to the XboxLive system.

There’re a couple of options, but the most straightforward and effective is to use signInAsync.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var xbox = Microsoft.Xbox.Services,
user = new xbox.System.XboxLiveUser();
/**
* Returns a Promise that resolves when the sign in process completes
*/
function signIn() {
return new Promise(function(resolve, reject) {
user.signInAsync(null).then(function (r) {
if (r && r.status === xbox.System.SignInStatus.success) {
resolve();
} else {
reject();
}
}, reject);
});
}

Retrieve user profile, Gamertag and picture

Once the user is authenticated, you can load its profile with all info associated like the gamertag, score and picture.

We need a XboxLiveContext to query the profile service and get the data we looking for.

In the following snippet, some utility functions are introduced to make the code cleaner.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/** @type {Microsoft.Xbox.Services.Social.XboxUserProfile} */
var userProfile;
/**
* Returns a Promise with the userProfile
*/
function getPlayerProfile() {
if (userProfile) {
return Promise.resolve(userProfile);
}
return loadPlayerProfile(user.xboxUserId).then(function (profile) {
userProfile = {
playerId: user.xboxUserId,
playerName: user.gamertag,
playerScore: user.gamerscore,
playerImage: profile.gameDisplayPictureResizeUri.rawUri
};
return userProfile;
});
});
function loadPlayerProfile(userId) {
return getContext().profileService.getUserProfileAsync(userId);
}
/** @type {Microsoft.Xbox.Services.XboxLiveContext} */
var context;
function getContext() {
if (!context) {
context = new xbox.XboxLiveContext(user);
}
return context;
}

Use leaderboards to submit player scores and stats

Leaderboards and statistics are another services the XboxLive provides. You can define up to 20 of them through the dev center. You need also to localize them in any language your game supports.

Developers under the Creators Collection program don’t get the full leaderboard features, but the service is limited to just player stats.

Key difference is that a leaderboard is composed by multiple stats, like multiple columns in a table where each row is a player entry. Instead, a stat is a simply a list of players and their score (it can be anything), in other words, it’s the common scenario where the game UI displays the score list.

In this post, we stick to stats as they’re enough to make a chart with the player scores.

It’s introduced the StatisticManager by which we can send scores. Because StatisticManager is a singleton instance, we reference directly it while the XboxLiveContext is created. In addition, StatisticManager needs to know on which players it will operate, thus we add the current player to its users.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/** @type {Microsoft.Xbox.Services.Statistics.Manager.StatisticManager} */
var statManager;
/**
* Submit a score to the XboxLive service
* @param {string} leaderboardId
* @param {number} value
*/
function submitScore(leaderboardId, value) {
statManager.setStatisticIntegerData(user.xboxUserId, leaderboardId, value);
statManager.requestFlushToService(user.xboxUserId);
}
//create statManager while creating context
function getContext() {
if (!context) {
context = new xbox.XboxLiveContext(user);
statManager = xbox.Statistics.Manager.StatisticManager.singletonInstance;
try {
statManager.addLocalUser(user); //add actual user
} catch (e) { }
}
return context;
}

In the above snippet, it’s assumed the score is an integer value, but you can use other supported data types(Integer, Numeric, String) and change the call accordingly.

submitScore is a fire and forget function, you won’t receive any value, as the StatisticManager processes all things in background when you use requestFlushToService.

Submit multiple score at once

If you send too many scores in a short time interval, XboxLive services will begin to throttle all your calls. Official documentation states to flush scores at most once every 5 minutes or so.

To limit this side effect and to avoid throttling, you can submit a batch of scores with one call.

1
2
3
4
5
6
7
8
9
10
11
12
/**
* Submit a batch of scores
* @param {Array.<{leaderboardId: string, score: number}>} scores
*/
function submitScores(scores) {
for (var a = 0; a < scores.length; a++) {
var entry = scores[a];
statManager.setStatisticIntegerData(user, entry.leaderboardId, entry.score);
}
statManager.requestFlushToService(user);
}

Retrieving and querying leaderboard scores

As mentioned earlier, here for leaderboards we intend stats, as we use them to send and get player scores.

Because the StatisticManager works in the background, the process of getting the data isn’t straightforward like a single call, but requires a more elaborate flow.

The process involves polling the StatisticManager for events and, when ready, processing the results.

In Javascript to perform the polling we use setTimeout to delay each call by 100ms. In other contexts or engines you should poll on any frame, thus bounding the call to the frame execution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* Returns a Promise with leaderboard entries
* @param {string} leaderboardId
* @param {number} maxItems
*/
function getLeaderboardScores(leaderboardId, maxItems) {
var query = new xbox.Leaderboard.LeaderboardQuery();
query.maxItems = maxItems;
statManager.getLeaderboard(user, leaderboardId, query);
return startPollingStatManager(leaderboardId);
}
function startPollingStatManager() {
return new Promise(function (resolve, reject) {
pollStatManager(resolve, reject);
});
});
function pollStatManager(resolve, reject) {
try {
var events = statManager.doWork();
for (var a = 0; a < events.length; a++) {
if (events[a].eventType === xbox.Statistics.Manager.StatisticEventType.getLeaderboardComplete) {
var result = events[a].eventArgs.result;
if (result) {
resolve(processLeaderboardResult(result));
} else {
resolve([]);
}
return;
}
}
} catch (e) {
reject();
}
//poll again after 100ms
setTimeout(function() {
pollStatManager(resolve, reject);
}, 100);
}
/**
* @param {Microsoft.Xbox.Services.Leaderboard.LeaderboardResult} result
*/
function processLeaderboardResult(result) {
var entries = [],
profiles = [];
for (var a = 0, l = result.rows.length; a < l; a++) {
var row = result.rows[a],
value = row.values[0];
profiles.push(row.xboxUserId);
entries.push({
playerId: row.xboxUserId,
playerName: row.gamertag,
playerImage: undefined, //we need to load it later
rank: row.rank,
//assumes score is an integer value
score: !isNaN(value) ? value : parseInt(value, 10)
});
}
return entries;
}

The flow isn’t the most linear in the field, but it works nicely when you call just the surface area of the snippet.

1
2
3
4
5
var leaderboard = "ermo-highscore-itinerary",
maxItems = 10;
getLeaderboardScores(leaderboard, maxItems).then(function(entries){
//here we can cycle and show the entries to the screen
});

Loading multiple player profiles

To complete the Retrieve leaderboard scenario, the last step is to load all players’ picture. As we did for the user logged in, the profile service comes handy to get all player profiles.

We have to pass the user-id list to get the pictures we want.

1
2
3
4
5
6
7
/**
* Returns a Promise with an array of player profiles
* @param {Array.<string>} userIds
*/
function loadPlayerProfiles(userIds) {
return getContext().profileService.getUserProfilesAsync(userIds);
}

Conclusion

With the Xbox Live SDK available for the UWP platform is pretty easy to take advantage of the Xbox Live services. Due to large amount of features, the Xbox Live SDK is huge and the API surface area can be confusing sometimes.

With this HowTo, we hope we eased the integration task for any developer willing to put some efforts on the UWP platform.

Keep coding.

Keep you eyes on this dev oriented caravanserai

If you want you can stay in touch:

This website uses cookies to improve your experience