Esempio n. 1
0
        public void CheckWithNoSettings(UUnitTestContext testContext)
        {
            //It should work with static class only
            PlayFabServerInstanceAPI serverInstanceWithoutAnyParameter = new PlayFabServerInstanceAPI();

            serverInstanceWithoutAnyParameter.GetAllSegments(new GetAllSegmentsRequest(), PlayFabUUnitUtils.ApiActionWrapper <GetAllSegmentsResult>(testContext, CheckWithNoSettingsSuccessCallBack), PlayFabUUnitUtils.ApiActionWrapper <PlayFabError>(testContext, SharedErrorCallback), testContext);
        }
        public void MultipleInstanceWithDifferentSettings(UUnitTestContext testContext)
        {
            PlayFabApiSettings settings1 = new PlayFabApiSettings();

            settings1.ProductionEnvironmentUrl = "https://test1.playfabapi.com";
            settings1.TitleId            = "test1";
            settings1.DeveloperSecretKey = "key1";

            PlayFabApiSettings settings2 = new PlayFabApiSettings();

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

            PlayFabServerInstanceAPI serverInstance1 = new PlayFabServerInstanceAPI(settings1, null);
            PlayFabServerInstanceAPI serverInstance2 = new PlayFabServerInstanceAPI(settings2, null);

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

            testContext.StringEquals("test2", serverInstance2.apiSettings.TitleId, "MultipleInstanceWithDifferentSettings can not be completed");
            testContext.StringEquals("https://test2.playfabapi.com", serverInstance2.apiSettings.ProductionEnvironmentUrl, "MultipleInstanceWithDifferentSettings can not be completed");
            testContext.StringEquals("key2", serverInstance2.apiSettings.DeveloperSecretKey, "MultipleInstanceWithDifferentSettings can not be completed");
            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
Esempio n. 3
0
        public static async Task <dynamic> UnlockHighSkillContent(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            /* Create the function execution's context through the request */
            var context = await FunctionPlayerPlayStreamContext <dynamic> .Create(req);

            var args = context.FunctionArgument;

            var playerStatUpdatedEvent = PlayFabSimpleJson.DeserializeObject <dynamic>(context.PlayStreamEventEnvelope.EventData);

            var request = new UpdateUserInternalDataRequest
            {
                PlayFabId = context.CurrentPlayerId,
                Data      = new Dictionary <string, string>
                {
                    { "HighSkillContent", "true" },
                    { "XPAtHighSkillUnlock", playerStatUpdatedEvent["StatisticValue"].ToString() }
                }
            };

            /* Use the ApiSettings and AuthenticationContext provided to the function as context for making API calls. */
            var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

            /* Execute the Server API request */
            var updateUserDataResponse = await serverApi.UpdateUserInternalDataAsync(request);

            log.LogInformation($"Unlocked HighSkillContent for {context.PlayerProfile.DisplayName}");

            return(new
            {
                profile = context.PlayerProfile
            });
        }
Esempio n. 4
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);
        }
Esempio n. 5
0
        public void ApiInstanceLogin(UUnitTestContext testContext)
        {
            PlayFabApiSettings settings = new PlayFabApiSettings();

            settings.TitleId            = testTitleData.titleId;
            settings.DeveloperSecretKey = testTitleData.developerSecretKey;

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

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

            PlayFabServerInstanceAPI serverInstance1 = new PlayFabServerInstanceAPI(settings);
            PlayFabServerInstanceAPI serverInstance2 = new PlayFabServerInstanceAPI(settings);

            serverInstance1.LoginWithServerCustomId(loginRequest1, PlayFabUUnitUtils.ApiActionWrapper <ServerLoginResult>(testContext, OnInstanceLogin1), PlayFabUUnitUtils.ApiActionWrapper <PlayFabError>(testContext, SharedErrorCallback), testContext);
            serverInstance2.LoginWithServerCustomId(loginRequest2, PlayFabUUnitUtils.ApiActionWrapper <ServerLoginResult>(testContext, OnInstanceLogin2), PlayFabUUnitUtils.ApiActionWrapper <PlayFabError>(testContext, SharedErrorCallback), testContext);
        }
        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);
        }
