public static async Task <GameState> InitializeAsync(PlayFabAuthenticationContext context, string SharedGroupId)
        {
            var sharedGroupData = await SharedGroupDataUtil.GetAsync(context, SharedGroupId);

            sharedGroupData.GameState = new GameState
            {
                BoardState      = new int[9],
                CurrentPlayerId = sharedGroupData.Match.PlayerOneId,
                Winner          = (int)OccupantType.NONE
            };

            await SharedGroupDataUtil.UpdateAsync(context, sharedGroupData);

            return(sharedGroupData.GameState);
        }
        public static async Task <TicTacToeSharedGroupData> AddMember(PlayFabAuthenticationContext context, string sharedGroupId, string playerId)
        {
            var sharedGroup = await SharedGroupDataUtil.GetAsync(context, sharedGroupId);

            if (!string.IsNullOrWhiteSpace(sharedGroup.Match.PlayerOneId) && !string.IsNullOrWhiteSpace(sharedGroup.Match.PlayerTwoId))
            {
                throw new Exception("Match is full");
            }

            if (string.Compare(sharedGroup.Match.PlayerOneId, playerId, true) == 0)
            {
                throw new Exception("This player is already the player one");
            }

            sharedGroup.Match.PlayerTwoId = playerId;

            return(await SharedGroupDataUtil.UpdateAsync(context, sharedGroup));
        }
Exemple #3
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            var serverSettings = new PlayFab.PlayFabApiSettings()
            {
                TitleId            = Environment.GetEnvironmentVariable("PlayFab.TitleId", EnvironmentVariableTarget.Process),
                DeveloperSecretKey = Environment.GetEnvironmentVariable("PlayFab.TitleSecret", EnvironmentVariableTarget.Process),
            };

            var authAPI       = new PlayFabAuthenticationInstanceAPI(serverSettings);
            var titleResponse = await authAPI.GetEntityTokenAsync(new PlayFab.AuthenticationModels.GetEntityTokenRequest());

            var title      = titleResponse.Result.Entity;
            var titleToken = titleResponse.Result.EntityToken;

            log.LogInformation($"Title is  : {title.Id}");
            log.LogInformation($"Token is  : {titleToken}");

            var request = new PlayFab.GroupsModels.ListMembershipRequest()
            {
                Entity = new PlayFab.GroupsModels.EntityKey
                {
                    Id   = "7B66887BFE1A76CE",
                    Type = "title_player_account",
                }
            };

            log.LogInformation($"Request is  : {JsonConvert.SerializeObject(request)}");

            var titleAuthContext = new PlayFabAuthenticationContext();

            titleAuthContext.EntityToken = titleToken;

            var api    = new PlayFabGroupsInstanceAPI(serverSettings, titleAuthContext);
            var result = await api.ListMembershipAsync(request);

            //var result = await PlayFabGroupsAPI.ListMembershipAsync(request);

            var groups = result.Result.Groups;
            var msg    = $"group is {JsonConvert.SerializeObject(groups)}\n";

            return((ActionResult) new OkObjectResult($"{msg}"));
        }
