Example #1
0
        private async Task <HttpCall> SendAndSaveAsync(RestRequest request, IHttpDataWriter outStream, bool retryInvalidToken, CancellationToken token = default(CancellationToken))
        {
            string url     = _instanceUrl + request.Path;
            var    headers = request.AdditionalHeaders != null ? new HttpCallHeaders(_accessToken, request.AdditionalHeaders) : new HttpCallHeaders(_accessToken, new Dictionary <string, string>());

            HttpCall call = await new HttpCall(request.Method, headers, url, request.RequestBody, request.ContentType).ExecuteAndSaveAsync(outStream, token).ConfigureAwait(false);

            if (!call.HasResponse)
            {
                System.Diagnostics.Debug.WriteLine("***HttpCall !call.HasResponse ");
                PlatformAdapter.SendToCustomLogger("HttpCall: no valid response", LoggingLevel.Error);

                throw new NetworkErrorException();
            }

            if (call.StatusCode == HttpStatusCode.Unauthorized || call.StatusCode == HttpStatusCode.Forbidden)
            {
                if (retryInvalidToken && _accessTokenProvider != null)
                {
                    string newAccessToken = await _accessTokenProvider();

                    if (newAccessToken != null)
                    {
                        _accessToken = newAccessToken;
                        call         = await Send(request, false, token);
                    }
                }
            }

            if (call.Success == false && call.HasResponse)
            {
                throw new ErrorResponseException(call);
            }

            return(call);
        }
Example #2
0
        public virtual async Task <bool> SyncDownAndSaveVersionData(Action <string> callbackHandler, IHttpDataWriter outStream, CancellationToken token = default(CancellationToken))
        {
            if (string.IsNullOrWhiteSpace(LatestPublishedVersionId))
            {
                throw new ArgumentNullException("LatestPublishedVersionId in SfdcObject is null/empty.");
            }

            CallBackHandler = callbackHandler;

            var success = false;

            try
            {
                var syncManager = SyncManager.GetInstance(AccountManager.GetAccount());

                var request = RestRequest.GetRequestForVersionDataDownload(SfdcApiVersion, LatestPublishedVersionId);

                var binResponse = await syncManager.SendRestRequestAndSaveBinary(request, outStream, token);

                success = binResponse.Success;
            }
            catch (SmartStoreException sse)
            {
                CreateLogItem("SmartStoreException", sse);
            }
            catch (OperationCanceledException oce)
            {
                CreateLogItem("OperationCanceledException", oce);
                throw;
            }
            catch (ErrorResponseException ere)
            {
                CreateLogItem("ErrorResponseException", ere);
                throw;
            }
            catch (NetworkErrorException nee)
            {
                CreateLogItem("NetworkErrorException", nee);
                throw;
            }
            catch (Exception e)
            {
                CreateLogItem("General exception", e);
            }

            return(success);
        }
Example #3
0
 public async Task <RestBinaryResponseSaved> SendRestRequestAndSaveBinary(RestRequest request, IHttpDataWriter outStream, CancellationToken token = default(CancellationToken))
 {
     return(await RestClient.SendAndSaveAsync(request, outStream, token));
 }
Example #4
0
        public async Task <RestBinaryResponseSaved> SendAndSaveAsync(RestRequest request, IHttpDataWriter outStream, CancellationToken token = default(CancellationToken))
        {
            HttpCall result = await SendAndSaveAsync(request, outStream, true, token);

            return(new RestBinaryResponseSaved(result));
        }
Example #5
0
        public async Task <HttpCall> ExecuteAndSaveAsync(IHttpDataWriter writer, CancellationToken token = default(CancellationToken))
        {
            if (Executed)
            {
                throw new InvalidOperationException("A HttpCall can only be executed once");
            }
            var req = new HttpRequestMessage(_method, new Uri(_url));

            // Setting header
            if (_headers != null)
            {
                if (_headers.Authorization != null)
                {
                    req.Headers.Authorization = _headers.Authorization;
                }
                foreach (var item in _headers.Headers)
                {
                    req.Headers[item.Key] = item.Value;
                }
            }
            // if the user agent has not yet been set, set it; we want to make sure this only really happens once since it requires an action that goes to the core thread.
            if (String.IsNullOrWhiteSpace(UserAgentHeader))
            {
                var task = new TaskCompletionSource <string>();
                await Task.Run(async() =>
                {
                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
                        CoreDispatcherPriority.Normal, async() =>
                    {
                        await GenerateUserAgentHeader();
                        task.SetResult(UserAgentHeader);
                    });
                }, token);

                await task.Task;
            }

            req.Headers.UserAgent.TryParseAdd(UserAgentHeader);
            if (!String.IsNullOrWhiteSpace(_requestBody))
            {
                switch (_contentType)
                {
                case ContentTypeValues.FormUrlEncoded:
                    req.Content = new HttpFormUrlEncodedContent(_requestBody.ParseQueryString());
                    break;

                default:
                    req.Content = new HttpStringContent(_requestBody);
                    req.Content.Headers.ContentType = new HttpMediaTypeHeaderValue(_contentType.MimeType());
                    break;
                }
            }

            // Performance adds
            HttpResponseMessage message;

            if (token.IsCancellationRequested)
            {
                token.ThrowIfCancellationRequested();
            }

            try
            {
                message = await _webClient.SendRequestAsync(req, HttpCompletionOption.ResponseHeadersRead).AsTask(token);

                await writer.PushToStreamAsync(message.Content.WriteToStreamAsync, message.Content);

                HandleMessageResponseForBinary(message);
            }
            catch (OperationCanceledException oce)
            {
                PlatformAdapter.SendToCustomLogger(oce, LoggingLevel.Error);
                throw;
            }
            catch (Exception ex)
            {
                PlatformAdapter.SendToCustomLogger(ex, LoggingLevel.Error);
                _httpCallErrorException = ex;
                message = null;
            }
            return(this);
        }