Skip to content

AccelByte/accelbyte-csharp-modular-sdk

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AccelByte Modular .NET (C#) SDK

⚠️ This accelbyte-csharp-modular-sdk is not to be confused with accelbyte-csharp-sdk:

  • The former (modular SDK) is experimental and is planned to be the sucessor for the latter (monolithic SDK).
  • The modular SDK allows developers to include only the required modules in projects.
  • If you are starting a new project, you may try to use modular SDK.
  • If you use monolithic SDK in an existing project, a migration path is available via compatibility layer in modular SDK.
  • Both monolithic and modular SDK will be maintained for some time to give time for migration until monolithic SDK is deprecated in the future.

A software development kit (SDK) for interacting with AccelByte Gaming Services (AGS) written in C#.

This SDK was generated from AGS OpenAPI spec files included in the spec directory.

Setup

This SDK requires .NET 6.0 SDK to be installed.

Usage

# always include these package to use AccelByte .NET SDK
$ dotnet add package AccelByte.Sdk.Abstractions
$ dotnet add package AccelByte.Sdk.Core

# include this package to do authentication to AGS or token validation
$ dotnet add package AccelByte.Sdk.Authentication

# feature packages, these are optional
$ dotnet add package AccelByte.Sdk.Feature.AutoRefreshToken
$ dotnet add package AccelByte.Sdk.Feature.LocalTokenValidation

# Api packages. You can include only one or more packages depending on your need.
$ dotnet add package AccelByte.Sdk.Api.<ApiName>

# Compatibility layer. Use this package to enable compatibility layer with monolithic sdk version.
$ dotnet add package AccelByte.Sdk.Api.Compat

See the list of api packages here.

Environment Variables

The following environment variables need to be set when using DefaultConfigRepository.

Name Required Example
AB_BASE_URL Yes https://test.accelbyte.io
AB_CLIENT_ID Yes abcdef0123456789abcdef0123456789
AB_CLIENT_SECRET Yes, but only if you use a private AB_CLIENT_ID ab#c,d)ef(ab#c,d)ef(ab#c,d)ef(ab
AB_NAMESPACE Yes accelbyte

Instantiation

//Add core namespace
using AccelByte.Sdk.Core;
using AccelByte.Sdk.Core.Net.Http;
using AccelByte.Sdk.Core.Repository;

IAccelByteSdk sdk = AccelByteSdk.Builder
    .UseDefaultHttpClient()
    .UseDefaultConfigRepository() // Using DefaultConfigRepository, make sure the required environment variables are set
    .UseDefaultTokenRepository()
    .UseDefaultCredentialRepository() // Required if you want to load user's credential via environment variables.
    .UseDefaultTokenValidator() // Required if you want to use ValidateToken method.
    .Build();

Login

Login Using Username and Password

bool login = sdk.LoginUser("myUsername", "myPassword");
if (!login)
{
    // Login failed  
}

Login Using Username and Password with Defined Scopes

bool login = sdk.LoginUser("myUsername", "myPassword", "<selected scopes>", null);
if (!login)
{
    // Login failed  
}

Login Using Username and Password without Scopes

bool login = sdk.LoginUser("myUsername", "myPassword", null, null);
if (!login)
{
    // Login failed  
}

Login Using OAuth Client

bool login = sdk.LoginClient();
if (!login)
{
    // Login failed  
}

⚠️ Please use LoginClient() function with confidential OAuth client: Using LoginClient() function with public OAuth client is not supported.

Interacting with a Service Endpoint

As an example, we will get current user profile info using getMyProfileInfo endpoint available in basic service.

//Add api namespace
using AccelByte.Sdk.Api;

//Add basic service model namespace
using AccelByte.Sdk.Api.Basic.Model;

// Login using username and password

bool login = sdk.LoginUser("myUsername", "myPassword");
if (!login)
{
    Console.WriteLine("Login failed");
}

try
{
    // Make a call to getMyProfileInfo endpoint
    UserProfilePrivateInfo? response = sdk.GetBasicApi().UserProfile.GetMyProfileInfoOp.Execute(sdk.Namespace);

    /*
    
    // If you need to modify operation object, first you can build the operation object
    GetMyProfileInfo operation = sdk.GetBasicApi().UserProfile.GetMyProfileInfoOp
        .Build(sdk.Namespace);

    // then
    UserProfilePrivateInfo? response = sdk.GetBasicApi().UserProfile.GetMyProfileInfo(operation);

    */

    Console.WriteLine(response.UserId); // Success response
}
catch (HttpResponseException e)
{
    Console.WriteLine(e.Message);
}

Logout

bool logout = sdk.Logout();
if (!logout)
{
    // Logout failed
}

Enable HTTP Logging

To enable http logging feature, build the sdk with EnableLog().

using AccelByte.Sdk.Core;

IAccelByteSdk sdk = AccelByteSdk.Builder
    .UseDefaultHttpClient()
    .UseDefaultConfigRepository()
    .UseDefaultTokenRepository()
    .EnableLog()
    .Build();

HTTP Retry Example

If retry feature is required, instantiate the sdk with ReliableHttpClient object.

//Add core namespace
using AccelByte.Sdk.Core;
using AccelByte.Sdk.Core.Net.Http;

//Using default retry policy 
HttpClientPolicy policy = HttpClientPolicy.Default;

IAccelByteSdk sdk = AccelByteSdk.Builder
    .SetHttpClient(ReliableHttpClient.Builder
        .SetDefaultPolicy(policy)                    
        .Build())    
    .UseDefaultConfigRepository()
    .UseDefaultTokenRepository()
    .Build();

For HttpClientPolicy properties, refer to this code.

Automatically Refresh Access Token

To enable automatic access token refresh, include AccelByte.Sdk.Feature.AutoRefreshToken and instantiate the sdk with following code.

//Add core namespace
using AccelByte.Sdk.Core;

//Add feature namespace
using AccelByte.Sdk.Feature.AutoRefreshToken;

IAccelByteSdk sdk = AccelByteSdk.Builder
    .UseDefaultHttpClient()
    // Using DefaultConfigRepository, make sure the required environment variables are set
    .UseDefaultConfigRepository()
    // Credential repository is required for auto refresh token to works
    .UseDefaultCredentialRepository()
    // call this to enable the feature
    .UseAutoTokenRefresh()
    .Build();

Then when login, use the extension method provided.

using AccelByte.Sdk.Core;
using AccelByte.Sdk.Feature.AutoRefreshToken;

//pass true to the third parameter
bool login = sdk.LoginUser("myUsername", "myPassword", true);
if (!login)
{
    Console.WriteLine("Login failed");
}

//Or simply pass true to the first parameter if username and password are stored and retrieved by credential repository
bool login = sdk.LoginUser(true);
if (!login)
{
    Console.WriteLine("Login failed");
}

Alternative to automatic access token refresh is scheduled access token refresh. Scheduled access token refresh is using a timer that periodically refresh the access token. To enable it, instead of using .UseAutoTokenRefresh(), use .UseScheduledTokenRefresh() while instantiate the sdk.

//Add core namespace
using AccelByte.Sdk.Core;

//Add feature namespace
using AccelByte.Sdk.Feature.AutoRefreshToken;

IAccelByteSdk sdk = AccelByteSdk.Builder
    .UseDefaultHttpClient()
    // Using DefaultConfigRepository, make sure the required environment variables are set
    .UseDefaultConfigRepository()
    // Credential repository is required for auto refresh token to works
    .UseDefaultCredentialRepository()
    // call this to enable the scheduled access token refresh
    .UseScheduledTokenRefresh()
    .Build();

This feature will try to update any open WebSocket connection when refresh action triggered by AutoTokenRefresh or ScheduledTokenRefresh.

NOTE: Do not use .UseAutoTokenRefresh() together with .UseScheduledTokenRefresh(). It will introduce unnecessary overhead and possibility of unexpected behaviour.

Token Validation

To use token validation, add AccelByte.Sdk.Authentication package and instantiate the sdk with following code.

//Add core namespace
using AccelByte.Sdk.Core;

IAccelByteSdk sdk = AccelByteSdk.Builder
    .UseDefaultHttpClient()
    // Using DefaultConfigRepository, make sure the required environment variables are set
    .UseDefaultConfigRepository()
    // Credential repository is required for auto refresh token to works
    .UseDefaultCredentialRepository()
    // call this to enable the feature
    .UseDefaultTokenValidator()    
    .Build();

Use following method to validate access token.

bool isValid = sdk.ValidateToken(accessTokenStr);

To validate permission and action, use following method.

bool isValid = sdk.ValidateToken(accessTokenStr, permissionStr, actionInt);

To validate permission and action with specified namespace and/or userid, use following method.

bool isValid = sdk.ValidateToken(accessTokenStr, permissionStr, actionInt, namespaceId, userId);

Note: To validate permission from user token, you need to instantiate the SDK with OAuth Client that has ADMIN:ROLE [READ] permission assigned to it.

Local Token Validation

Enable this feature to use local token validation instead of default token validation. To enable it, add AccelByte.Sdk.Feature.LocalTokenValidation package, include AccelByte.Sdk.Feature.LocalTokenValidation namespace and then instantiate the sdk with following code.

//Add core namespace
using AccelByte.Sdk.Core;

//Add feature namespace
using AccelByte.Sdk.Feature.LocalTokenValidation;

IAccelByteSdk sdk = AccelByteSdk.Builder
    .UseDefaultHttpClient()
    // Using DefaultConfigRepository, make sure the required environment variables are set
    .UseDefaultConfigRepository()
    // Credential repository is required for auto refresh token to works
    .UseDefaultCredentialRepository()
    // call this to enable the feature
    .UseLocalTokenValidator()
    // call this to enable auto refresh for token revocation list
    .UseAutoRefreshForTokenRevocationList()
    // call this to enable auto cache clear for token validator
    .UseTokenValidatorAutoClearCache()
    .Build();

Then use the usual ValidateToken methods.

If you only want to parse the access token.

var payload = sdk.ParseAccessToken(accessTokenStr, false);

Or, you want to validate the token first before parse it.

var payload = sdk.ParseAccessToken('<access token>', true);
//payload will be null if the access token is invalid.

Permission and namespace context cache can be cleared manually or automatically with set interval.

  • To use it manually, call sdk.Configuration.TokenValidator.InvalidateCache().
  • to enable auto clear, instantiate the sdk with UseTokenValidatorAutoClearCache(<interval in seconds>) method.

Operation with Generic Response

C# Extend SDK enable overloaded ParseOperation method with generic data type that applies to almost all operations with response model which has one or more object data type in it. For example:

using AccelByte.Sdk.Api.Cloudsave.Model;
using AccelByte.Sdk.Api.Cloudsave.Operation;

GameRecordExample myGameRecord = new GameRecordExample()
{
    MyStatus = "ALIVE",
    Location = "MOUNTAIN",
    Character = new GameRecordExample.CharacterClass()
    {
        Name = "Character",
        Strength = 10,
        Agility = 15,
        Intelligence = 20
    }
};

ModelsGameRecordResponse<GameRecordExample>? response = sdk.GetCloudsaveApi().PublicGameRecord.PostGameRecordHandlerV1Op
    .Execute<GameRecordExample>(myGameRecord, "test_record", sdk.Namespace);

The list of which endpoints that support it can be found in here

FlightID

C# Extend SDK enable support for FlightID transmission during Http request. By default, new flight id will be generated when the sdk is loaded. There will be some case that this default value need to be updated with new value.

  • To update default flight id globally, use following code:

    AccelByteConfig.UpdateDefaultFlightId("<new flight id value>");

    This will update the default flight id, and will be used by newly created sdk object (won't affect existing sdk object created before this code get executed).

  • To update flight id value in sdk object, use following code:

    sdk.UpdateFlightId("<new flight id value>");

    This will update the flight id value stored inside the sdk object. Will be used for all operations executed by the sdk object.

  • To update flight id value for specific operation, use UpdateFlightId method when building the operation object.

    // Make a call to getMyProfileInfo endpoint
    UserProfilePrivateInfo? response = sdk.Basic.UserProfile.GetMyProfileInfoOp
        .UpdateFlightId("<new flight id value>")
        .Execute(sdk.Namespace);

Web Socket Service

C# Extend SDK is able to connect to Lobby Web Socket Service. Following code demonstrate on how to use it.

using AccelByte.Sdk.Core;
using AccelByte.Sdk.Api.Lobby;

var sdk = AccelByteSdk.Builder
    .UseDefaultHttpClient()
    .UseDefaultConfigRepository()
    .Build();

// do login first

var lobbyWs = new LobbyService(sdk.Configuration);

//start connect
await lobbyWs.Connect(false);

//listen to message, this will block the execution
await lobbyWs.Listen();

//disconnect
await lobbyWs.Disconnect();

By default, web socket service is allowed to reconnect when not normal closure is received. To disable it, set AllowReconnect to false.

lobbyWs.AllowReconnect = false;

To handle message, register the event on which message type. For example:

lobbyWs.OnFriendsStatusResponse = (data) =>
{

};

In some cases, it is probably desired to handle all incoming message in single handler. To do this, set RedirectAllReceivedMessagesToMessageReceivedEvent to true and register an action to OnMessageReceived.

lobbyWs.RedirectAllReceivedMessagesToMessageReceivedEvent = true;
lobbyWs.OnMessageReceived = (message) =>
{
    
};

Migrate from Monolithic Version

See this migration info.

Documentation

For documentation about AccelByte Gaming Services and SDK, see docs.accelbyte.io