Esempio n. 7
0
        public void CheckWithAuthContextAndWithoutAuthContext(UUnitTestContext testContext)
        {
            PlayFabSettings.DeveloperSecretKey = testTitleData.developerSecretKey;

            //IT will  use static developer key - Should has no error
            PlayFabServerInstanceAPI serverInstance1 = new PlayFabServerInstanceAPI();
            var result = serverInstance1.GetAllSegmentsAsync(new GetAllSegmentsRequest()).Result;

            PlayFabAuthenticationContext context = new PlayFabAuthenticationContext();

            context.DeveloperSecretKey = "WRONGKEYTOFAIL";

            //IT will  use context developer key - Should has error because of wrong key
            PlayFabServerInstanceAPI serverInstance2 = new PlayFabServerInstanceAPI(context);
            var result2 = serverInstance2.GetAllSegmentsAsync(new GetAllSegmentsRequest()).Result;

            try
            {
                testContext.NotNull(result.Result, "Server Instance1 result is null");
                testContext.IsNull(result.Error, "Server Instance1 result got error message : " + result.Error?.ErrorMessage ?? string.Empty);
                testContext.IsNull(result2.Result, "Server Instance2 result is not null");
                testContext.NotNull(result2.Error, "Server Instance2 got no error message");
                testContext.IntEquals(401, result2.Error.HttpCode, "Server Instance2 got wrong error");
                testContext.EndTest(UUnitFinishState.PASSED, null);
            }
            catch (Exception ex)
            {
                testContext.Fail("CheckWithAuthContextAndWithoutAuthContext failed : " + ex.Message);
            }
        }
