Пример #1
0
        public void Awake()
        {
            // Instance methods must be cast to a delegate inside the registration function
            PlayFabSettings.RequestCallback <object> onApiRequestInstGl = OnApiRequest_InstGl;                            // Generic callbacks have to use the generic signature
            PlayFabSettings.ResponseCallback <object, PlayFabResultCommon> onApiResponseInstGl    = OnApiResponse_InstGl; // Generic callbacks have to use the generic signature
            PlayFabClientAPI.LoginWithEmailAddressRequestCallback          onApiRequestInstLogin  = OnApiRequest_InstLogin;
            PlayFabClientAPI.LoginWithEmailAddressResponseCallback         onApiResponseInstLogin = OnApiResponse_InstLogin;
            PlayFabSettings.RequestCallback <object> onApiRequestInstLogin2 = OnApiRequest_InstLogin2;                         // Generic callbacks have to use the generic signature
            PlayFabSettings.ResponseCallback <object, PlayFabResultCommon> onApiResponseInstLogin2 = OnApiResponse_InstLogin2; // Generic callbacks have to use the generic signature

            // Registering for instance methods, using the local delegate variables (bound to the "this" instance)
            PlayFabSettings.RegisterForRequests(null, onApiRequestInstGl);
            PlayFabSettings.RegisterForResponses(null, onApiResponseInstGl);
            PlayFabSettings.RegisterForRequests("/Client/LoginWithEmailAddress", onApiRequestInstLogin);
            PlayFabSettings.RegisterForResponses("/Client/LoginWithEmailAddress", onApiResponseInstLogin);
            PlayFabSettings.RegisterForRequests("/Client/LoginWithAndroidDeviceID", onApiRequestInstLogin2);
            PlayFabSettings.RegisterForResponses("/Client/LoginWithAndroidDeviceID", onApiResponseInstLogin2);
            PlayFabSettings.RegisterForRequests("/Client/LoginWithIOSDeviceID", onApiRequestInstLogin2);
            PlayFabSettings.RegisterForResponses("/Client/LoginWithIOSDeviceID", onApiResponseInstLogin2);

            // Registering for static methods, using the static delegate variables defined by each function
            PlayFabSettings.RegisterForRequests(null, _onApiRequestStGl);
            PlayFabSettings.RegisterForResponses(null, _onApiResponseStGl);
            PlayFabSettings.RegisterForRequests("/Client/LoginWithEmailAddress", _onApiRequestStLogin);
            PlayFabSettings.RegisterForResponses("/Client/LoginWithEmailAddress", _onApiResponseStLogin);
            PlayFabSettings.RegisterForRequests("/Client/LoginWithAndroidDeviceID", _onApiRequestStLogin2);
            PlayFabSettings.RegisterForResponses("/Client/LoginWithAndroidDeviceID", _onApiResponseStLogin2);
            PlayFabSettings.RegisterForRequests("/Client/LoginWithIOSDeviceID", _onApiRequestStLogin2);
            PlayFabSettings.RegisterForResponses("/Client/LoginWithIOSDeviceID", _onApiResponseStLogin2);
        }
Пример #2
0
        public static async Task <object> DoPost(string urlPath, PlayFabRequestCommon request, string authType, string authKey, Dictionary <string, string> extraHeaders, PlayFabApiSettings apiSettings = null)
        {
            var fullPath = apiSettings == null?PlayFabSettings.GetFullUrl(urlPath, PlayFabSettings.RequestGetParams) : apiSettings.GetFullUrl(urlPath, PlayFabSettings.RequestGetParams);

            var titleId = apiSettings?.TitleId == null ? PlayFabSettings.TitleId : apiSettings.TitleId;

            if (titleId == null)
            {
                throw new PlayFabException(PlayFabExceptionCode.TitleNotSet, "You must set your titleId before making an api call");
            }
            var transport = PluginManager.GetPlugin <ITransportPlugin>(PluginContract.PlayFab_Transport);

            var headers = new Dictionary <string, string>();

            if (authType != null && authKey != null)
            {
                headers[authType] = authKey;
            }
            if (extraHeaders != null)
            {
                foreach (var extraHeader in extraHeaders)
                {
                    headers.Add(extraHeader.Key, extraHeader.Value);
                }
            }

            return(await transport.DoPost(fullPath, request, headers));
        }
