Example #1
0
        /// <summary>
        /// Creates a new <c>FunctionExecutionContext</c> out of the incoming request to an Azure Function.
        /// </summary>
        /// <param name="request">The request incoming to an Azure Function from the PlayFab server</param>
        /// <returns>A new populated <c>FunctionExecutionContext</c> instance</returns>
        public static async Task <FunctionExecutionContext <TFunctionArgument> > Create(System.Net.Http.HttpRequestMessage request)
        {
            using (var content = request.Content)
            {
                var body = await content.ReadAsStringAsync();

                var contextInternal = Json.PlayFabSimpleJson.DeserializeObject <FunctionExecutionContextInternal>(body);
                var settings        = new PlayFabApiSettings
                {
                    TitleId = contextInternal.TitleAuthenticationContext.Id
                };
                var authContext = new PlayFabAuthenticationContext
                {
                    EntityToken = contextInternal.TitleAuthenticationContext.EntityToken
                };

                return(new FunctionExecutionContext <TFunctionArgument>()
                {
                    ApiSettings = settings,
                    CallerEntityProfile = contextInternal.CallerEntityProfile,
                    FunctionArgument = contextInternal.FunctionArgument,
                    AuthenticationContext = authContext
                });
            }
        }
Example #2
0
 public CheckBblStandby()
 {
     context        = new PlayFabAuthenticationContext();
     settings       = new PlayFabApiSettings();
     authApi        = new PlayFabAuthenticationInstanceAPI(settings, context);
     multiplayerApi = new PlayFabMultiplayerInstanceAPI(settings, context);
 }
        /// <summary>
        /// Creates a new <c>FunctionTaskContext</c> out of the incoming request to an Azure Function.
        /// </summary>
        /// <param name="request">The request incoming to an Azure Function from the PlayFab server</param>
        /// <returns>A new populated <c>FunctionTaskContext</c> instance</returns>
        public static async Task <FunctionTaskContext <TFunctionArgument> > Create(HttpRequestMessage request)
        {
            using (var content = request.Content)
            {
                var body = await content.ReadAsStringAsync();

                var contextInternal = PlayFabSimpleJson.DeserializeObject <FunctionTaskContextInternal>(body);
                var settings        = new PlayFabApiSettings
                {
                    TitleId            = contextInternal.TitleAuthenticationContext.Id,
                    DeveloperSecretKey = Environment.GetEnvironmentVariable("PLAYFAB_DEV_SECRET_KEY", EnvironmentVariableTarget.Process)
                };

                var authContext = new PlayFabAuthenticationContext
                {
                    EntityToken = contextInternal.TitleAuthenticationContext.EntityToken
                };

                return(new FunctionTaskContext <TFunctionArgument>()
                {
                    ApiSettings = settings,
                    AuthenticationContext = authContext,
                    ScheduledTaskNameId = contextInternal.ScheduledTaskNameId,
                    EventHistory = contextInternal.EventHistory,
                    FunctionArgument = contextInternal.FunctionArgument
                });
            }
        }
        /// <summary>
        /// Separated from OnPlayFabLogin, to explicitly lose the refs to loginResult and registerResult, because
        ///   only one will be defined, but both usually have all the information we REALLY need here.
        /// But the result signatures are different and clunky, so do the separation above, and processing here
        /// </summary>
        private static void _OnPlayFabLogin(ClientModels.UserSettings settingsForUser, string playFabId, string entityId,
                                            string entityType, PlayFabApiSettings settings, IPlayFabInstanceApi instanceApi)
        {
            _needsAttribution = _gatherDeviceInfo = _gatherScreenTime = false;
            if (settingsForUser != null)
            {
                _needsAttribution = settingsForUser.NeedsAttribution;
                _gatherDeviceInfo = settingsForUser.GatherDeviceInfo;
                _gatherScreenTime = settingsForUser.GatherFocusInfo;
            }

            // Device attribution (adid or idfa)
            if (settings.AdvertisingIdType != null && settings.AdvertisingIdValue != null)
            {
                DoAttributeInstall(settings, instanceApi);
            }
            else
            {
                GetAdvertIdFromUnity(settings, instanceApi);
            }

            // Device information gathering
            SendDeviceInfoToPlayFab(settings, instanceApi);

#if !DISABLE_PLAYFABENTITY_API
            if (!string.IsNullOrEmpty(entityId) && !string.IsNullOrEmpty(entityType) && _gatherScreenTime)
            {
                PlayFabHttp.InitializeScreenTimeTracker(entityId, entityType, playFabId);
            }
            else
            {
                settings.DisableFocusTimeCollection = true;
            }
#endif
        }
        /// <summary>
        /// Creates a new <c>FunctionContext</c> out of the incoming request to an Azure Function.
        /// </summary>
        /// <param name="request">The request incoming to an Azure Function from the PlayFab server</param>
        /// <returns>A new populated <c>FunctionContext</c> instance</returns>
        public static async Task <FunctionContext <TFunctionArgument> > Create(HttpRequestMessage request)
        {
            using (var content = request.Content)
            {
                var body = await content.ReadAsStringAsync();

                var contextInternal = Json.PlayFabSimpleJson.DeserializeObject <FunctionContextInternal>(body);
                var settings        = new PlayFabApiSettings
                {
                    TitleId            = contextInternal.TitleAuthenticationContext.Id,
                    DeveloperSecretKey = Environment.GetEnvironmentVariable("PLAYFAB_DEV_SECRET_KEY", EnvironmentVariableTarget.Process)
                };

                var authContext = new PlayFabAuthenticationContext
                {
                    EntityToken = contextInternal.TitleAuthenticationContext.EntityToken
                };

                return(new FunctionContext <TFunctionArgument>()
                {
                    ApiSettings = settings,
                    CallerEntityProfile = contextInternal.CallerEntityProfile,
                    FunctionArgument = contextInternal.FunctionArgument,
                    AuthenticationContext = authContext,
                    CurrentPlayerId = contextInternal.CallerEntityProfile.Lineage.TitlePlayerAccountId
                });
            }
        }