Exemple #4
0
        public void ApiInstanceLogin(UUnitTestContext testContext)
        {
            PlayFabApiSettings settings = new PlayFabApiSettings();

            settings.TitleId = PlayFabSettings.TitleId;

            PlayFabAuthenticationContext context = new PlayFabAuthenticationContext();

            context.DeveloperSecretKey = testTitleData.developerSecretKey;

            var loginRequest1 = new LoginWithServerCustomIdRequest()
            {
                CreateAccount         = true,
                ServerCustomId        = "test_Instance1",
                AuthenticationContext = context
            };

            var loginRequest2 = new LoginWithServerCustomIdRequest()
            {
                CreateAccount         = true,
                ServerCustomId        = "test_Instance2",
                AuthenticationContext = context
            };

            try
            {
                PlayFabServerInstanceAPI serverInstance1 = new PlayFabServerInstanceAPI(settings, context);
                PlayFabServerInstanceAPI serverInstance2 = new PlayFabServerInstanceAPI(settings, context);

                var result1 = serverInstance1.LoginWithServerCustomIdAsync(loginRequest1, null, testTitleData.extraHeaders).Result;
                var result2 = serverInstance2.LoginWithServerCustomIdAsync(loginRequest2, null, testTitleData.extraHeaders).Result;

                testContext.NotNull(result1.Result, "serverInstace1 login failed");
                testContext.NotNull(result2.Result, "serverInstance2 login failed");
                testContext.IsNull(result1.Error, "serverInstance1 got error: " + result1.Error?.ErrorMessage ?? string.Empty);
                testContext.IsNull(result2.Error, "serverInstance2 got error: " + result2.Error?.ErrorMessage ?? string.Empty);
                testContext.EndTest(UUnitFinishState.PASSED, null);
            }
            catch (Exception)
            {
                testContext.Fail("Multi Intance Server api can not be created");
            }
        }
        public static async Task <TicTacToeSharedGroupData> GetAsync(PlayFabAuthenticationContext context, string groupId)
        {
            var request = new GetSharedGroupDataRequest
            {
                AuthenticationContext = context,
                SharedGroupId         = groupId
            };

            var response = await GetPlayFabServerInstanceAPI().GetSharedGroupDataAsync(request);

            var resultData = response?.Result?.Data ?? null;

            if (resultData == null)
            {
                return(null);
            }

            return(ParseFromSharedGroupData <TicTacToeSharedGroupData>(resultData, Constants.SHARED_GROUP_DATA_DICTIONARY_ENTRY_NAME));
        }
Exemple #6
0
        public void MultipleInstanceWithDifferentSettings(UUnitTestContext testContext)
        {
            PlayFabApiSettings settings = new PlayFabApiSettings();

            settings.ProductionEnvironmentUrl = "https://test1.playfabapi.com";
            settings.TitleId = "test1";

            PlayFabApiSettings settings2 = new PlayFabApiSettings();

            settings2.ProductionEnvironmentUrl = "https://test2.playfabapi.com";
            settings2.TitleId = "test2";

            PlayFabAuthenticationContext context = new PlayFabAuthenticationContext();

            context.DeveloperSecretKey = "key1";

            PlayFabAuthenticationContext context2 = new PlayFabAuthenticationContext();

            context2.DeveloperSecretKey = "key2";

            try
            {
                PlayFabServerInstanceAPI serverInstance1 = new PlayFabServerInstanceAPI(settings, context);
                PlayFabServerInstanceAPI serverInstance2 = new PlayFabServerInstanceAPI(settings2, context2);

                testContext.StringEquals("test1", serverInstance1.GetSettings().TitleId, "MultipleInstanceWithDifferentSettings can not be completed");
                testContext.StringEquals("https://test1.playfabapi.com", serverInstance1.GetSettings().ProductionEnvironmentUrl, "MultipleInstanceWithDifferentSettings can not be completed");
                testContext.StringEquals("key1", serverInstance1.GetAuthenticationContext().DeveloperSecretKey, "MultipleInstanceWithDifferentSettings can not be completed");

                testContext.StringEquals("test2", serverInstance2.GetSettings().TitleId, "MultipleInstanceWithDifferentSettings can not be completed");
                testContext.StringEquals("https://test2.playfabapi.com", serverInstance2.GetSettings().ProductionEnvironmentUrl, "MultipleInstanceWithDifferentSettings can not be completed");
                testContext.StringEquals("key2", serverInstance2.GetAuthenticationContext().DeveloperSecretKey, "MultipleInstanceWithDifferentSettings can not be completed");
                testContext.EndTest(UUnitFinishState.PASSED, null);
            }
            catch (Exception)
            {
                testContext.Fail("Multi Intance Server api can not be created");
            }
        }