Пример #3
0
        /// <summary>
        /// Sends a POST HTTP request
        /// </summary>
        public static void Post(string urlPath, string data, string authType, string authKey, Action <CallRequestContainer> callback, object request, object customData, bool isBlocking = false)
        {
            var requestContainer = new CallRequestContainer {
                RequestType = PlayFabSettings.RequestType, CallId = callIdGen++, AuthKey = authKey, AuthType = authType, Callback = callback, Data = data, Url = urlPath, Request = request, CustomData = customData
            };

            if (!isBlocking)
            {
#if PLAYFAB_IOS_PLUGIN
                PlayFabiOSPlugin.Post(PlayFabSettings.GetFullUrl(urlPath), PlayFabVersion.getVersionString(), requestContainer, PlayFabSettings.InvokeRequest);
#elif UNITY_WP8
                instance.StartCoroutine(instance.MakeRequestViaUnity(requestContainer));
#else
                if (PlayFabSettings.RequestType == WebRequestType.HttpWebRequest)
                {
                    lock (ActiveRequests)
                        ActiveRequests.Insert(0, requestContainer); // Parsing on this container is done backwards, so insert at 0 to make calls process in roughly queue order (but still not actually guaranteed)
                    PlayFabSettings.InvokeRequest(urlPath, requestContainer.CallId, request, customData);
                    _ActivateWorkerThread();
                }
                else
                {
                    instance.StartCoroutine(instance.MakeRequestViaUnity(requestContainer));
                }
#endif
            }
            else
            {
                StartHttpWebRequest(requestContainer);
                ProcessHttpWebResult(requestContainer, true);
                callback(requestContainer);
            }
        }
        /// <summary>
        /// Internal method for Make API Calls
        /// </summary>
        protected internal static void MakeApiCall <TResult>(string apiEndpoint,
                                                             PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback,
                                                             Action <PlayFabError> errorCallback, object customData = null, bool allowQueueing = false)
            where TResult : PlayFabResultCommon
        {
            InitializeHttp();
            SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre);

            var reqContainer = new CallRequestContainer
            {
                ApiEndpoint   = apiEndpoint,
                FullUrl       = PlayFabSettings.GetFullUrl(apiEndpoint),
                CustomData    = customData,
                Payload       = Encoding.UTF8.GetBytes(JsonWrapper.SerializeObject(request, PlayFabUtil.ApiSerializerStrategy)),
                AuthKey       = authType,
                ApiRequest    = request,
                ErrorCallback = errorCallback,
            };

#if PLAYFAB_REQUEST_TIMING
            reqContainer.Timing.StartTimeUtc = DateTime.UtcNow;
            reqContainer.Timing.ApiEndpoint  = apiEndpoint;
#endif

            // These closures preserve the TResult generic information in a way that's safe for all the devices
            reqContainer.DeserializeResultJson = () =>
            {
                reqContainer.ApiResult = JsonWrapper.DeserializeObject <TResult>(reqContainer.JsonResponse, PlayFabUtil.ApiSerializerStrategy);
            };
            reqContainer.InvokeSuccessCallback = () =>
            {
                if (resultCallback != null)
                {
                    resultCallback((TResult)reqContainer.ApiResult);
                }
            };

            if (allowQueueing && _apiCallQueue != null && !_internalHttp.SessionStarted)
            {
                for (var i = _apiCallQueue.Count - 1; i >= 0; i--)
                {
                    if (_apiCallQueue[i].ApiEndpoint == apiEndpoint)
                    {
                        _apiCallQueue.RemoveAt(i);
                    }
                }
                _apiCallQueue.Add(reqContainer);
            }
            else
            {
                _internalHttp.MakeApiCall(reqContainer);
            }
        }