Example #6
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);
        }
Example #7
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);
        }
Example #8
0
        public static async Task <EmptyResponse> AddMember(PlayFabAuthenticationContext authenticationContext, string matchlobbyId, EntityKey member)
        {
            var apiSettings = new PlayFabApiSettings
            {
                TitleId            = Environment.GetEnvironmentVariable(Constants.PLAYFAB_TITLE_ID, EnvironmentVariableTarget.Process),
                DeveloperSecretKey = Environment.GetEnvironmentVariable(Constants.PLAYFAB_DEV_SECRET_KEY, EnvironmentVariableTarget.Process)
            };
            var groupApi = new PlayFabGroupsInstanceAPI(apiSettings, authenticationContext);
            var members  = new List <EntityKey>()
            {
                member
            };

            var response = await groupApi.AddMembersAsync(new AddMembersRequest
            {
                Group = new EntityKey
                {
                    Id   = matchlobbyId,
                    Type = "group"
                },
                Members = members
            });

            if (response.Error != null)
            {
                throw new Exception($"An error occurred while the addition of member to the group: Error: {response.Error.GenerateErrorReport()}");
            }

            return(response.Result);
        }
        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);
        }
Example #10
0
        private static void DoAttributeInstall(PlayFabApiSettings settings, IPlayFabInstanceApi instanceApi)
        {
            if (!_needsAttribution || settings.DisableAdvertising)
            {
                return; // Don't send this value to PlayFab if it's not required
            }
            var attribRequest = new ClientModels.AttributeInstallRequest();

            switch (settings.AdvertisingIdType)
            {
            case PlayFabSettings.AD_TYPE_ANDROID_ID: attribRequest.Adid = settings.AdvertisingIdValue; break;

            case PlayFabSettings.AD_TYPE_IDFA: attribRequest.Idfa = settings.AdvertisingIdValue; break;
            }
            var clientInstanceApi = instanceApi as PlayFabClientInstanceAPI;

            if (clientInstanceApi != null)
            {
                clientInstanceApi.AttributeInstall(attribRequest, OnAttributeInstall, null, settings);
            }
            else
            {
                PlayFabClientAPI.AttributeInstall(attribRequest, OnAttributeInstall, null, settings);
            }
        }
        private static void SendDeviceInfoToPlayFab(PlayFabApiSettings settings, IPlayFabInstanceApi instanceApi)
        {
            if (settings.DisableDeviceInfo || !_gatherDeviceInfo)
            {
                return;
            }

            var serializer = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer);
            var request    = new ClientModels.DeviceInfoRequest
            {
                Info = serializer.DeserializeObject <Dictionary <string, object> >(serializer.SerializeObject(new PlayFabDataGatherer()))
            };
            var clientInstanceApi = instanceApi as PlayFabClientInstanceAPI;

            if (clientInstanceApi != null)
            {
                clientInstanceApi.ReportDeviceInfo(request, null, OnGatherFail, settings);
            }
