question

Arnau Castillo avatar image
Arnau Castillo asked

Azure Function Update Leaderboard Problem

In the Visual Studio Installer I have installed Azure Development ("Desarrollo de Azure") and with that I have managed to create Azure Functions that have worked perfectly.

The problem that I have is that I want to update an statistic (my game has leaderboards) with the Azure Function that you have below.

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using PlayFab.Samples;


namespace FuncionRankingPrueba1
{
    public static class RankingPrueba
    {
        [FunctionName("UpdateRanking")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string name = req.Query["name"];
            string time = req.Query["time"];


            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.FunctionArgument?.name;
            time = time ?? data?.FunctionArgument?.time;
            float timeFloat = Single.Parse(time);

            var request = new UpdatePlayerStatisticsRequest
            {
                Statistics = new List<StatisticUpdate>
            {
                new StatisticUpdate
                {
                    StatisticName = name, Value = timeFloat
                }
            }
            };
            var result = server.UpdatePlayerStatistics(request);
            return new OkObjectResult(result);
        }
    }
}


I don't know if it is the correct way of doing it, but the problem that I face is that I don't manage to publish the function to Azure because these names are not found:

- UpdatePlayerStatisticsRequest

- List

- StatisticUpdate

- Playfab

I assume that Azure doesn't find the Playfab library, but I don't know how to add it to Visual Studio.

CloudScriptLeaderboards and Statistics
7lxg0.png (57.8 KiB)
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Made Wang avatar image
Made Wang answered

[Edited]Referring to Quickstart - PlayFab Client library for C# - PlayFab | Microsoft Docs, use the Nuget package manager to add PlayFabAllSDK, then add the following reference.

using PlayFab;

using PlayFab.ServerModels;

Regarding List, you need to add the following reference.

using System.Collections.Generic;

Also, you can delete the following two lines as they don't work in CSAF.

string name = req.Query["name"];
string time = req.Query["time"];

You can refer to the following code to further improve:

[FunctionName("UpdatePlayerStatistics")]
        public static async Task<dynamic> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string name; // = req.Query["name"];
            string time; // = req.Query["time"];
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = data?.FunctionArgument?.name;
            time = data?.FunctionArgument?.time;
            //float timeFloat = Single.Parse(time);
            int timeFloat = int.Parse(time);

            var request = new UpdatePlayerStatisticsRequest
            {
                PlayFabId = data.CallerEntityProfile.Lineage.MasterPlayerAccountId,
                Statistics = new List<StatisticUpdate>
            {
                new StatisticUpdate
                {
                    StatisticName = name, 
                    Value = timeFloat
                }
            }
            };
            var apiSettings = new PlayFabApiSettings
            {
                TitleId = data.TitleAuthenticationContext.Id,
                DeveloperSecretKey = Environment.GetEnvironmentVariable("PLAYFAB_DEV_SECRET_KEY", EnvironmentVariableTarget.Process),
            };
            var serverApi = new PlayFabServerInstanceAPI(apiSettings);
            return await serverApi.UpdatePlayerStatisticsAsync(request);
        }

1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Arnau Castillo avatar image Arnau Castillo commented ·

Thanks for the answer @Made Wang. I appreciate it. I am facing a new problem.

This is the only part of your code that I've changed.

 
                  
  1. var serverApi =newPlayFabServerInstanceAPI(apiSettings);
  2. return(IActionResult)await serverApi.UpdatePlayerStatisticsAsync(request);

I have had to add the (IActionResult) because otherwise it gives the error: "you can't convert the type "PlayFab.PlayFabResult<PlayFab.ServerModels.UpdatePlayerStatisticsResult>" in Microsoft.AspNetCore.Mvc.IActionResult".


The problem that I'm facing is that I can publish it without problem, but when I run this code from my project, where Prueba3 is the azure function that I've published, it gives this error:

"CloudScript/ExecuteFunction: Invocation of cloud script function Prueba3 failed"

If I simplify the azure function to only return the string (Level1Times) and integer (23), it works fine. It is only when I add the request that it fails.

0 Likes 0 ·
Arnau Castillo avatar image
Arnau Castillo answered

Thanks for the answer @Made Wang. I appreciate it. I am facing a new problem.

This is my final code:

namespace FuncionRankingPrueba1
{
    public static class RankingPrueba
    {
        [FunctionName("UpdateRanking")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string name; 
            string time; 
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = data?.FunctionArgument?.name;
            time = data?.FunctionArgument?.time;
            int timeint=  int.Parse(time);
            var request = new UpdatePlayerStatisticsRequest
            {
                PlayFabId = data.CallerEntityProfile.Lineage.MasterPlayerAccountId,
                Statistics = new List<StatisticUpdate>
            {
                new StatisticUpdate
                {
                    StatisticName = name,
                    Value = timeint
                }
            }
            };
            var apiSettings = new PlayFabApiSettings
            {
                TitleId = data.TitleAuthenticationContext.Id,
                DeveloperSecretKey = Environment.GetEnvironmentVariable("PLAYFAB_DEV_SECRET_KEY", EnvironmentVariableTarget.Process),
            };
            var serverApi = new PlayFabServerInstanceAPI(apiSettings);
            return (IActionResult)await serverApi.UpdatePlayerStatisticsAsync(request);
        }
    }
}

I have had to add the (IActionResult) because otherwise it gives the error: "you can't convert the type "PlayFab.PlayFabResult<PlayFab.ServerModels.UpdatePlayerStatisticsResult>" in Microsoft.AspNetCore.Mvc.IActionResult".


The problem that I'm facing is that I can publish it without problem, but when I run this code from my project, where Prueba3 is the azure function that I've published, it gives this error:

public void UpdateLeaderBoard()
    {
        Debug.Log("UpdateLead");
        PlayFabCloudScriptAPI.ExecuteFunction(new ExecuteFunctionRequest()
        {
            Entity = new PlayFab.CloudScriptModels.EntityKey()
            {
                Id = PlayFabSettings.staticPlayer.EntityId, 
                Type = PlayFabSettings.staticPlayer.EntityType, 
            },
            FunctionName = "Prueba3", 
            FunctionParameter = new {name= "Level1Times", time="23"},
            GeneratePlayStreamEvent = false 
        }, (ExecuteFunctionResult result) =>
        {
            Debug.Log($"The {result.FunctionName} function took {result.ExecutionTimeMilliseconds} to complete");
            Debug.Log($"Result: {result.FunctionResult.ToString()}");
        }, (PlayFabError error) =>
        {
            Debug.Log($"Opps Something went wrong: {error.GenerateErrorReport()}");
        });
    }


Error: "CloudScript/ExecuteFunction: Invocation of cloud script function Prueba3 failed"

If I simplify the azure function to only return the string (Level1Times) and integer (23), it works fine. It is only when I add the request that it fails.

1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Made Wang avatar image Made Wang commented ·

Sorry for my carelessness, you need to change the IActionResult to dynamic so that you don't need to typecast when returning the result, as follows.

public static async Task<dynamic> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Error rendering WebPanel (widgets/consolidation-widget.ftl): org.hibernate.hql.internal.ast.QuerySyntaxException: AvailableConsolidation is not mapped [from AvailableConsolidation up where up.node = :node]