Пример #5
0
        private static HttpClient CreateClient(this PlayFabSettings settings)
        {
            HttpClient client = settings.MessageHandler == null
                ? new HttpClient()
                : new HttpClient(settings.MessageHandler);

            if (settings.RequestTimeout.HasValue)
            {
                client.Timeout = settings.RequestTimeout.Value;
            }

            return(client);
        }
Пример #6
0
            public void Register()
            {
                // Instance methods must be cast to a delegate inside the registration function
                PlayFabSettings.RequestCallback <object> onRequestInstGl = OnRequest_InstGl;                         // Generic callbacks have to use the generic signature
                PlayFabSettings.ResponseCallback <object, PlayFabResultCommon> onResponseInstGl = OnResponse_InstGl; // Generic callbacks have to use the generic signature
                PlayFabClientAPI.LoginWithCustomIDRequestCallback  onRequestInstLogin           = OnRequest_InstLogin;
                PlayFabClientAPI.LoginWithCustomIDResponseCallback onResponseInstLogin          = OnResponse_InstLogin;

                // Registering for instance methods, using the local delegate variables (bound to the "this" instance)
                PlayFabSettings.RegisterForRequests(null, onRequestInstGl);
                PlayFabSettings.RegisterForResponses(null, onResponseInstGl);
                PlayFabSettings.RegisterForRequests("/Client/LoginWithCustomID", onRequestInstLogin);
                PlayFabSettings.RegisterForResponses("/Client/LoginWithCustomID", onResponseInstLogin);
            }
Пример #7
0
        public void OnDestroy()
        {
            PlayFabSettings.UnregisterInstance(this); // Automatically unregisters all callbacks bound to this instance - No delegate casting or local variables needed for a full un-register

            // Un-registering for static methods, using the static delegate variables defined by each function - No simple way to identify/clear these together the instance
            PlayFabSettings.UnregisterForRequests(null, _onApiRequestStGl);
            PlayFabSettings.UnregisterForResponses(null, _onApiResponseStGl);
            PlayFabSettings.UnregisterForRequests("/Client/LoginWithEmailAddress", _onApiRequestStLogin);
            PlayFabSettings.UnregisterForResponses("/Client/LoginWithEmailAddress", _onApiResponseStLogin);
            PlayFabSettings.UnregisterForRequests("/Client/LoginWithAndroidDeviceID", _onApiRequestStLogin2);
            PlayFabSettings.UnregisterForResponses("/Client/LoginWithAndroidDeviceID", _onApiResponseStLogin2);
            PlayFabSettings.UnregisterForRequests("/Client/LoginWithIOSDeviceID", _onApiRequestStLogin2);
            PlayFabSettings.UnregisterForResponses("/Client/LoginWithIOSDeviceID", _onApiResponseStLogin2);
        }
Пример #8
0
        internal static async Task DoPut(this PlayFabSettings settings, string apiName, string url, string contentType, Stream data)
        {
            HttpResponseMessage httpResponse = null;

            if (settings.ApiCallback != null)
            {
                settings.ApiCallback(PlayFabApiEvent.SendingRequest, settings, apiName, "PUT", url, null);
            }

            using (HttpClient client = settings.CreateClient())
                using (StreamContent body = new StreamContent(data))
                {
                    body.Headers.Add("Content-Type", contentType);

                    httpResponse = await client.PutAsync(url, body);

                    var httpResponseStream = await httpResponse.Content.ReadAsStreamAsync();

                    bool hasData = true;
                    var  buffer  = new byte[4096];
                    do
                    {
                        int read = await httpResponseStream.ReadAsync(buffer, 0, buffer.Length);

                        hasData = read != 0;
                    } while (hasData);

                    if (settings.ApiCallback != null)
                    {
                        settings.ApiCallback(PlayFabApiEvent.ReceivedReply, settings, apiName, "PUT", url, null);
                    }
                }

            if (!httpResponse.IsSuccessStatusCode)
            {
                throw new PlayFabHttpException(httpResponse.StatusCode, httpResponse.ReasonPhrase);
            }
        }