Esempio n. 8
0
        public static async Task <dynamic> MakeApiCall(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            /* Create the function execution's context through the request */
            var context = await FunctionContext <dynamic> .Create(req);

            var args = context.FunctionArgument;

            /* Create the request object through the SDK models */
            var request = new UpdatePlayerStatisticsRequest
            {
                PlayFabId  = context.CurrentPlayerId,
                Statistics = new List <StatisticUpdate>
                {
                    new StatisticUpdate
                    {
                        StatisticName = "Level",
                        Value         = 2
                    }
                }
            };
            /* Use the ApiSettings and AuthenticationContext provided to the function as context for making API calls. */
            var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

            /* The PlayFabServerAPI SDK methods provide means of making HTTP request to the PlayFab Main Server without any
             * extra code needed to issue the HTTP requests. */
            return(await serverApi.UpdatePlayerStatisticsAsync(request));
        }
        public void CheckWithNoSettings(UUnitTestContext testContext)
        {
            PlayFabSettings.staticSettings.DeveloperSecretKey = testTitleData.developerSecretKey;

            //It should work with static class only
            PlayFabServerInstanceAPI serverInstanceWithoutAnyParameter = new PlayFabServerInstanceAPI();
            var getAllSegmentsTask = serverInstanceWithoutAnyParameter.GetAllSegmentsAsync(new GetAllSegmentsRequest());

            ContinueWithContext(getAllSegmentsTask, testContext, null, false, "Work with no settings failed", true);
        }
        public void CreateMultipleServerInstance(UUnitTestContext testContext)
        {
            PlayFabServerInstanceAPI serverInstanceWithoutAnyParameter    = new PlayFabServerInstanceAPI();
            PlayFabServerInstanceAPI serverInstanceWithSettings           = new PlayFabServerInstanceAPI(instanceSettings);
            PlayFabServerInstanceAPI serverInstanceWithContext            = new PlayFabServerInstanceAPI(instanceContext);
            PlayFabServerInstanceAPI serverInstanceWithSameParameter      = new PlayFabServerInstanceAPI(instanceContext);
            PlayFabServerInstanceAPI serverInstanceWithSettingsAndContext = new PlayFabServerInstanceAPI(instanceSettings, instanceContext);

            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
    // 指定したキーのユーザーデータを更新
    // key : ex) UserDataKey.userMonsterList
    // value : ex) new List<UserMonsterInfo>(){ }
    public static async Task UpdateUserDataAsync(FunctionExecutionContext <dynamic> context, Dictionary <UserDataKey, object> dict)
    {
        var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

        var data   = dict.ToDictionary(kvp => kvp.Key.ToString(), kvp => JsonConvert.SerializeObject(kvp.Value));
        var result = await serverApi.UpdateUserDataAsync(new UpdateUserDataRequest()
        {
            PlayFabId = context.CallerEntityProfile.Lineage.MasterPlayerAccountId,
            Data      = data,
        });
    }
        // ドロップテーブルから取得するアイテムを抽選
        private static async Task <string> EvaluateRandomResultTable(FunctionExecutionContext <dynamic> context, dynamic dropTableName)
        {
            var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

            var result = await serverApi.EvaluateRandomResultTableAsync(new EvaluateRandomResultTableRequest()
            {
                TableId = dropTableName
            });

            return(result.Result.ResultItemId);
        }
Esempio n. 13
0
        // インベントリカスタムデータを更新
        private static async Task UpdateUserInventoryCustomDataAsync(FunctionExecutionContext <dynamic> context, DevelopUpdateUserInventoryCustomDataApiRequest request)
        {
            var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

            var result = await serverApi.UpdateUserInventoryItemCustomDataAsync(new UpdateUserInventoryItemDataRequest()
            {
                PlayFabId      = context.CallerEntityProfile.Lineage.MasterPlayerAccountId,
                ItemInstanceId = request.itemInstanceId,
                Data           = request.data,
            });
        }
        // ドロップテーブルから取得するアイテムを抽選
        private static async Task <List <GrantedItemInstance> > GrantItemsToUserTask(FunctionExecutionContext <Dictionary <string, List <string> > > context, dynamic itemIdList)
        {
            var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

            var result = await serverApi.GrantItemsToUserAsync(new GrantItemsToUserRequest()
            {
                PlayFabId = context.CallerEntityProfile.Lineage.MasterPlayerAccountId,
                ItemIds   = itemIdList
            });

            return(result.Result.ItemGrantResults);
        }
    // 指定したモンスターのカスタムデータを更新
    public static async Task UpdateUserMonsterCustomDataAsync(FunctionExecutionContext <dynamic> context, string itemInstanceId, UserMonsterCustomData customData)
    {
        var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

        var customDataDict = UserDataUtil.GetCustomDataDict(customData);
        var result         = await serverApi.UpdateUserInventoryItemCustomDataAsync(new UpdateUserInventoryItemDataRequest()
        {
            PlayFabId      = context.CallerEntityProfile.Lineage.MasterPlayerAccountId,
            ItemInstanceId = itemInstanceId,
            Data           = customDataDict,
        });
    }
    // 指定したアイテムを消費します
    public static async Task <ConsumeItemResult> ConsumeItemAsync(FunctionExecutionContext <dynamic> context, string itemInstanceId, int consumeCount)
    {
        var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

        var result = await serverApi.ConsumeItemAsync(new ConsumeItemRequest()
        {
            PlayFabId      = context.CallerEntityProfile.Lineage.MasterPlayerAccountId,
            ItemInstanceId = itemInstanceId,
            ConsumeCount   = consumeCount,
        });

        return(result.Result);
    }
    // ユーザーインベントリ情報を取得する
    public static async Task <UserInventoryInfo> GetUserInventoryAsync(FunctionExecutionContext <dynamic> context)
    {
        var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

        var result = await serverApi.GetUserInventoryAsync(new GetUserInventoryRequest()
        {
            PlayFabId = context.CallerEntityProfile.Lineage.MasterPlayerAccountId,
        });

        var userInventory = UserDataUtil.GetUserInventory(result.Result);

        return(userInventory);
    }
    // ユーザーデータを取得する
    public static async Task <UserDataInfo> GetUserDataAsync(FunctionExecutionContext <dynamic> context)
    {
        var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

        var result = await serverApi.GetUserDataAsync(new GetUserDataRequest()
        {
            PlayFabId = context.CallerEntityProfile.Lineage.MasterPlayerAccountId,
        });

        // ユーザーデータのパラム名とそのデータのJsonの辞書にしてユーザーデータを取得
        var userData = UserDataUtil.GetUserData(result.Result.Data);

        return(userData);
    }
Esempio n. 19
0
        public static async Task <dynamic> LevelCompleted(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            /* Create the function execution's context through the request */
            var context = await FunctionContext <dynamic> .Create(req);

            var args = context.FunctionArgument;

            var level          = args["levelName"];
            var monstersKilled = (int)args["monstersKilled"];

            var updateUserInternalDataRequest = new UpdateUserInternalDataRequest
            {
                PlayFabId = context.CurrentPlayerId,
                Data      = new Dictionary <string, string>
                {
                    { "lastLevelCompleted", level }
                }
            };

            /* Use the ApiSettings and AuthenticationContext provided to the function as context for making API calls. */
            var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);
            /* Execute the Server API request */
            var updateUserDataResult = await serverApi.UpdateUserInternalDataAsync(updateUserInternalDataRequest);

            log.LogDebug($"Set lastLevelCompleted for player {context.CurrentPlayerId} to {level}");

            var updateStatRequest = new UpdatePlayerStatisticsRequest
            {
                PlayFabId  = context.CurrentPlayerId,
                Statistics = new List <StatisticUpdate>
                {
                    new StatisticUpdate
                    {
                        StatisticName = "level_monster_kills",
                        Value         = monstersKilled
                    }
                }
            };

            /* Execute the server API request */
            var updateStatResult = await serverApi.UpdatePlayerStatisticsAsync(updateStatRequest);

            log.LogDebug($"Updated level_monster_kills stat for player {context.CurrentPlayerId} to {monstersKilled}");

            return(new
            {
                updateStatResult.Result
            });
        }