#if !DISABLE_PLAYFAB_STATIC_API
            else
            {
                PlayFabClientAPI.ReportDeviceInfo(request, null, OnGatherFail, settings);
            }
#endif
        }
        private static async void SendDeviceInfoToPlayFab(PlayFabApiSettings settings, IPlayFabInstanceApi instanceApi)
        {
            if (settings.DisableDeviceInfo || !_gatherDeviceInfo)
            {
                return;
            }

            var serializer = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer);
            var request    = new ClientModels.DeviceInfoRequest
            {
                Info = serializer.DeserializeObject <Dictionary <string, object> >(serializer.SerializeObject(new PlayFabDataGatherer()))
            };
            var clientInstanceApi = instanceApi as PlayFabClientInstanceAPI;

            if (clientInstanceApi != null)
            {
                clientInstanceApi.ReportDeviceInfo(request, null, e => Debug.Log("OnGatherFail: " + e.GenerateErrorReport()), settings);
            }
            else
            {
                try
                {
                    await ClientAPI.ReportDeviceInfo(request.Info, customData : settings);
                }
                catch (PlayFabError e)
                {
                    Debug.Log("OnGatherFail: " + e.GenerateErrorReport());
                }
            }
        }
Example #13
0
 public Player(string customId, PlayFabApiSettings settings)
 {
     this.customId = customId;
     httpClient    = new HttpClient();
     context       = new PlayFabAuthenticationContext();
     clientApi     = new PlayFabClientInstanceAPI(settings, context);
     mpApi         = new PlayFabMultiplayerInstanceAPI(settings, context);
 }
Example #14
0
        public PlayFabQosApi(PlayFabApiSettings settings = null, PlayFabAuthenticationContext authContext = null, bool reportResults = true)
        {
            _authContext = authContext ?? PlayFabSettings.staticPlayer;

            multiplayerApi     = new PlayFabMultiplayerInstanceAPI(settings, _authContext);
            eventsApi          = new PlayFabEventsInstanceAPI(settings, _authContext);
            qosResultsReporter = SendSuccessfulQosResultsToPlayFab;
            _reportResults     = reportResults;
        }
Example #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);
        }
Example #16
0
        public static void TrySetSecretKey(PlayFabApiSettings settings)
        {
            var secretKey = Environment.GetEnvironmentVariable(Constants.PLAYFAB_DEV_SECRET_KEY, EnvironmentVariableTarget.Process);

            if (!string.IsNullOrEmpty(secretKey))
            {
                settings.DeveloperSecretKey = secretKey;
            }
        }
Example #17
0
        public static void TrySetCloudName(PlayFabApiSettings settings)
        {
            var cloud = Environment.GetEnvironmentVariable(Constants.PLAYFAB_CLOUD_NAME, EnvironmentVariableTarget.Process);

            if (!string.IsNullOrEmpty(cloud))
            {
                settings.VerticalName = cloud;
            }
        }
Example #18
0
        private static async Task Run(string titleId, string playerId, bool chinaVer, bool listQosForTitle, bool verbose)
        {
            PlayFabApiSettings settings = new PlayFabApiSettings()
            {
                TitleId = titleId
            };
            PlayFabClientInstanceAPI clientApi = new PlayFabClientInstanceAPI(settings);

            // Login
            var loginRequest = new LoginWithCustomIDRequest()
            {
                CustomId      = playerId,
                CreateAccount = true
            };
            PlayFabResult <LoginResult> login = await clientApi.LoginWithCustomIDAsync(loginRequest);

            if (login.Error != null)
            {
                Console.WriteLine(login.Error.ErrorMessage);
                throw new Exception($"Login failed with HttpStatus={login.Error.HttpStatus}");
            }
            Console.WriteLine($"Logged in player {login.Result.PlayFabId} (CustomId={playerId})");
            Console.WriteLine();

            // Measure QoS
            Stopwatch sw = Stopwatch.StartNew();

            PlayFabSDKWrapper.QoS.PlayFabQosApi qosApi    = new PlayFabSDKWrapper.QoS.PlayFabQosApi(settings, clientApi.authenticationContext);
            PlayFabSDKWrapper.QoS.QosResult     qosResult = await qosApi.GetQosResultAsync(250, degreeOfParallelism : 4, pingsPerRegion : 10, listQosForTitle : listQosForTitle, chinaVer : chinaVer);

            if (qosResult.ErrorCode != 0)
            {
                Console.WriteLine(qosResult.ErrorMessage);
                throw new Exception($"QoS ping failed with ErrorCode={qosResult.ErrorCode}");
            }

            Console.WriteLine($"Pinged QoS servers in {sw.ElapsedMilliseconds}ms with results:");

            if (verbose)
            {
                string resultsStr = JsonConvert.SerializeObject(qosResult.RegionResults, Formatting.Indented);
                Console.WriteLine(resultsStr);
            }

            int timeouts = qosResult.RegionResults.Sum(x => x.NumTimeouts);

            Console.WriteLine(string.Join(Environment.NewLine,
                                          qosResult.RegionResults.Select(x => $"{x.Region} - {x.LatencyMs}ms")));

            Console.WriteLine($"NumTimeouts={timeouts}");
            Console.WriteLine();

            Console.ReadKey();
        }