Exemple #7
0
        public static async Task <TicTacToeSharedGroupData> CreateMatchLobby(PlayFabAuthenticationContext authenticationContext, string sharedGroupId, string playerOne, IAsyncCollector <MatchLobby> matchlobbyCollection)
        {
            var sharedGroupData = new TicTacToeSharedGroupData
            {
                SharedGroupId = sharedGroupId,
                Match         = new Match
                {
                    PlayerOneId = playerOne
                },
                MatchLobby = new MatchLobby
                {
                    MatchLobbyId        = sharedGroupId,
                    CurrentAvailability = 1
                }
            };

            var sharedGroupDataUpdated = await SharedGroupDataUtil.UpdateAsync(authenticationContext, sharedGroupData);

            await matchlobbyCollection.AddAsync(sharedGroupDataUpdated.MatchLobby);

            return(sharedGroupDataUpdated);
        }
Exemple #8
0
        public void CreateMultipleServerInstance(UUnitTestContext testContext)
        {
            PlayFabApiSettings settings = new PlayFabApiSettings();

            settings.TitleId = PlayFabSettings.TitleId;

            PlayFabAuthenticationContext context = new PlayFabAuthenticationContext();

            context.DeveloperSecretKey = testTitleData.developerSecretKey;

            try
            {
                PlayFabServerInstanceAPI serverInstanceWithoutAnyParameter    = new PlayFabServerInstanceAPI();
                PlayFabServerInstanceAPI serverInstanceWithSettings           = new PlayFabServerInstanceAPI(settings);
                PlayFabServerInstanceAPI serverInstanceWithContext            = new PlayFabServerInstanceAPI(context);
                PlayFabServerInstanceAPI serverInstanceWithSameParameter      = new PlayFabServerInstanceAPI(context);
                PlayFabServerInstanceAPI serverInstanceWithSettingsAndContext = new PlayFabServerInstanceAPI(settings, context);
                testContext.EndTest(UUnitFinishState.PASSED, null);
            }
            catch (Exception)
            {
                testContext.Fail("Multi Intance Server api can not be created");
            }
        }
        public void GetPFTitleEntityToken()
        {
            if (_tokenRefreshTime < DateTime.UtcNow)
            {
                GetEntityTokenRequest request = new GetEntityTokenRequest();

                // Using reflection here since the property has an internal setter. Clearing it is essential, to force,
                // the SDK to use the secret key (and not send a potentially expired token). If the SDK behavior changes to use the secret key (if available),
                // then all this code can be removed
                FieldInfo fieldInfo = typeof(PlayFabSettings).GetField("staticPlayer", BindingFlags.Static | BindingFlags.NonPublic);

                PlayFabAuthenticationContext context = (PlayFabAuthenticationContext)fieldInfo.GetValue(null);

                fieldInfo = typeof(PlayFabAuthenticationContext).GetField("EntityToken", BindingFlags.Instance | BindingFlags.Public);
                fieldInfo.SetValue(context, null);

                PlayFabSettings.staticSettings.TitleId            = TitleId;
                PlayFabSettings.staticSettings.DeveloperSecretKey = _secretKey;

                // The SDK sets the entity token as part of response evaluation.
                PlayFabAuthenticationAPI.GetEntityTokenAsync(request).Wait();
                _tokenRefreshTime = DateTime.UtcNow.AddHours(TokenRefreshIntervalInHours);
            }
        }