Esempio n. 20
0
        public void CreateMultipleServerInstance(UUnitTestContext testContext)
        {
            PlayFabApiSettings settings = new PlayFabApiSettings();

            settings.TitleId            = testTitleData.titleId;
            settings.DeveloperSecretKey = testTitleData.developerSecretKey;

            var instance1 = new PlayFabServerInstanceAPI();
            var instance2 = new PlayFabServerInstanceAPI(settings);

            instance1.ForgetAllCredentials();
            instance2.ForgetAllCredentials();

            testContext.EndTest(UUnitFinishState.PASSED, null);
        }
Esempio n. 21
0
        public void CheckWithAuthContextAndWithoutAuthContext(UUnitTestContext testContext)
        {
            //IT will  use static developer key - Should has no error
            PlayFabServerInstanceAPI serverInstance1 = new PlayFabServerInstanceAPI();

            serverInstance1.GetAllSegments(new GetAllSegmentsRequest(), PlayFabUUnitUtils.ApiActionWrapper <GetAllSegmentsResult>(testContext, CheckWithAuthContextAndWithoutAuthContextSuccessCallBack), PlayFabUUnitUtils.ApiActionWrapper <PlayFabError>(testContext, SharedErrorCallback), testContext);

            var apiSettings = new PlayFabApiSettings();

            apiSettings.DeveloperSecretKey = "WRONGKEYTOFAIL";

            //IT will  use context developer key - Should has error because of wrong key
            PlayFabServerInstanceAPI serverInstance2 = new PlayFabServerInstanceAPI(apiSettings);

            serverInstance2.GetAllSegments(new GetAllSegmentsRequest(), PlayFabUUnitUtils.ApiActionWrapper <GetAllSegmentsResult>(testContext, CheckWithAuthContextAndWithoutAuthContextSuccessCallBack), PlayFabUUnitUtils.ApiActionWrapper <PlayFabError>(testContext, CheckWithAuthContextAndWithoutAuthContextExpectedErrorCallBack), testContext);
        }