Example #19
0
        public static async Task <GetObjectsResponse> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] FunctionExecutionContext 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)}");

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

            var titleAuthContext = new PlayFabAuthenticationContext();

            titleAuthContext.EntityToken = req.TitleAuthenticationContext.EntityToken;

            var api = new PlayFabDataInstanceAPI(titleSettings, titleAuthContext);

            var getObjectsRequest = new GetObjectsRequest
            {
                Entity = new DataModels.EntityKey
                {
                    Id   = req.CallerEntityProfile.Entity.Id,
                    Type = req.CallerEntityProfile.Entity.Type
                }
            };

            Stopwatch sw = Stopwatch.StartNew();
            PlayFabResult <GetObjectsResponse> getObjectsResponse = await api.GetObjectsAsync(getObjectsRequest);

            sw.Stop();

            if (getObjectsResponse.Error != null)
            {
                throw new InvalidOperationException($"GetObjectsAsync failed: {getObjectsResponse.Error.GenerateErrorReport()}");
            }
            else
            {
                log.LogInformation($"GetObjectsAsync succeeded in {sw.ElapsedMilliseconds}ms");
                log.LogInformation($"GetObjectsAsync returned. ProfileVersion: {getObjectsResponse.Result.ProfileVersion}. Entity: {getObjectsResponse.Result.Entity.Id}/{getObjectsResponse.Result.Entity.Type}. NumObjects: {getObjectsResponse.Result.Objects.Count}.");
                return(getObjectsResponse.Result);
            }
        }
Example #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);
        }
        public async void TestForNotFoundWithImportantInfo(UUnitTestContext testContext)
        {
            var eReq = new AuthenticationModels.GetEntityTokenRequest();

            eReq.Entity      = new AuthenticationModels.EntityKey();
            eReq.Entity.Type = "title";
            eReq.Entity.Id   = testTitleData.titleId;

            var multiApiSettings = new PlayFabApiSettings();

            multiApiSettings.TitleId            = testTitleData.titleId;
            multiApiSettings.DeveloperSecretKey = testTitleData.developerSecretKey;
            var authApi = new PlayFabAuthenticationInstanceAPI(multiApiSettings);

            var tokenTask = await authApi.GetEntityTokenAsync(eReq);

            testContext.IsNull(tokenTask.Error, "Failed to retrieve the Title Entity Token, check your playFabSettings.staticPlayer: " + PlayFabSettings.staticPlayer.EntityType);

            if (aliasId == "")
            {
                testContext.Fail("aliasId was blank, we will not get the expected failed NotFound response this test is asking for. Make sure testTitleData.json has a valid aliasId listed (check playfab multiplayer dashboard for your own valid aliasId)");
            }

            MultiplayerModels.UpdateBuildAliasRequest updateBuildAliasRequest = new MultiplayerModels.UpdateBuildAliasRequest()
            {
                AliasId               = aliasId,
                AliasName             = "aliasName",
                AuthenticationContext = new PlayFab.PlayFabAuthenticationContext()
                {
                    EntityToken = tokenTask.Result.EntityToken
                },
            };

            var multiplayerApi = new PlayFabMultiplayerInstanceAPI(multiApiSettings, updateBuildAliasRequest.AuthenticationContext);

            PlayFab.PlayFabResult <MultiplayerModels.BuildAliasDetailsResponse> res = await multiplayerApi.UpdateBuildAliasAsync(updateBuildAliasRequest);

            string response = PlayFab.PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer).SerializeObject(res);

            if (response.Contains("MultiplayerServerNotFound") && res.Error.HttpCode == 404)
            {
                testContext.EndTest(UUnitFinishState.PASSED, null);
            }
            else
            {
                testContext.Fail("We called the Mutliplayer API expecting to not find anything, but we didn't detect this to be the error. Details: " + res.Error.GenerateErrorReport() + " and http code: " + res.Error.HttpCode);
            }
        }