Exemple #10
0
    /// <summary>
    /// ログイン実行
    /// </summary>
    private void Login()
    {
        // 既にログイン済みだったのでIDを保存して終了
        if (PlayFabClientAPI.IsClientLoggedIn())
        {
            Debug.Log("PlayFabへログイン済み:IDをPlayFabLoginクラスへ保存します");
            PlayFabAuthenticationContext player = PlayFabSettings.staticPlayer;
            _playfabID = player.PlayFabId;
            return;
        }

        // 通信待ちでなかったら通信開始
        if (!waitConnect.GetWait(gameObject.name))
        {
            customID = LoadCustomID();
            var request = new LoginWithCustomIDRequest {
                CustomId = customID, CreateAccount = shouldCreateAccount
            };
            PlayFabClientAPI.LoginWithCustomID(request, OnLoginSuccess, OnLoginFailure);

            // 通信待ちに設定する
            waitConnect.AddWait(gameObject.name);
        }
    }
        public static async Task <dynamic> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation($"{nameof(GetCharacterInventoryFunc)} C# HTTP trigger function processed a request.");
            var serverSettings = new PlayFab.PlayFabApiSettings()
            {
                TitleId            = Environment.GetEnvironmentVariable("PlayFab.TitleId", EnvironmentVariableTarget.Process),
                DeveloperSecretKey = Environment.GetEnvironmentVariable("PlayFab.TitleSecret", EnvironmentVariableTarget.Process),
            };

            var authAPI       = new PlayFabAuthenticationInstanceAPI(serverSettings);
            var titleResponse = await authAPI.GetEntityTokenAsync(new PlayFab.AuthenticationModels.GetEntityTokenRequest());

            var title      = titleResponse.Result.Entity;
            var titleToken = titleResponse.Result.EntityToken;

            var titleAuthContext = new PlayFabAuthenticationContext();

            titleAuthContext.EntityToken = titleToken;

            FunctionExecutionContext <dynamic> context = JsonConvert.DeserializeObject <FunctionExecutionContext <dynamic> >(await req.ReadAsStringAsync());
            dynamic args    = context.FunctionArgument;
            var     message = $"Args: {args}";

            log.LogInformation(message);

            var request = new GetCharacterInventoryRequest {
                PlayFabId   = args["playfabId"] ?? context.CallerEntityProfile.Lineage.MasterPlayerAccountId,
                CharacterId = args["characterId"]
            };

            var serverApi = new PlayFabServerInstanceAPI(serverSettings, titleAuthContext);

            return(await serverApi.GetCharacterInventoryAsync(request));
        }
Exemple #12
0
 protected internal static void MakeApiCallWithFullUri <TResult>(string fullUri,
                                                                 PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback,
                                                                 Action <PlayFabError> errorCallback, object customData = null, Dictionary <string, string> extraHeaders = null, PlayFabAuthenticationContext authenticationContext = null, PlayFabApiSettings apiSettings = null, IPlayFabInstanceApi instanceApi = null)
     where TResult : PlayFabResultCommon
 {
     apiSettings = apiSettings ?? PlayFabSettings.staticSettings;
     // This will not be called if environment file does not exist or does not contain property the debugging URI
     _MakeApiCall(null, fullUri, request, authType, resultCallback, errorCallback, customData, extraHeaders, false, authenticationContext, apiSettings, instanceApi);
 }
Exemple #13
0
        protected internal static Task <TResult> MakeApiCallAsync <TResult>(string apiEndpoint,
                                                                            PlayFabRequestCommon request, AuthType authType, object customData = null, Dictionary <string, string> extraHeaders = null, PlayFabAuthenticationContext authenticationContext = null, PlayFabApiSettings apiSettings = null, IPlayFabInstanceApi instanceApi = null)
            where TResult : PlayFabResultCommon
        {
            TaskCompletionSource <TResult> tcs = new TaskCompletionSource <TResult>();

            apiSettings = apiSettings ?? PlayFabSettings.staticSettings;
            var fullUrl = apiSettings.GetFullUrl(apiEndpoint, apiSettings.RequestGetParams);

            _MakeApiCall(apiEndpoint, fullUrl, request, authType, (TResult a) => tcs.SetResult(a), error =>
            {
                Debug.LogError(error.GenerateErrorReport());
                tcs.SetException(error);
            }, customData, extraHeaders, false, authenticationContext, apiSettings, instanceApi);
            return(tcs.Task);
        }
Exemple #14
0
        protected internal static void MakeApiCall <TResult>(string apiEndpoint,
                                                             PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback,
                                                             Action <PlayFabError> errorCallback, object customData = null, Dictionary <string, string> extraHeaders = null, PlayFabAuthenticationContext authenticationContext = null, PlayFabApiSettings apiSettings = null, IPlayFabInstanceApi instanceApi = null)
            where TResult : PlayFabResultCommon
        {
            apiSettings = apiSettings ?? PlayFabSettings.staticSettings;
            var fullUrl = apiSettings.GetFullUrl(apiEndpoint, apiSettings.RequestGetParams);

            _MakeApiCall(apiEndpoint, fullUrl, request, authType, resultCallback, errorCallback, customData, extraHeaders, false, authenticationContext, apiSettings, instanceApi);
        }