Пример #9
0
        internal static async Task <string> DoPost(this PlayFabSettings settings, string apiName, string url, object request, string authType, string authKey)
        {
            string bodyString = null;
            var    serializer = JsonSerializer.Create(settings.JsonSettings);

            if (request == null)
            {
                bodyString = "{}";
            }
            else if (request is String)
            {
                bodyString = (String)request;
            }
            else
            {
                StringWriter jsonString = new StringWriter();
                using (var writer = new JsonTextWriter(jsonString)
                {
                    Formatting = settings.JsonFormatting
                })
                {
                    serializer.Serialize(writer, request);
                    bodyString = jsonString.ToString();
                }
            }

            if (settings.ApiCallback != null)
            {
                settings.ApiCallback(PlayFabApiEvent.SendingRequest, settings, apiName, "POST", url, bodyString);
            }

            HttpResponseMessage httpResponse = null;
            String httpResponseString        = null;

            using (HttpClient client = settings.CreateClient())
                using (ByteArrayContent postBody = new ByteArrayContent(Encoding.UTF8.GetBytes(bodyString)))
                {
                    postBody.Headers.Add("Content-Type", "application/json");
                    if (authType != null)
                    {
                        postBody.Headers.Add(authType, authKey);
                    }
                    postBody.Headers.Add("X-PlayFabSDK", PlayFabVersion.getVersionString());

                    httpResponse = await client.PostAsync(url, postBody);

                    httpResponseString = await httpResponse.Content.ReadAsStringAsync();
                }

            if (settings.ApiCallback != null)
            {
                settings.ApiCallback(PlayFabApiEvent.ReceivedReply, settings, apiName, "POST", url, httpResponseString);
            }

            if (!httpResponse.IsSuccessStatusCode)
            {
                if (String.IsNullOrEmpty(httpResponseString) || httpResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new PlayFabHttpException(httpResponse.StatusCode, httpResponse.ReasonPhrase);
                }

                PlayFabJsonError errorResult = null;

                errorResult = serializer.Deserialize <PlayFabJsonError>(new JsonTextReader(new StringReader(httpResponseString)));

                throw new PlayFabException(errorResult);
            }

            if (String.IsNullOrEmpty(httpResponseString))
            {
                throw new PlayFabException(PlayFabErrorCode.Unknown, "Internal server error");
            }

            return(httpResponseString);
        }
