private void LeaderBoardContinued(PlayFabResult <GetLeaderboardResult> clientResult, UUnitTestContext testContext, string failMessage) { testContext.True(clientResult.Result.Leaderboard.Count > 0, "Leaderboard does not contain enough entries."); }
private void LoginOrRegisterContinued(PlayFabResult <LoginResult> loginResult, UUnitTestContext testContext, string failMessage) { testContext.True(clientApi.IsClientLoggedIn(), failMessage); }
private void LoginWithAdvertisingIdContinued(PlayFabResult <LoginResult> loginResult, UUnitTestContext testContext, string failMessage) { testContext.True(clientApi.IsClientLoggedIn(), failMessage); testContext.StringEquals(PlayFabSettings.AD_TYPE_ANDROID_ID + "_Successful", PlayFabSettings.staticSettings.AdvertisingIdType); }
private void LeaderBoardContinued(PlayFabResult <GetAccountInfoResult> accountResult, UUnitTestContext testContext, string failMessage) { testContext.True(Enum.IsDefined(typeof(UserOrigination), accountResult.Result.AccountInfo.TitleInfo.Origination.Value), "Origination Enum not valid"); }
protected virtual async Task SilentlyAuthenticate(Platform platform, System.Action <LoginResult> callback = null) { PlayFabResult <LoginResult> result = null; switch (platform) { case Platform.Android: { //Login with the android device ID result = await PlayFabClient.LoginWithAndroidDeviceIDAsync(new LoginWithAndroidDeviceIDRequest() { TitleId = PlayFabSettings.staticSettings.TitleId, AndroidDevice = CrossDeviceInfo.Current.DeviceName, OS = CrossDeviceInfo.Current.Platform.ToString(), AndroidDeviceId = CrossDeviceInfo.Current.Id, CreateAccount = true, InfoRequestParameters = this.InfoRequestParams }).ConfigureAwait(false); } break; case Platform.iOS: { result = await PlayFabClient.LoginWithIOSDeviceIDAsync(new LoginWithIOSDeviceIDRequest() { TitleId = PlayFabSettings.staticSettings.TitleId, DeviceModel = CrossDeviceInfo.Current.Model, OS = CrossDeviceInfo.Current.Platform.ToString(), DeviceId = CrossDeviceInfo.Current.Id, CreateAccount = true, InfoRequestParameters = InfoRequestParams }).ConfigureAwait(false); } break; default: { result = await PlayFabClient.LoginWithCustomIDAsync(new LoginWithCustomIDRequest() { TitleId = PlayFabSettings.staticSettings.TitleId, CustomId = CrossDeviceInfo.Current.Id, CreateAccount = true, InfoRequestParameters = InfoRequestParams }).ConfigureAwait(false); } break; } if (null != result.Error) { //report errro back to the subscriber if (callback == null) { Logout(); OnPlayFabError?.Invoke(result.Error); } else { //make sure the loop completes, callback with null callback.Invoke(null); } } else { //Store identity and session PlayFabId = result.Result.PlayFabId; SessionTicket = result.Result.SessionTicket; //check if we want to get this callback directly or send to event subscribers. if (callback == null) { //report login result back to the subscriber OnLoginSuccess?.Invoke(result.Result); } else { //report login result back to the caller callback.Invoke(result.Result); } } }
private void GetEntityTokenContinued(PlayFabResult <GetEntityTokenResponse> result, UUnitTestContext testContext, string failMessage) { entityId = result.Result.Entity.Id; entityType = result.Result.Entity.Type; }
private void LoginOrRegisterContinued(PlayFabResult <LoginResult> loginResult, UUnitTestContext testContext, string failMessage) { PlayFabId = loginResult.Result.PlayFabId; // Needed for subsequent tests testContext.True(PlayFabClientAPI.IsClientLoggedIn(), "User login failed"); }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "ItemFound")] Item item, HttpRequestMessage req, [DocumentDB(Constants.CosmosDbName, Constants.FoundItemsCollectionName, ConnectionStringSetting = Constants.ConnectionStringSettingName, CreateIfNotExists = true)] IAsyncCollector <FoundItem> document, TraceWriter log) { log.Info("ItemFound, authenticating user"); try { string playFabId = await PlayFab.AuthenticateUserAsync(req, log); if (string.IsNullOrEmpty(playFabId)) { return(new HttpResponseMessage(HttpStatusCode.Unauthorized)); } log.Info("Adding found item"); item.Found = true; FoundItem fi = new FoundItem { Date = DateTime.Now.ToString(Constants.DateFormat), PlayFabId = playFabId, Item = item }; await document.AddAsync(fi); log.Info("Updating leaderboard"); UpdatePlayerStatisticsRequest playerStatReq = new UpdatePlayerStatisticsRequest { PlayFabId = playFabId, Statistics = new List <StatisticUpdate> { new StatisticUpdate { StatisticName = "Score", Value = 1 } } }; PlayFabResult <UpdatePlayerStatisticsResult> result = await PlayFabServerAPI.UpdatePlayerStatisticsAsync(playerStatReq); if (result.Error != null) { log.Error($"Error updating leaderboard: {result.Error.GenerateErrorReport()}"); } else { log.Info($"PlayFab complete: {result.Result}"); } log.Info("ItemFound complete"); return(new HttpResponseMessage(HttpStatusCode.OK)); } catch (Exception ex) { log.Error(ex.Message); return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } }
private async Task <Dictionary <string, string> > GetQoSServerList(bool listQosForTitle = false, bool chinaVer = false) { if (_dataCenterMap?.Count > 0) { // If the dataCenterMap is already initialized, return return(_dataCenterMap); } var response = new PlayFabResult <ListQosServersResponse>(); var dataCenterMap = new Dictionary <string, string>(); if (!chinaVer && listQosForTitle) { var request = new ListQosServersForTitleRequest(); PlayFabResult <ListQosServersForTitleResponse> res = await multiplayerApi.ListQosServersForTitleAsync(request); if (res == null || res.Error != null) { return(null); } dataCenterMap = new Dictionary <string, string>(res.Result.QosServers.Count); foreach (QosServer qosServer in res.Result.QosServers) { if (!string.IsNullOrEmpty(qosServer.Region)) { dataCenterMap[qosServer.Region] = qosServer.ServerUrl; } } return(_dataCenterMap = dataCenterMap); } else if (chinaVer) { //China Qos Servers response.Result = new ListQosServersResponse() { QosServers = new List <QosServer>() { new QosServer() { Region = "ChinaNorth2", ServerUrl = "pfmsqosprodcn.chinanorth2.cloudapp.chinacloudapi.cn" }, new QosServer() { Region = "ChinaEast2", ServerUrl = "pfmsqosprodcn.chinaeast2.cloudapp.chinacloudapi.cn" } } }; } else { var request = new ListQosServersRequest(); response = await multiplayerApi.ListQosServersAsync(request); } if (response == null || response.Error != null) { return(null); } dataCenterMap = new Dictionary <string, string>(response.Result.QosServers.Count); foreach (QosServer qosServer in response.Result.QosServers) { if (!string.IsNullOrEmpty(qosServer.Region)) { dataCenterMap[qosServer.Region] = qosServer.ServerUrl; } } // if (!chinaVer && !listQosForTitle) dataCenterMap = dataCenterMap.Where(x => x.Key == "EastAsia" || x.Key == "JapanWest").ToDictionary(t => t.Key, t => t.Value); //Specify some regions for testing return(_dataCenterMap = dataCenterMap); }
private static async Task Run(string titleId, string playerId, string buildId, 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(); PlayFabQosApi qosApi = new PlayFabQosApi(settings, clientApi.authenticationContext); QosResult qosResult = await qosApi.GetQosResultAsync(250, degreeOfParallelism : 4, pingsPerRegion : 10); 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(); // Allocate a server string sessionId = Guid.NewGuid().ToString(); List <string> preferredRegions = qosResult.RegionResults .Where(x => x.ErrorCode == (int)QosErrorCode.Success) .Select(x => x.Region).ToList(); PlayFabMultiplayerInstanceAPI mpApi = new PlayFabMultiplayerInstanceAPI(settings, clientApi.authenticationContext); PlayFabResult <RequestMultiplayerServerResponse> server = await mpApi.RequestMultiplayerServerAsync(new RequestMultiplayerServerRequest() { BuildId = buildId, PreferredRegions = preferredRegions, SessionId = sessionId } ); if (server.Error != null) { Console.WriteLine(server.Error.ErrorMessage); throw new Exception($"Allocation failed with HttpStatus={server.Error.HttpStatus}"); } string serverLoc = $"{server.Result.IPV4Address}:{server.Result.Ports[0].Num}"; Console.WriteLine($"Allocated server {serverLoc}"); // Issue Http request against the server using (HttpResponseMessage getResult = await HttpClient.GetAsync("http://" + serverLoc)) { getResult.EnsureSuccessStatusCode(); Console.WriteLine("Received response:"); string responseStr = await getResult.Content.ReadAsStringAsync(); Console.WriteLine(responseStr); Console.WriteLine(); } }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "CloudScript/ExecuteFunction")] HttpRequest request, ILogger log) { // Extract the caller's entity token string callerEntityToken = request.Headers["X-EntityToken"]; // Extract the request body and deserialize StreamReader reader = new StreamReader(request.Body); string body = await reader.ReadToEndAsync(); ExecuteFunctionRequest execRequest = PlayFabSimpleJson.DeserializeObject <ExecuteFunctionRequest>(body); // Grab the title entity token for authentication var titleEntityToken = await GetTitleEntityToken(); var argumentsUri = GetArgumentsUri(); // Prepare the `Get Arguments` request var contextRequest = new GetArgumentsForExecuteFunctionRequest { AuthenticationContext = new PlayFabAuthenticationContext { EntityToken = titleEntityToken }, CallingEntity = callerEntityToken, Request = execRequest }; // Execute the arguments request PlayFabResult <GetArgumentsForExecuteFunctionResult> getArgsResponse = await PlayFabCloudScriptAPI.GetArgumentsForExecuteFunctionAsync(contextRequest); // Validate no errors on arguments request if (getArgsResponse.Error != null) { throw new Exception("Failed to retrieve functions argument"); } // Extract the request for the next stage from the get arguments response EntityRequest entityRequest = getArgsResponse?.Result?.Request; // Assemble the target function's path in the current App string routePrefix = GetHostRoutePrefix(); string functionPath = routePrefix != null ? routePrefix + "/" + execRequest.FunctionName : execRequest.FunctionName; // Build URI of Azure Function based on current host var uriBuilder = new UriBuilder { Host = request.Host.Host, Port = request.Host.Port ?? 80, Path = functionPath }; // Serialize the request to the azure function and add headers var functionRequestContent = new StringContent(PlayFabSimpleJson.SerializeObject(entityRequest)); functionRequestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var sw = new Stopwatch(); sw.Start(); // Execute the local azure function using (var client = new HttpClient()) { using (HttpResponseMessage functionResponseMessage = await client.PostAsync(uriBuilder.Uri.AbsoluteUri, functionRequestContent)) { sw.Stop(); double executionTime = sw.ElapsedMilliseconds; // Extract the response content using (HttpContent functionResponseContent = functionResponseMessage.Content) { string functionResponseString = await functionResponseContent.ReadAsStringAsync(); // Prepare a response to reply back to client with and include function execution results var functionResult = new ExecuteFunctionResult { FunctionName = execRequest.FunctionName, FunctionResult = PlayFabSimpleJson.DeserializeObject(functionResponseString), ExecutionTimeSeconds = executionTime }; // Reply back to client with final results var output = new PlayFabJsonSuccess <ExecuteFunctionResult> { code = 200, status = "OK", data = functionResult }; var outputStr = PlayFabSimpleJson.SerializeObject(output); return(new HttpResponseMessage { Content = new StringContent(outputStr, Encoding.UTF8, "application/json"), StatusCode = HttpStatusCode.OK }); } } } }
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); } }