コード例 #1
0
 /// <summary>
 /// Cloud Script is one of PlayFab's most versatile features. It allows client code to request execution of any kind of
 /// custom server-side functionality you can implement, and it can be used in conjunction with virtually anything.
 /// </summary>
 public static void GetArgumentsForExecuteFunction(GetArgumentsForExecuteFunctionRequest request, Action <GetArgumentsForExecuteFunctionResult> resultCallback, Action <PlayFabError> errorCallback, object customData = null, Dictionary <string, string> extraHeaders = null)
 {
     PlayFabHttp.MakeApiCall("/CloudScript/GetArgumentsForExecuteFunction", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
 }
コード例 #2
0
        /// <summary>
        /// Cloud Script is one of PlayFab's most versatile features. It allows client code to request execution of any kind of
        /// custom server-side functionality you can implement, and it can be used in conjunction with virtually anything.
        /// </summary>
        public static async Task <PlayFabResult <GetArgumentsForExecuteFunctionResult> > GetArgumentsForExecuteFunctionAsync(GetArgumentsForExecuteFunctionRequest request, object customData = null, Dictionary <string, string> extraHeaders = null)
        {
            if ((request?.AuthenticationContext?.EntityToken ?? PlayFabSettings.staticPlayer.EntityToken) == null)
            {
                throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call GetEntityToken before calling this method");
            }

            var httpResult = await PlayFabHttp.DoPost("/CloudScript/GetArgumentsForExecuteFunction", request, "X-EntityToken", PlayFabSettings.staticPlayer.EntityToken, extraHeaders);

            if (httpResult is PlayFabError)
            {
                var error = (PlayFabError)httpResult;
                PlayFabSettings.GlobalErrorHandler?.Invoke(error);
                return(new PlayFabResult <GetArgumentsForExecuteFunctionResult> {
                    Error = error, CustomData = customData
                });
            }

            var resultRawJson = (string)httpResult;
            var resultData    = PluginManager.GetPlugin <ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject <PlayFabJsonSuccess <GetArgumentsForExecuteFunctionResult> >(resultRawJson);
            var result        = resultData.data;

            return(new PlayFabResult <GetArgumentsForExecuteFunctionResult> {
                Result = result, CustomData = customData
            });
        }
コード例 #3
0
        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
                        });
                    }
                }
            }
        }