Пример #10
0
        public async Task <object> DoPost(string urlPath, PlayFabRequestCommon request, string authType, string authKey, Dictionary <string, string> extraHeaders)
        {
            var    fullUrl = PlayFabSettings.GetFullUrl(urlPath);
            string bodyString;

            if (request == null)
            {
                bodyString = "{}";
            }
            else
            {
                bodyString = JsonWrapper.SerializeObject(request);
            }

            var client = new HttpClient();
            HttpResponseMessage httpResponse;
            string httpResponseString;

            using (var postBody = new ByteArrayContent(Encoding.UTF8.GetBytes(bodyString)))
            {
                postBody.Headers.Add("Content-Type", "application/json");
                if (authType != null)
                {
                    postBody.Headers.Add(authType, authKey);
                }
                postBody.Headers.Add("X-PlayFabSDK", PlayFabSettings.SdkVersionString);
                if (extraHeaders != null)
                {
                    foreach (var headerPair in extraHeaders)
                    {
                        postBody.Headers.Add(headerPair.Key, headerPair.Value);
                    }
                }

                try
                {
                    httpResponse = await client.PostAsync(fullUrl, postBody);

                    httpResponseString = await httpResponse.Content.ReadAsStringAsync();
                }
                catch (HttpRequestException e)
                {
                    return(new PlayFabError
                    {
                        Error = PlayFabErrorCode.ConnectionError,
                        ErrorMessage = e.InnerException.Message
                    });
                }
                catch (Exception e)
                {
                    return(new PlayFabError
                    {
                        Error = PlayFabErrorCode.ConnectionError,
                        ErrorMessage = e.Message
                    });
                }
            }

            if (!httpResponse.IsSuccessStatusCode)
            {
                var error = new PlayFabError();

                if (string.IsNullOrEmpty(httpResponseString) || httpResponse.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    error.HttpCode   = (int)httpResponse.StatusCode;
                    error.HttpStatus = httpResponse.StatusCode.ToString();
                    return(error);
                }

                PlayFabJsonError errorResult;
                try
                {
                    errorResult = JsonWrapper.DeserializeObject <PlayFabJsonError>(httpResponseString);
                }
                catch (Exception e)
                {
                    error.HttpCode     = (int)httpResponse.StatusCode;
                    error.HttpStatus   = httpResponse.StatusCode.ToString();
                    error.Error        = PlayFabErrorCode.JsonParseError;
                    error.ErrorMessage = e.Message;
                    return(error);
                }

                error.HttpCode     = errorResult.code;
                error.HttpStatus   = errorResult.status;
                error.Error        = (PlayFabErrorCode)errorResult.errorCode;
                error.ErrorMessage = errorResult.errorMessage;
                error.ErrorDetails = errorResult.errorDetails;
                return(error);
            }

            if (string.IsNullOrEmpty(httpResponseString))
            {
                return(new PlayFabError
                {
                    Error = PlayFabErrorCode.Unknown,
                    ErrorMessage = "Internal server error"
                });
            }

            return(httpResponseString);
        }
        public static void HandleResults(string responseStr, string errorStr, out ResultType result, out PlayFabError error)
        {
            result = null;
            error  = null;

            if (errorStr != null)
            {
                error = new PlayFabError();
                if (PlayFabSettings.GlobalErrorHandler != null)
                {
                    PlayFabSettings.GlobalErrorHandler(error);
                }
                return;
            }

            ResultContainer <ResultType> resultEnvelope = new ResultContainer <ResultType>();

            try
            {
                JsonConvert.PopulateObject(responseStr, resultEnvelope, Util.JsonSettings);
            }
            catch (Exception e)
            {
                error              = new PlayFabError();
                error.Error        = PlayFabErrorCode.Unknown;
                error.ErrorMessage = e.ToString();
                if (PlayFabSettings.GlobalErrorHandler != null)
                {
                    PlayFabSettings.GlobalErrorHandler(error);
                }
                return;
            }

            if (resultEnvelope.errorCode.HasValue)
            {
                PlayFabErrorCode errorEnum;
                try
                {
                    errorEnum = (PlayFabErrorCode)resultEnvelope.errorCode.Value;
                }
                catch
                {
                    errorEnum = PlayFabErrorCode.Unknown;
                }

                error = new PlayFabError
                {
                    HttpCode     = resultEnvelope.code,
                    HttpStatus   = resultEnvelope.status,
                    Error        = errorEnum,
                    ErrorMessage = resultEnvelope.errorMessage,
                    ErrorDetails = resultEnvelope.errorDetails
                };
                if (PlayFabSettings.GlobalErrorHandler != null)
                {
                    PlayFabSettings.GlobalErrorHandler(error);
                }

                return;
            }

            result = resultEnvelope.data;
        }
Пример #12
0
        public static void HandleResults(string responseStr, ref PlayFabError pfError, out ResultType result)
        {
            result = null;

            if (pfError != null)
            {
                if (PlayFabSettings.GlobalErrorHandler != null)
                {
                    PlayFabSettings.GlobalErrorHandler(pfError);
                }
                return;
            }

            ResultContainer <ResultType> resultEnvelope = new ResultContainer <ResultType>();

            try
            {
                JsonConvert.PopulateObject(responseStr, resultEnvelope, Util.JsonSettings);
            }
            catch (Exception e)
            {
                pfError              = new PlayFabError();
                pfError.HttpCode     = (int)HttpStatusCode.OK; // Technically we did get a result from the server
                pfError.HttpStatus   = "Client failed to parse response from server";
                pfError.Error        = PlayFabErrorCode.Unknown;
                pfError.ErrorMessage = e.ToString();
                pfError.ErrorDetails = null;
                if (PlayFabSettings.GlobalErrorHandler != null)
                {
                    PlayFabSettings.GlobalErrorHandler(pfError);
                }
                return;
            }

            if (resultEnvelope.errorCode.HasValue)
            {
                PlayFabErrorCode errorEnum;
                try
                {
                    errorEnum = (PlayFabErrorCode)resultEnvelope.errorCode.Value;
                }
                catch
                {
                    errorEnum = PlayFabErrorCode.Unknown;
                }

                pfError = new PlayFabError
                {
                    HttpCode     = resultEnvelope.code,
                    HttpStatus   = resultEnvelope.status,
                    Error        = errorEnum,
                    ErrorMessage = resultEnvelope.errorMessage,
                    ErrorDetails = resultEnvelope.errorDetails
                };
                if (PlayFabSettings.GlobalErrorHandler != null)
                {
                    PlayFabSettings.GlobalErrorHandler(pfError);
                }

                return;
            }

            result = resultEnvelope.data;
        }