Exemple #15
0
        public static async Task DeletePlayFabMatchLobbyAsync(PlayFabApiSettings apiSettings, PlayFabAuthenticationContext authenticationContext, string matchlobbyId)
        {
            var groupApi = new PlayFabGroupsInstanceAPI(apiSettings, authenticationContext);
            var request  = new DeleteGroupRequest {
                Group = CreateEntityKey(matchlobbyId)
            };

            await groupApi.DeleteGroupAsync(request);
        }
 /// <summary>
 /// Instantiates a new instance of the SimpleSignalRClient class.
 /// </summary>
 /// <param name="settings">PlayFab API Settings to be used by this client when calling PlayFab APIs.</param>
 /// <param name="authContext">The auth context to be used by this client when calling PlayFab APIs.</param>
 public SimpleSignalRClient(PlayFabApiSettings settings, PlayFabAuthenticationContext authContext)
 {
     cloudScriptAPI = new PlayFabCloudScriptInstanceAPI(settings, authContext);
 }
        public static async Task <GameState> GetAsync(PlayFabAuthenticationContext context, string SharedGroupId)
        {
            var sharedGroupData = await SharedGroupDataUtil.GetAsync(context, SharedGroupId);

            return(sharedGroupData.GameState);
        }
 private void OnLoginSuccess(LoginResult result)
 {
     PlayFabId            = result.PlayFabId;
     playfabAuthenContext = result.AuthenticationContext;
     Debug.Log("Welcome");
 }
        public static async Task <TicTacToeState> GetCurrentGameState(string playFabId, PlayFabApiSettings apiSettings, PlayFabAuthenticationContext authenticationContext)
        {
            var request = new GetUserDataRequest()
            {
                PlayFabId = playFabId,
                Keys      = new List <string>()
                {
                    Constants.GAME_CURRENT_STATE_KEY
                }
            };

            var serverApi = new PlayFabServerInstanceAPI(apiSettings, authenticationContext);

            var result = await serverApi.GetUserDataAsync(request);

            if (result.Error != null)
            {
                throw new Exception($"An error occurred while fetching the current game state: Error: {result.Error.GenerateErrorReport()}");
            }

            var resultData = result.Result.Data;

            // Current state found
            if (resultData.Count > 0 && resultData.TryGetValue(Constants.GAME_CURRENT_STATE_KEY, out var currentGameStateRecord))
            {
                return(PlayFabSimpleJson.DeserializeObject <TicTacToeState>(currentGameStateRecord.Value));
            }
            // Current game record does not exist and so must be created
            else
            {
                var newState = new TicTacToeState()
                {
                    Data = new int[9]
                };
                await UpdateCurrentGameState(newState, playFabId, apiSettings, authenticationContext);

                return(newState);
            }
        }
        public static async Task UpdateCurrentGameState(TicTacToeState state, string playFabId, PlayFabApiSettings apiSettings, PlayFabAuthenticationContext authenticationContext)
        {
            var serializedNewGameState = PlayFabSimpleJson.SerializeObject(state);

            var request = new UpdateUserDataRequest()
            {
                PlayFabId = playFabId,
                Data      = new Dictionary <string, string>()
                {
                    { Constants.GAME_CURRENT_STATE_KEY, serializedNewGameState }
                }
            };

            var serverApi = new PlayFabServerInstanceAPI(apiSettings, authenticationContext);

            var result = await serverApi.UpdateUserDataAsync(request);

            if (result.Error != null)
            {
                throw new Exception($"An error occured while creating a new game state: {result.Error.GenerateErrorReport()}");
            }
        }
        public static async Task AddGameStateHistory(TicTacToeState gameState, string playFabId, PlayFabApiSettings apiSettings, PlayFabAuthenticationContext authenticationContext)
        {
            var gamesPlayed = await GameDataUtil.GetGamesPlayed(playFabId, apiSettings, authenticationContext);

            var key = $"{Constants.GAME_STATE_KEY}_{gamesPlayed + 1}";

            var serializedGameState = PlayFabSimpleJson.SerializeObject(gameState);

            var request = new UpdateUserDataRequest()
            {
                PlayFabId = playFabId,
                Data      = new Dictionary <string, string>()
                {
                    { key, serializedGameState }
                }
            };

            var serverApi = new PlayFabServerInstanceAPI(apiSettings, authenticationContext);

            var result = await serverApi.UpdateUserDataAsync(request);

            if (result.Error != null)
            {
                throw new Exception($"An error occured while updating the game state: Error: {result.Error.GenerateErrorReport()}");
            }

            await GameDataUtil.SetGamesPlayed(gamesPlayed + 1, playFabId, apiSettings, authenticationContext);
        }