Esempio n. 22
0
        private static async Task <List <MonsterMB> > GetTitleData(FunctionExecutionContext <dynamic> context)
        {
            var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

            var result = await serverApi.GetTitleDataAsync(new PlayFab.ServerModels.GetTitleDataRequest()
            {
                Keys = new List <string>()
                {
                    "MonsterMB"
                },
            });

            var monsterList = JsonConvert.DeserializeObject <List <MonsterMB> >(result.Result.Data["MonsterMB"]);

            return(monsterList);
        }
        /// <summary>
        /// This method acts as an example on how to make an API call from an Azure Function back to PlayFab.
        /// While it is okay to use non-instance API in a game environment, it is critical to use the InstanceAPIs when
        /// making PlayFab API calls from an Azure Function as runtime may be shared among several of your functions, if not all,
        /// and using the static API methods can result in various static fields overriding each other when functions are
        /// called concurrently.
        /// </summary>
        /// <param name="playFabId"></param>
        /// <param name="statName"></param>
        /// <param name="deltaValue"></param>
        /// <returns></returns>
        public static async Task UpdateStatValue(string playFabId, string statName, int deltaValue)
        {
            // Create an API settings object with the authentication credentials
            var apiSettings = new PlayFabApiSettings
            {
                TitleId            = Environment.GetEnvironmentVariable(Constants.PLAYFAB_TITLE_ID, EnvironmentVariableTarget.Process),
                VerticalName       = Environment.GetEnvironmentVariable(Constants.PLAYFAB_CLOUD_NAME, EnvironmentVariableTarget.Process),
                DeveloperSecretKey = Environment.GetEnvironmentVariable(Constants.PLAYFAB_DEV_SECRET_KEY, EnvironmentVariableTarget.Process)
            };

            // Instantiate a server api client using the settings
            var serverApi = new PlayFabServerInstanceAPI(apiSettings);

            // Grab the previous value of the player's stat
            var currentStatResult = await serverApi.GetPlayerStatisticsAsync(
                new GetPlayerStatisticsRequest
            {
                PlayFabId = playFabId
            });

            // Apply the delta on the stat
            int oldValue = 0;

            // Try catch in case the stat was not found then assign it to the player
            try
            {
                oldValue = currentStatResult.Result.Statistics.First(stat => stat.StatisticName.Equals(statName)).Value;
            }
            catch (InvalidOperationException) {} // Do not handle stat not found for player, simply create it with update.

            var newValue = oldValue + deltaValue;

            // Update the player's stat with the new value
            var updateStatResult = await serverApi.UpdatePlayerStatisticsAsync(
                new UpdatePlayerStatisticsRequest
            {
                Statistics = new List <StatisticUpdate>
                {
                    new StatisticUpdate
                    {
                        StatisticName = statName,
                        Value         = newValue
                    }
                },
                PlayFabId = playFabId
            });
        }
    // ユーザーにアイテムを付与する
    // ユーザーにアイテムを付与するときは直接GrantItemsToUserを呼ぶんじゃなくてこれを呼ぶ
    public static async Task <List <GrantedItemInstance> > GrantItemsToUserAsync(FunctionExecutionContext <dynamic> context, List <string> itemIdList)
    {
        var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

        // アイテム付与前のインベントリ情報を保持しておく
        var beforeUserInventory = await DataProcessor.GetUserInventoryAsync(context);

        var result = await serverApi.GrantItemsToUserAsync(new GrantItemsToUserRequest()
        {
            PlayFabId = context.CallerEntityProfile.Lineage.MasterPlayerAccountId,
            ItemIds   = itemIdList
        });

        var grantedItemList = result.Result.ItemGrantResults;

        // 付与したアイテムが未所持モンスターだった場合新規でモンスターデータを作成し追加
        var monsterList = grantedItemList.Where(i => ItemUtil.GetItemType(i) == ItemType.Monster).ToList();

        if (monsterList.Any())
        {
            var monsterMasterList = await DataProcessor.GetMasterAsyncOf <MonsterMB>(context);

            var notHaveMonsterList = monsterList.Where(i => !beforeUserInventory.userMonsterList.Any(u => u.monsterId == ItemUtil.GetItemId(i))).ToList();

            // 未所持のモンスターデータを作成する
            foreach (var itemInstance in notHaveMonsterList)
            {
                var level      = 1;
                var monster    = monsterMasterList.First(m => m.id == ItemUtil.GetItemId(itemInstance));
                var status     = MonsterUtil.GetMonsterStatus(monster, level);
                var customData = new UserMonsterCustomData()
                {
                    level  = level,
                    exp    = 0,
                    hp     = status.hp,
                    attack = status.attack,
                    heal   = status.heal,
                    grade  = monster.initialGrade,
                };
                await DataProcessor.UpdateUserMonsterCustomDataAsync(context, itemInstance.ItemInstanceId, customData);
            }
        }

        return(grantedItemList);
    }