Example #22
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);
        }
        /// <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
            });
        }
Example #24
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);
        }
Example #25
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()}");
            }
        }
Example #26
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");
            }
        }
        /// <summary>
        /// When a PlayFab login occurs, check the result information, and
        ///   relay it to _OnPlayFabLogin where the information is used
        /// </summary>
        /// <param name="result"></param>
        public static void OnPlayFabLogin(PlayFabResultCommon result, PlayFabApiSettings settings,
                                          IPlayFabInstanceApi instanceApi)
        {
            var loginResult    = result as ClientModels.LoginResult;
            var registerResult = result as ClientModels.RegisterPlayFabUserResult;

            if (loginResult == null && registerResult == null)
            {
                return;
            }

            // Gather things common to the result types
            ClientModels.UserSettings settingsForUser = null;
            string playFabId  = null;
            string entityId   = null;
            string entityType = null;

            if (loginResult != null)
            {
                settingsForUser = loginResult.SettingsForUser;
                playFabId       = loginResult.PlayFabId;
                if (loginResult.EntityToken != null)
                {
                    entityId   = loginResult.EntityToken.Entity.Id;
                    entityType = loginResult.EntityToken.Entity.Type;
                }
            }
            else if (registerResult != null)
            {
                settingsForUser = registerResult.SettingsForUser;
                playFabId       = registerResult.PlayFabId;
                if (registerResult.EntityToken != null)
                {
                    entityId   = registerResult.EntityToken.Entity.Id;
                    entityType = registerResult.EntityToken.Entity.Type;
                }
            }

            _OnPlayFabLogin(settingsForUser, playFabId, entityId, entityType, settings, instanceApi);
        }
Example #28
0
        private static void GetAdvertIdFromUnity(PlayFabApiSettings settings, IPlayFabInstanceApi instanceApi)
        {
#if UNITY_5_3_OR_NEWER && (UNITY_ANDROID || UNITY_IOS) && (!UNITY_EDITOR || TESTING)
            Application.RequestAdvertisingIdentifierAsync(
                (advertisingId, trackingEnabled, error) =>
            {
                settings.DisableAdvertising = !trackingEnabled;
                if (!trackingEnabled)
                {
                    return;
                }
#if UNITY_ANDROID
                settings.AdvertisingIdType = PlayFabSettings.AD_TYPE_ANDROID_ID;
#elif UNITY_IOS
                settings.AdvertisingIdType = PlayFabSettings.AD_TYPE_IDFA;
#endif
                settings.AdvertisingIdValue = advertisingId;
                DoAttributeInstall(settings, instanceApi);
            }
                );
#endif
        }
Example #29
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");
            }
        }
        public void CheckWithAuthContextAndWithoutAuthContext(UUnitTestContext testContext)
        {
            PlayFabSettings.staticSettings.TitleId            = testTitleData.titleId;
            PlayFabSettings.staticSettings.DeveloperSecretKey = testTitleData.developerSecretKey;

            //IT will  use static developer key - Should has no error
            PlayFabServerInstanceAPI serverInstance1 = new PlayFabServerInstanceAPI();

            //IT will  use context developer key - Should has error because of wrong key
            PlayFabApiSettings settings2 = new PlayFabApiSettings();

            settings2.TitleId            = testTitleData.titleId;
            settings2.DeveloperSecretKey = "WRONGKEYTOFAIL";
            PlayFabServerInstanceAPI serverInstance2 = new PlayFabServerInstanceAPI(settings2);

            PlayFabResult <GetAllSegmentsResult> result1, result2;

            try
            {
                result1 = serverInstance1.GetAllSegmentsAsync(new GetAllSegmentsRequest()).Result;
                result2 = serverInstance2.GetAllSegmentsAsync(new GetAllSegmentsRequest()).Result;
            }
            catch (AggregateException e)
            {
                throw e.InnerException;
            }

            testContext.IsNull(result1.Error, result1?.Error?.GenerateErrorReport());
            testContext.NotNull(result1.Result, "Server Instance1 result is null");

            testContext.NotNull(result2.Error, result2?.Error?.GenerateErrorReport());
            testContext.IsNull(result2.Result, result2?.Error?.GenerateErrorReport());
            testContext.IntEquals(401, result2.Error.HttpCode, "Server Instance2 got wrong error");

            testContext.EndTest(UUnitFinishState.PASSED, null);
        }