Exemple #22
0
        public void ParallelRequest(UUnitTestContext testContext)
        {
            List <Task> tasks = new List <Task>();

            PlayFabApiSettings settings = new PlayFabApiSettings();

            settings.TitleId = PlayFabSettings.TitleId;

            PlayFabAuthenticationContext context = new PlayFabAuthenticationContext();

            context.DeveloperSecretKey = testTitleData.developerSecretKey;

            PlayFabAuthenticationContext context2 = new PlayFabAuthenticationContext();

            context2.DeveloperSecretKey = "GETERROR";

            PlayFabAuthenticationContext context3 = new PlayFabAuthenticationContext();

            context3.DeveloperSecretKey = testTitleData.developerSecretKey;

            PlayFabAuthenticationContext context4 = new PlayFabAuthenticationContext();

            context4.DeveloperSecretKey = "TESTKEYERROR";

            PlayFabAuthenticationContext context5 = new PlayFabAuthenticationContext();

            context5.DeveloperSecretKey = "123421";


            PlayFabServerInstanceAPI serverInstance = new PlayFabServerInstanceAPI(settings, context);

            tasks.Add(serverInstance.GetAllSegmentsAsync(new GetAllSegmentsRequest()));

            PlayFabServerInstanceAPI serverInstance1 = new PlayFabServerInstanceAPI(settings, context);

            tasks.Add(serverInstance1.GetAllSegmentsAsync(new GetAllSegmentsRequest()));

            PlayFabServerInstanceAPI serverInstance2 = new PlayFabServerInstanceAPI(settings, context2);

            tasks.Add(serverInstance2.GetAllSegmentsAsync(new GetAllSegmentsRequest()));

            PlayFabServerInstanceAPI serverInstance3 = new PlayFabServerInstanceAPI(settings, context3);

            tasks.Add(serverInstance3.GetAllSegmentsAsync(new GetAllSegmentsRequest()));

            PlayFabServerInstanceAPI serverInstance4 = new PlayFabServerInstanceAPI(settings, context4);

            tasks.Add(serverInstance4.GetAllSegmentsAsync(new GetAllSegmentsRequest()));

            PlayFabServerInstanceAPI serverInstance5 = new PlayFabServerInstanceAPI(settings, context5);

            tasks.Add(serverInstance5.GetAllSegmentsAsync(new GetAllSegmentsRequest()));

            Task.WhenAll(tasks).ContinueWith(whenAll =>
            {
                if (!whenAll.IsCanceled && !whenAll.IsFaulted)
                {
                    testContext.EndTest(UUnitFinishState.PASSED, null);
                }
                else
                {
                    testContext.Fail("Parallel Requests failed " + whenAll.Exception.Flatten().Message);
                }
            });
        }