Пример #13
0
        protected internal static void MakeApiCall <TResult>(string apiEndpoint, PlayFabRequestCommon request, AuthType authType, Action <TResult> resultCallback, Action <PlayFabError> errorCallback, object customData = null, Dictionary <string, string> extraHeaders = null, bool allowQueueing = false) where TResult : PlayFabResultCommon
        {
            PlayFabHttp.InitializeHttp();
            PlayFabHttp.SendEvent(apiEndpoint, request, null, ApiProcessingEventType.Pre);
            CallRequestContainer reqContainer = new CallRequestContainer
            {
                ApiEndpoint    = apiEndpoint,
                FullUrl        = PlayFabSettings.GetFullUrl(apiEndpoint),
                CustomData     = customData,
                Payload        = Encoding.UTF8.GetBytes(JsonWrapper.SerializeObject(request)),
                ApiRequest     = request,
                ErrorCallback  = errorCallback,
                RequestHeaders = (extraHeaders ?? new Dictionary <string, string>())
            };

            foreach (KeyValuePair <string, string> keyValuePair in PlayFabHttp.GlobalHeaderInjection)
            {
                if (!reqContainer.RequestHeaders.ContainsKey(keyValuePair.Key))
                {
                    reqContainer.RequestHeaders[keyValuePair.Key] = keyValuePair.Value;
                }
            }
            reqContainer.RequestHeaders["X-ReportErrorAsSuccess"] = "true";
            reqContainer.RequestHeaders["X-PlayFabSDK"]           = "UnitySDK-2.39.180409";
            if (authType != AuthType.LoginSession)
            {
                if (authType == AuthType.EntityToken)
                {
                    reqContainer.RequestHeaders["X-EntityToken"] = PlayFabHttp._internalHttp.EntityToken;
                }
            }
            else
            {
                reqContainer.RequestHeaders["X-Authorization"] = PlayFabHttp._internalHttp.AuthKey;
            }
            reqContainer.DeserializeResultJson = delegate()
            {
                reqContainer.ApiResult = JsonWrapper.DeserializeObject <TResult>(reqContainer.JsonResponse);
            };
            reqContainer.InvokeSuccessCallback = delegate()
            {
                if (resultCallback != null)
                {
                    resultCallback((TResult)((object)reqContainer.ApiResult));
                }
            };
            if (allowQueueing && PlayFabHttp._apiCallQueue != null && !PlayFabHttp._internalHttp.SessionStarted)
            {
                for (int i = PlayFabHttp._apiCallQueue.Count - 1; i >= 0; i--)
                {
                    if (PlayFabHttp._apiCallQueue[i].ApiEndpoint == apiEndpoint)
                    {
                        PlayFabHttp._apiCallQueue.RemoveAt(i);
                    }
                }
                PlayFabHttp._apiCallQueue.Add(reqContainer);
            }
            else
            {
                PlayFabHttp._internalHttp.MakeApiCall(reqContainer);
            }
        }