Esempio n. 25
0
        public static async Task <dynamic> UpdatePlayerMove(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            /* Create the function execution's context through the request */
            var context = await FunctionContext <dynamic> .Create(req);

            var args = context.FunctionArgument;

            /* Use the ApiSettings and AuthenticationContext provided to the function as context for making API calls. */
            var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

            bool validMove = await ProcessPlayerMove(serverApi, args["playerMove"], context.CurrentPlayerId, log);

            return(new
            {
                ValidMove = validMove
            });
        }
    // マスタデータを取得する
    public static async Task <List <T> > GetMasterAsyncOf <T>(FunctionExecutionContext <dynamic> context) where T : MasterBookBase
    {
        var serverApi = new PlayFabServerInstanceAPI(context.ApiSettings, context.AuthenticationContext);

        var masterDataName = TextUtil.GetDescriptionAttribute <T>();
        var result         = await serverApi.GetTitleDataAsync(new GetTitleDataRequest()
        {
            Keys = new List <string>()
            {
                masterDataName
            },
        });

        var masterDataJson = result.Result.Data[masterDataName];
        var masterDataList = JsonConvert.DeserializeObject <List <T> >(masterDataJson);

        return(masterDataList);
    }
Esempio n. 27
0
        public void ParallelRequest(UUnitTestContext testContext)
        {
            var settings1 = new PlayFabApiSettings();

            settings1.TitleId            = testTitleData.titleId;
            settings1.DeveloperSecretKey = testTitleData.developerSecretKey;

            var settings2 = new PlayFabApiSettings();

            settings2.TitleId            = testTitleData.titleId;
            settings2.DeveloperSecretKey = "TESTKEYERROR";

            PlayFabServerInstanceAPI serverInstance1 = new PlayFabServerInstanceAPI(settings1);
            PlayFabServerInstanceAPI serverInstance2 = new PlayFabServerInstanceAPI(settings2);

            serverInstance1.GetAllSegments(new GetAllSegmentsRequest(), PlayFabUUnitUtils.ApiActionWrapper <GetAllSegmentsResult>(testContext, ParallelRequestSuccessCallBack), PlayFabUUnitUtils.ApiActionWrapper <PlayFabError>(testContext, ParallelRequestExpectedErrorCallBack), testContext);
            serverInstance2.GetAllSegments(new GetAllSegmentsRequest(), PlayFabUUnitUtils.ApiActionWrapper <GetAllSegmentsResult>(testContext, ParallelRequestSuccessCallBack), PlayFabUUnitUtils.ApiActionWrapper <PlayFabError>(testContext, ParallelRequestExpectedErrorCallBack), testContext);
        }
Esempio n. 28
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()}");
            }
        }
Esempio n. 29
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");
            }
        }
Esempio n. 30
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");
            }
        }