Exemple #23
0
        public static async Task <int> GetGamesPlayed(string playFabId, PlayFabApiSettings apiSettings, PlayFabAuthenticationContext authenticationContext)
        {
            var request = new GetUserDataRequest
            {
                PlayFabId = playFabId,
                Keys      = new List <string> {
                    Constants.GAMES_PLAYED_KEY
                }
            };

            var serverApi = new PlayFabServerInstanceAPI(apiSettings, authenticationContext);

            var result = await serverApi.GetUserDataAsync(request);

            if (result.Error != null)
            {
                throw new Exception($"An error occured while fetching the number of games played: Error: {result.Error.GenerateErrorReport()}");
            }

            var resultData = result.Result.Data;

            if (resultData.Count > 0 && resultData.TryGetValue(Constants.GAMES_PLAYED_KEY, out var gamesPlayedRecord))
            {
                return(int.Parse(gamesPlayedRecord.Value));
            }

            // Set the number of games played to be 0 since the record doesn't exist
            await SetGamesPlayed(0, playFabId, apiSettings, authenticationContext);

            return(0);
        }
Exemple #24
0
        /// <summary>
        /// Internal method for Make API Calls
        /// </summary>
        private static void _MakeApiCall <TResult>(string apiEndpoint, string fullUrl,
                                                   PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback,
                                                   Action <PlayFabError> errorCallback, object customData, Dictionary <string, string> extraHeaders, bool allowQueueing, PlayFabAuthenticationContext authenticationContext, PlayFabApiSettings apiSettings, IPlayFabInstanceApi instanceApi)
            where TResult : PlayFabResultCommon
        {
            InitializeHttp();
            SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre);

            var serializer   = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer);
            var reqContainer = new CallRequestContainer
            {
                ApiEndpoint    = apiEndpoint,
                FullUrl        = fullUrl,
                settings       = apiSettings,
                context        = authenticationContext,
                CustomData     = customData,
                Payload        = Encoding.UTF8.GetBytes(serializer.SerializeObject(request)),
                ApiRequest     = request,
                ErrorCallback  = errorCallback,
                RequestHeaders = extraHeaders ?? new Dictionary <string, string>(), // Use any headers provided by the customer
                instanceApi    = instanceApi
            };

            // Append any additional headers
            foreach (var pair in GlobalHeaderInjection)
            {
                if (!reqContainer.RequestHeaders.ContainsKey(pair.Key))
                {
                    reqContainer.RequestHeaders[pair.Key] = pair.Value;
                }
            }

#if PLAYFAB_REQUEST_TIMING
            reqContainer.Timing.StartTimeUtc = DateTime.UtcNow;
            reqContainer.Timing.ApiEndpoint  = apiEndpoint;
#endif

            // Add PlayFab Headers
            var transport = PluginManager.GetPlugin <ITransportPlugin>(PluginContract.PlayFab_Transport);
            reqContainer.RequestHeaders["X-ReportErrorAsSuccess"] = "true";                        // Makes processing PlayFab errors a little easier
            reqContainer.RequestHeaders["X-PlayFabSDK"]           = PlayFabSettings.VersionString; // Tell PlayFab which SDK this is
            switch (authType)
            {
#if ENABLE_PLAYFABSERVER_API || ENABLE_PLAYFABADMIN_API || UNITY_EDITOR
            case AuthType.DevSecretKey:
                if (apiSettings.DeveloperSecretKey == null)
                {
                    throw new PlayFabException(PlayFabExceptionCode.DeveloperKeyNotSet, "DeveloperSecretKey is not found in Request, Server Instance or PlayFabSettings");
                }
                reqContainer.RequestHeaders["X-SecretKey"] = apiSettings.DeveloperSecretKey; break;
#endif
#if !DISABLE_PLAYFABCLIENT_API
            case AuthType.LoginSession:
                if (authenticationContext != null)
                {
                    reqContainer.RequestHeaders["X-Authorization"] = authenticationContext.ClientSessionTicket;
                }
                break;
#endif
#if !DISABLE_PLAYFABENTITY_API
            case AuthType.EntityToken:
                if (authenticationContext != null)
                {
                    reqContainer.RequestHeaders["X-EntityToken"] = authenticationContext.EntityToken;
                }
                break;
#endif
            }

            // These closures preserve the TResult generic information in a way that's safe for all the devices
            reqContainer.DeserializeResultJson = () =>
            {
                reqContainer.ApiResult = serializer.DeserializeObject <TResult>(reqContainer.JsonResponse);
            };
            reqContainer.InvokeSuccessCallback = () =>
            {
                if (resultCallback != null)
                {
                    resultCallback((TResult)reqContainer.ApiResult);
                }
            };

            if (allowQueueing && _apiCallQueue != null)
            {
                for (var i = _apiCallQueue.Count - 1; i >= 0; i--)
                {
                    if (_apiCallQueue[i].ApiEndpoint == apiEndpoint)
                    {
                        _apiCallQueue.RemoveAt(i);
                    }
                }
                _apiCallQueue.Add(reqContainer);
            }
            else
            {
                transport.MakeApiCall(reqContainer);
            }
        }
 void loginSuccessCallback(LoginResult result)
 {
     Debug.Log("Login success!");
     authContext = result.AuthenticationContext;
 }