Пример #14
0
        public async Task <object> DoPost(string urlPath, PlayFabRequestCommon request, string authType, string authKey)
        {
            var    fullUrl = PlayFabSettings.GetFullUrl(urlPath);
            string bodyString;

            if (request == null)
            {
                bodyString = "{}";
            }
            else
            {
                bodyString = JsonWrapper.SerializeObject(request);
            }

            var httpClient     = new HttpClient();
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(fullUrl));

            requestMessage.Content = new HttpStringContent(bodyString, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
            if (authType != null)
            {
                requestMessage.Headers.Add(new KeyValuePair <string, string>(authType, authKey));
            }
            requestMessage.Headers.Add(new KeyValuePair <string, string>("X-PlayFabSDK", PlayFabSettings.SdkVersionString));

            HttpResponseMessage httpResponse;
            string httpResponseString;

            try
            {
                httpResponse = await httpClient.SendRequestAsync(requestMessage);

                httpResponseString = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (Exception e)
            {
                return(new PlayFabError
                {
                    Error = PlayFabErrorCode.ConnectionError,
                    ErrorMessage = e.Message
                });
            }

            if (!httpResponse.IsSuccessStatusCode)
            {
                var error = new PlayFabError();

                if (string.IsNullOrEmpty(httpResponseString) || httpResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    error.HttpCode   = (int)httpResponse.StatusCode;
                    error.HttpStatus = httpResponse.StatusCode.ToString();
                    return(error);
                }

                PlayFabJsonError errorResult;
                try
                {
                    errorResult = JsonWrapper.DeserializeObject <PlayFabJsonError>(httpResponseString);
                }
                catch (Exception e)
                {
                    error.HttpCode     = (int)httpResponse.StatusCode;
                    error.HttpStatus   = httpResponse.StatusCode.ToString();
                    error.Error        = PlayFabErrorCode.JsonParseError;
                    error.ErrorMessage = e.Message;
                    return(error);
                }

                error.HttpCode     = errorResult.code;
                error.HttpStatus   = errorResult.status;
                error.Error        = (PlayFabErrorCode)errorResult.errorCode;
                error.ErrorMessage = errorResult.errorMessage;
                error.ErrorDetails = errorResult.errorDetails;
                return(error);
            }

            if (string.IsNullOrEmpty(httpResponseString))
            {
                return(new PlayFabError
                {
                    Error = PlayFabErrorCode.Unknown,
                    ErrorMessage = "Internal server error"
                });
            }

            return(httpResponseString);
        }
Пример #15
0
        public static async Task <object> DoPost(string urlPath, object request, string authType, string authKey)
        {
            string fullUrl    = PlayFabSettings.GetFullUrl(urlPath);
            string bodyString = null;
            var    serializer = JsonSerializer.Create(PlayFabSettings.JsonSettings);

            if (request == null)
            {
                bodyString = "{}";
            }
            else if (request is String)
            {
                bodyString = (String)request;
            }
            else
            {
                StringWriter jsonString = new StringWriter();
                var          writer     = new JsonTextWriter(jsonString)
                {
                    Formatting = PlayFabSettings.JsonFormatting
                };
                serializer.Serialize(writer, request);
                bodyString = jsonString.ToString();
            }

            HttpClient       client   = new HttpClient();
            ByteArrayContent postBody = new ByteArrayContent(Encoding.UTF8.GetBytes(bodyString));

            postBody.Headers.Add("Content-Type", "application/json");
            if (authType != null)
            {
                postBody.Headers.Add(authType, authKey);
            }
            postBody.Headers.Add("X-PlayFabSDK", PlayFabSettings.SdkVersionString);

            HttpResponseMessage httpResponse = null;
            String httpResponseString        = null;

            try
            {
                httpResponse = await client.PostAsync(fullUrl, postBody);

                httpResponseString = await httpResponse.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException e)
            {
                PlayFabError error = new PlayFabError();
                error.Error        = PlayFabErrorCode.ConnectionError;
                error.ErrorMessage = e.InnerException.Message;
                return(error);
            }
            catch (Exception e)
            {
                PlayFabError error = new PlayFabError();
                error.Error        = PlayFabErrorCode.ConnectionError;
                error.ErrorMessage = e.Message;
                return(error);
            }

            if (!httpResponse.IsSuccessStatusCode)
            {
                PlayFabError error = new PlayFabError();

                if (String.IsNullOrEmpty(httpResponseString) || httpResponse.StatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    error.HttpCode   = (int)httpResponse.StatusCode;
                    error.HttpStatus = httpResponse.StatusCode.ToString();
                    return(error);
                }


                PlayFabJsonError errorResult = null;
                try
                {
                    errorResult = serializer.Deserialize <PlayFabJsonError>(new JsonTextReader(new StringReader(httpResponseString)));
                }
                catch (Exception e)
                {
                    error.HttpCode   = (int)httpResponse.StatusCode;
                    error.HttpStatus = httpResponse.StatusCode.ToString();

                    error.Error        = PlayFabErrorCode.JsonParseError;
                    error.ErrorMessage = e.Message;

                    return(error);
                }

                error.HttpCode     = errorResult.code;
                error.HttpStatus   = errorResult.status;
                error.Error        = (PlayFabErrorCode)errorResult.errorCode;
                error.ErrorMessage = errorResult.errorMessage;
                error.ErrorDetails = errorResult.errorDetails;
                return(error);
            }

            if (String.IsNullOrEmpty(httpResponseString))
            {
                PlayFabError error = new PlayFabError();
                error.Error        = PlayFabErrorCode.Unknown;
                error.ErrorMessage = "Internal server error";
                return(error);
            }

            return(httpResponseString);
        }
        public static void HandleResults(string responseStr, string errorStr, out ResultType result, out PlayFabError error)
        {
            result = null;
            error  = null;

            if (errorStr != null)
            {
                error = new PlayFabError();
                if (PlayFabSettings.GlobalErrorHandler != null)
                {
                    PlayFabSettings.GlobalErrorHandler(error);
                }
                return;
            }

            ResultType parsedResult = null;
            Dictionary <String, object> rawResultEnvelope = null;

            try
            {
                rawResultEnvelope = (Dictionary <String, object>)JsonReader.Deserialize(responseStr, Util.GlobalJsonReaderSettings);
                if (rawResultEnvelope.ContainsKey("data"))
                {
                    Dictionary <String, object> rawResult = (Dictionary <String, object>)rawResultEnvelope["data"];
                    parsedResult = new ResultType();
                    parsedResult.Deserialize(rawResult);
                }
            }
            catch (Exception e)
            {
                error              = new PlayFabError();
                error.Error        = PlayFabErrorCode.Unknown;
                error.ErrorMessage = e.ToString();
                if (PlayFabSettings.GlobalErrorHandler != null)
                {
                    PlayFabSettings.GlobalErrorHandler(error);
                }
                return;
            }

            if (rawResultEnvelope.ContainsKey("errorCode"))
            {
                PlayFabErrorCode errorEnum;
                try
                {
                    errorEnum = (PlayFabErrorCode)(int)(double)rawResultEnvelope["errorCode"];
                }
                catch
                {
                    errorEnum = PlayFabErrorCode.Unknown;
                }

                Dictionary <string, List <string> > errorDetails = null;
                if (rawResultEnvelope.ContainsKey("errorDetails"))
                {
                    Dictionary <string, object> rawErrorDetails = (Dictionary <string, object>)rawResultEnvelope["errorDetails"];
                    errorDetails = new Dictionary <string, List <string> > ();
                    foreach (string key in rawErrorDetails.Keys)
                    {
                        object[]      keyErrors = (object[])rawErrorDetails[key];
                        List <string> errorList = new List <string>();
                        for (int i = 0; i < keyErrors.Length; i++)
                        {
                            errorList.Add((string)keyErrors[i]);
                        }
                        errorDetails.Add(key, errorList);
                    }
                }

                error = new PlayFabError
                {
                    HttpCode     = (int)(double)rawResultEnvelope["code"],
                    HttpStatus   = (string)rawResultEnvelope["status"],
                    Error        = errorEnum,
                    ErrorMessage = (string)rawResultEnvelope["errorMessage"],
                    ErrorDetails = errorDetails
                };
                if (PlayFabSettings.GlobalErrorHandler != null)
                {
                    PlayFabSettings.GlobalErrorHandler(error);
                }

                return;
            }

            result = parsedResult;
        }