Exemple #26
0
        public static async Task <SetObjectsResponse> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] FunctionExecutionContext <TestObject> req,
            HttpRequest httpRequest,
            ILogger log)
        {
            string body = await httpRequest.ReadAsStringAsync();

            log.LogInformation($"HTTP POST Body: {body}");

            log.LogInformation($"callingEntityKey: {JsonConvert.SerializeObject(req.CallerEntityProfile.Entity)}");
            log.LogInformation($"currentEntity: {JsonConvert.SerializeObject(req.CallerEntityProfile)}");

            string    name = req.FunctionArgument.ObjectName;
            TestValue val  = req.FunctionArgument.ObjectValue;

            val.PlayerDetails.MapPosition = new[] { _random.NextDouble(), _random.NextDouble(), _random.NextDouble() };

            var titleSettings = new PlayFabApiSettings
            {
                TitleId      = req.TitleAuthenticationContext.Id,
                VerticalName = Settings.Cloud
            };

            var titleAuthContext = new PlayFabAuthenticationContext();

            titleAuthContext.EntityToken = req.TitleAuthenticationContext.EntityToken;

            var setObjectsRequest = new SetObjectsRequest
            {
                Entity = new DataModels.EntityKey
                {
                    Id   = req.CallerEntityProfile.Entity.Id,
                    Type = req.CallerEntityProfile.Entity.Type
                },
                Objects = new System.Collections.Generic.List <SetObject>
                {
                    new SetObject
                    {
                        DataObject = val,
                        ObjectName = name
                    }
                }
            };

            var       dataAPI = new PlayFabDataInstanceAPI(titleSettings, titleAuthContext);
            Stopwatch sw      = Stopwatch.StartNew();
            PlayFabResult <SetObjectsResponse> setObjectsResponse = await dataAPI.SetObjectsAsync(setObjectsRequest);

            sw.Stop();

            if (setObjectsResponse.Error != null)
            {
                throw new InvalidOperationException($"SetObjectsAsync failed: {setObjectsResponse.Error.GenerateErrorReport()}");
            }
            else
            {
                log.LogInformation($"SetObjectsAsync succeeded in {sw.ElapsedMilliseconds}ms");
                log.LogInformation($"SetObjectsAsync returned. ProfileVersion: {setObjectsResponse.Result.ProfileVersion}. NumResults: {setObjectsResponse.Result.SetResults.Count}");
                return(setObjectsResponse.Result);
            }
        }
Exemple #27
0
        public static async Task SetGamesPlayed(int gamesPlayed, string playFabId, PlayFabApiSettings apiSettings, PlayFabAuthenticationContext authenticationContext)
        {
            var request = new UpdateUserDataRequest
            {
                PlayFabId = playFabId,
                Data      = new Dictionary <string, string> {
                    { Constants.GAMES_PLAYED_KEY.ToString(), gamesPlayed.ToString() }
                }
            };

            var serverApi = new PlayFabServerInstanceAPI(apiSettings, authenticationContext);

            var result = await serverApi.UpdateUserDataAsync(request);

            if (result.Error != null)
            {
                throw new Exception($"An error occured while updating the number of games played: Error: {result.Error.GenerateErrorReport()}");
            }
        }