Ejemplo n.º 1
0
        public FoundationResponse(NSData responseData, NSHttpUrlResponse urlResponse)
        {
            statusCode = urlResponse.StatusCode;

            var mutableData = responseData as NSMutableData;

            if (mutableData != null)
            {
                unsafe {
                    stream = new UnmanagedMemoryStream((byte *)mutableData.Bytes, mutableData.Length);
                }
            }
            else
            {
                stream = responseData.AsStream();
            }

            headers = new Dictionary <string, string> ();
            var hs = urlResponse.AllHeaderFields;

            foreach (var k in hs.Keys)
            {
                headers[k.ToString()] = hs.ObjectForKey(k).ToString();
            }
        }
Ejemplo n.º 2
0
            public override void StartLoading()
            {
                var    hasResult = false;
                object result    = null;

                lock (Bridges)
                {
                    if (Bridges.FirstOrDefault(
                            bridge =>
                            !string.IsNullOrWhiteSpace(bridge.Protocol) &&
                            Request.Url.ToString().StartsWith(bridge.Protocol))?
                        .HandleRequestUrl(Request.Url.ToString(), out hasResult, out result) != true)
                    {
                        return;
                    }
                }
                var response = new NSHttpUrlResponse(Request.Url, 200, "1.1",
                                                     NSDictionary.FromObjectsAndKeys(
                                                         new object[] { "Access-Control-Allow-Origin", "Access-Control-Allow-Headers" },
                                                         new object[] { "*", "Content-Type" }));

                Client.ReceivedResponse(this, response, NSUrlCacheStoragePolicy.NotAllowed);
                Client.DataLoaded(this, NSData.FromString(hasResult ? JsonConvert.SerializeObject(result) : ""));
                Client.FinishedLoading(this);
            }
Ejemplo n.º 3
0
        public FoundationResponse(NSData responseData, NSHttpUrlResponse urlResponse)
        {
            data       = responseData;
            statusCode = urlResponse.StatusCode;

            headers = new Dictionary <string, string> ();
            var hs = urlResponse.AllHeaderFields;

            foreach (var k in hs.Keys)
            {
                var o = hs.ObjectForKey(k);
                if (k == null || o == null)
                {
                    continue;
                }

                var key = k.ToString();
                if (key == null)
                {
                    continue;
                }

                headers[key] = o.ToString();
            }
        }
		public FoundationResponse (NSData responseData, NSHttpUrlResponse urlResponse)
		{
			data = responseData;
			statusCode = urlResponse.StatusCode;

			headers = new Dictionary<string, string> ();
			var hs = urlResponse.AllHeaderFields;
			foreach (var k in hs.Keys) {
				headers[k.ToString ()] = hs.ObjectForKey (k).ToString ();
			}
		}
Ejemplo n.º 5
0
 void HandleError(string error, NSHttpUrlResponse response)
 {
     if (response != null)
     {
         string msg = string.Format("Remote service returned error {0}. Status: {1}, Description: {2}", error, response.StatusCode, response.Description);
         _wrapper.Error = new CacheControllerWebException(msg, (HttpStatusCode)response.StatusCode);
     }
     else
     {
         _wrapper.Error = new CacheControllerException(error);
     }
 }
Ejemplo n.º 6
0
        public FoundationResponse(NSData responseData, NSHttpUrlResponse urlResponse)
        {
            data       = responseData;
            statusCode = urlResponse.StatusCode;

            headers = new Dictionary <string, string> ();
            var hs = urlResponse.AllHeaderFields;

            foreach (var k in hs.Keys)
            {
                headers[k.ToString()] = hs.ObjectForKey(k).ToString();
            }
        }
Ejemplo n.º 7
0
        public override void DecidePolicy(WKWebView webView, WKNavigationResponse navigationResponse, Action <WKNavigationResponsePolicy> decisionHandler)
        {
            NSHttpUrlResponse response = navigationResponse.Response as NSHttpUrlResponse;

            NSHttpCookie[] cookies = NSHttpCookie.CookiesWithResponseHeaderFields(response.AllHeaderFields, response.Url);

            foreach (NSHttpCookie cookie in cookies)
            {
                NSHttpCookieStorage.SharedStorage.SetCookie(cookie);
            }

            decisionHandler(WKNavigationResponsePolicy.Allow);
        }
Ejemplo n.º 8
0
        public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            Console.WriteLine(string.Format("DidCompleteWithError TaskId: {0}{1}", task.TaskIdentifier, (error == null ? "" : " Error: " + error.Description)));

            NSString          dataString    = NSString.FromData(_data, NSStringEncoding.UTF8);
            var               message       = dataString == null ? string.Empty : $"{dataString}";
            var               responseError = false;
            NSHttpUrlResponse response      = null;

            if (task.Response is NSHttpUrlResponse)
            {
                response = task.Response as NSHttpUrlResponse;
                Console.WriteLine("HTTP Response {0}", response);
                Console.WriteLine("HTTP Status {0}", response.StatusCode);
                responseError = response.StatusCode != 200 && response.StatusCode != 201;
            }

            System.Diagnostics.Debug.WriteLine("COMPLETE");

            //Remove the temporal multipart file
            if (File.Exists(multiPartPath))
            {
                File.Delete(multiPartPath);
            }

            if (error == null && !responseError)
            {
                var fileUploadResponse = new FileUploadResponse(message, (int)response?.StatusCode, tag);
                uploadCompletionSource.SetResult(fileUploadResponse);
                FileUploadCompleted(this, fileUploadResponse);
            }
            else if (responseError)
            {
                var fileUploadResponse = new FileUploadResponse(message, (int)response?.StatusCode, tag);
                uploadCompletionSource.SetResult(fileUploadResponse);
                FileUploadError(this, fileUploadResponse);
            }
            else
            {
                var fileUploadResponse = new FileUploadResponse(error.Description, (int)response?.StatusCode, tag);
                uploadCompletionSource.SetResult(fileUploadResponse);
                FileUploadError(this, fileUploadResponse);
            }

            _data = new NSMutableData();
        }
Ejemplo n.º 9
0
            public void StartUrlSchemeTask(WKWebView webView, IWKUrlSchemeTask urlSchemeTask)
            {
                var responseBytes = GetResponseBytes(urlSchemeTask.Request.Url.AbsoluteString, out var contentType, statusCode: out var statusCode);

                if (statusCode == 200)
                {
                    using (var dic = new NSMutableDictionary <NSString, NSString>())
                    {
                        dic.Add((NSString)"Content-Length", (NSString)(responseBytes.Length.ToString(CultureInfo.InvariantCulture)));
                        dic.Add((NSString)"Content-Type", (NSString)contentType);
                        // Disable local caching. This will prevent user scripts from executing correctly.
                        dic.Add((NSString)"Cache-Control", (NSString)"no-cache, max-age=0, must-revalidate, no-store");
                        using var response = new NSHttpUrlResponse(urlSchemeTask.Request.Url, statusCode, "HTTP/1.1", dic);
                        urlSchemeTask.DidReceiveResponse(response);
                    }
                    urlSchemeTask.DidReceiveData(NSData.FromArray(responseBytes));
                    urlSchemeTask.DidFinish();
                }
            }
Ejemplo n.º 10
0
		public FoundationResponse (NSData responseData, NSHttpUrlResponse urlResponse)
		{
			data = responseData;
			statusCode = urlResponse.StatusCode;

			headers = new Dictionary<string, string> ();
			var hs = urlResponse.AllHeaderFields;
			foreach (var k in hs.Keys) {
				var o = hs.ObjectForKey (k);
				if (k == null || o == null)
					continue;

				var key = k.ToString ();
				if (key == null)
					continue;

				headers[key] = o.ToString ();
			}
		}
Ejemplo n.º 11
0
        private void PubliceRequestMethod(NSMutableUrlRequest request)
        {
            NSError err;
            // 设置header
            NSMutableDictionary header = new NSMutableDictionary();

            header.SetValueForKey((NSString)"application/json; charset=utf-8", (NSString)"Content-Type");
            request.Headers = header;

            NSUrlSession session = NSUrlSession.FromConfiguration(NSUrlSessionConfiguration.DefaultSessionConfiguration, (INSUrlSessionDelegate)this, NSOperationQueue.CurrentQueue);

            NSUrlSessionDataTask task = session.CreateDataTask(request, (data, response, error) =>
            {
                if (error != null)
                {
                    Console.WriteLine(error.Description);
                }
                else
                {
                    NSHttpUrlResponse resp = (NSHttpUrlResponse)response;
                    NSDictionary dicData   = (NSDictionary)NSJsonSerialization.Deserialize(data, NSJsonReadingOptions.MutableLeaves, out err);
                    if (dicData == null)
                    {
                        return;
                    }
                    NSObject code = dicData.ValueForKey((NSString)"code");
                    if (resp.StatusCode == 200 && code.ToString().Equals("0"))
                    {
                        NetworkHelperRDelegate(dicData, resp, null);
                        Console.WriteLine(resp.Description);
                    }
                    else
                    {
                        NetworkHelperRDelegate(dicData, resp, err);
                        string message = dicData.ValueForKey((NSString)"message").ToString();
                        Console.WriteLine(dicData.Description);
                    }
                }
            });

            task.Resume();
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Starts a task that handles the retrieval of the resource.
        /// </summary>
        /// <param name="webView">The webview to use.</param>
        /// <param name="urlSchemeTask">The scheme task status object.</param>
        public void StartUrlSchemeTask(WKWebView webView, IWKUrlSchemeTask urlSchemeTask)
        {
            var url = urlSchemeTask.Request.Url;

            var stream = this.requestHandler(url.AbsoluteString, out string contentType, out Encoding encoding);

            NSDictionary headers = new NSMutableDictionary();

            headers.SetValueForKey((NSString)contentType, (NSString)"Content-Type");
            headers.SetValueForKey((NSString)"no-cache", (NSString)"Cache-Control");
            var response = new NSHttpUrlResponse(url, stream != null ? 200 : 404, "HTTP/1.1", headers);

            urlSchemeTask.DidReceiveResponse(response);
            if (stream != null)
            {
                urlSchemeTask.DidReceiveData(NSData.FromStream(stream));
            }

            urlSchemeTask.DidFinish();
        }
		private void BlockForAlbumProcessing (NSUrlRequest request, NSHttpUrlResponse response, NSDictionary json)
		{
			NSArray data = (NSArray)json.ObjectForKey (new NSString("shots"));

			var photos = new List<PhotoInfo> ();

			for (var x = 0; x < data.Count; x++) {
				var photo = new NSDictionary (data.ValueAt((uint)x));

				// Gather the high-quality photo information.
				var originalImageSource = (NSString)photo.ObjectForKey (new NSString("image_url"));
				var thumbnailImageSource = (NSString)photo.ObjectForKey (new NSString("image_teaser_url"));
				var width = (NSNumber)photo.ObjectForKey (new NSString("width"));
				var height = (NSNumber)photo.ObjectForKey (new NSString("height"));

				// We gather the highest-quality photo's dimensions so that we can size the thumbnails
				// correctly until the high-quality image is downloaded.
				var dimensions = new SizeF (width.Int32Value, height.Int32Value);

				photos.Add (new PhotoInfo{
					OriginalSource = originalImageSource.ToString(),
					ThumbnailSoruce = thumbnailImageSource.ToString(),
					Dimensions = dimensions
				});
			}

			_photos = photos;

			if(ScrubberIsEnabled)
				LoadThumbnails ();

			_albumDataSource.Photos = _photos;
			_scrubberDataSource.Photos = _photos;

			PhotoAlbumView.ReloadData ();
			if (PhotoScrubberView != null)
				PhotoScrubberView.ReloadData ();

			RefreshChromeState ();
		}
        public void DecidePolicy(WKWebView webView, WKNavigationResponse navigationResponse, Action <WKNavigationResponsePolicy> decisionHandler)
        {
            if (navigationResponse.Response.GetType() == typeof(NSHttpUrlResponse))
            {
                NSHttpUrlResponse response = (NSHttpUrlResponse)navigationResponse.Response;
                if (response.StatusCode >= 400)
                {
                    // The navigation request resulted in an error.
                    SetTaskResult(null, new HealthServiceException(ClientResources.LoginErrorWithCode.FormatResource(response.StatusCode)));

                    return;
                }

                string url = response.Url.AbsoluteString;

                if (url.Contains(_endUrlString))
                {
                    SetTaskResult(new Uri(url), null);
                }
            }

            decisionHandler(WKNavigationResponsePolicy.Allow);
        }
Ejemplo n.º 15
0
 public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action <NSUrlRequest> completionHandler)
 {
     completionHandler(sessionHandler.AllowAutoRedirect ? newRequest : null);
 }
Ejemplo n.º 16
0
        void OnDownloadCompleted(object sender, NSUrlEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    _filePath = e.FilePath.Replace("file://", "").Replace("%20", " ");

                    NSHttpUrlResponse response = (NSHttpUrlResponse)_currentTask.Response;
                    if (response != null)
                    {
                        HttpStatusCode code = (HttpStatusCode)response.StatusCode;
                        if (code == HttpStatusCode.OK)
                        {
                            NSDictionary headers = response.AllHeaderFields;
                            if (string.IsNullOrWhiteSpace(_behaviors.UserId))
                            {
                                _behaviors.UserId = headers["userid"].ToString();
                            }
                            if (string.IsNullOrWhiteSpace(_behaviors.UserEmail))
                            {
                                _behaviors.UserEmail = headers["email"].ToString();
                            }
                            _behaviors.ResourceVersion = headers["resourceversion"].ToString();

                            _behaviors.SaveUserSession();

                            IIOContext io = IOContext.Current;
                            if (io.Exists(_filePath))
                            {
                                FileStream fileStream = io.FileStream(_filePath, FileMode.Open);

                                fileStream.Seek(0, SeekOrigin.Begin);
                                int contentLength;
                                if (!int.TryParse(headers["unzippedcontentlength"].ToString(), out contentLength))
                                {
                                    contentLength = -1;
                                }
                                Stream responseStream = new ProgressStream(fileStream, contentLength, _behaviors.ReadProgressCallback);

                                // CreateInstance the SyncReader
                                if (ApplicationContext.Current.Settings.BitMobileFormatterDisabled)
                                {
                                    _syncReader = new ODataAtomReader(responseStream, _knownTypes);
                                }
                                else
                                {
                                    _syncReader = new BMReader(responseStream, _knownTypes);
                                }

                                _wrapper.DownloadResponse      = new ChangeSet();
                                _wrapper.DownloadResponse.Data = GetDownloadedValues(_wrapper);
                            }
                            else
                            {
                                _wrapper.Error = new FileNotFoundException(String.Format("Downloaded data file not found! {0}, Description: {1}", e.FilePath, response.Description));
                            }
                        }
                        else
                        {
                            _wrapper.Error = new CacheControllerWebException(string.Format("Remote service returned error status. Status: {0}, Description: {1}", code, response.Description), code);
                        }
                    }
                    else
                    {
                        _wrapper.Error = new CacheControllerException("Response is null");
                    }
                }
                else
                {
                    var response = _currentTask.Response as NSHttpUrlResponse;
                    HandleError(e.Error, response);
                }

                // If we get here then it means we completed the request. Return to the original caller
                _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper);
            }
            catch (Exception ex)
            {
                if (ExceptionUtility.IsFatal(ex))
                {
                    throw;
                }

                _wrapper.Error = ex;

                _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper);
            }
        }
Ejemplo n.º 17
0
 void HandleError(string error, NSHttpUrlResponse response)
 {
     if (response != null)
     {
         string msg = string.Format("Remote service returned error {0}. Status: {1}, Description: {2}", error, response.StatusCode, response.Description);
         _wrapper.Error = new CacheControllerWebException(msg, (HttpStatusCode)response.StatusCode);
     }
     else
         _wrapper.Error = new CacheControllerException(error);
 }
Ejemplo n.º 18
0
        public override void DidCompleteWithError(NSUrlSession session, NSUrlSessionTask task, NSError error)
        {
            Console.WriteLine(string.Format("DidCompleteWithError TaskId: {0}{1}", task.TaskIdentifier, (error == null ? "" : " Error: " + error.Description)));
            NSMutableData _data = null;

            if (uploadData.ContainsKey(task.TaskIdentifier))
            {
                _data = uploadData[task.TaskIdentifier];
                uploadData.Remove(task.TaskIdentifier);
            }
            else
            {
                _data = new NSMutableData();
            }

            NSString          dataString    = NSString.FromData(_data, NSStringEncoding.UTF8);
            var               message       = dataString == null ? string.Empty : $"{dataString}";
            var               responseError = false;
            NSHttpUrlResponse response      = null;

            string[] parts = task.TaskDescription.Split('|');

            if (task.Response is NSHttpUrlResponse)
            {
                response = task.Response as NSHttpUrlResponse;
                Console.WriteLine("HTTP Response {0}", response);
                Console.WriteLine("HTTP Status {0}", response.StatusCode);
                responseError = response.StatusCode != 200 && response.StatusCode != 201;
            }

            System.Diagnostics.Debug.WriteLine("COMPLETE");

            //Remove the temporal multipart file
            if (parts != null && parts.Length > 0 && File.Exists(parts[1]))
            {
                File.Delete(parts[1]);
            }

            if (parts == null || parts.Length == 0)
            {
                parts = new string[] { string.Empty, string.Empty }
            }
            ;

            IDictionary <string, string> responseHeaders = new Dictionary <string, string>();
            var rHeaders = response.AllHeaderFields;

            if (rHeaders != null)
            {
                foreach (var rHeader in rHeaders)
                {
                    if (!string.IsNullOrEmpty($"{rHeader.Value}"))
                    {
                        responseHeaders.Add($"{rHeader.Key}", $"{rHeader.Value}");
                    }
                }
            }

            if (error == null && !responseError)
            {
                var fileUploadResponse = new FileUploadResponse(message, (int)response?.StatusCode, parts[0], new ReadOnlyDictionary <string, string>(responseHeaders));
                uploadCompletionSource.TrySetResult(fileUploadResponse);
                FileUploadCompleted(this, fileUploadResponse);
            }
            else if (responseError)
            {
                var fileUploadResponse = new FileUploadResponse(message, (int)response?.StatusCode, parts[0], new ReadOnlyDictionary <string, string>(responseHeaders));
                uploadCompletionSource.TrySetResult(fileUploadResponse);
                FileUploadError(this, fileUploadResponse);
            }
            else
            {
                var fileUploadResponse = new FileUploadResponse(error.Description, (int)response?.StatusCode, parts[0], new ReadOnlyDictionary <string, string>(responseHeaders));
                uploadCompletionSource.TrySetResult(fileUploadResponse);
                FileUploadError(this, fileUploadResponse);
            }

            _data = null;
        }
Ejemplo n.º 19
0
        public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action <NSUrlRequest> completionHandler)
        {
            var nextRequest = _secureHttpClientHandler.AllowAutoRedirect ? newRequest : null;

            completionHandler(nextRequest);
        }
Ejemplo n.º 20
0
 public virtual void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action <NSUrlRequest> completionHandler)
 {
     State = -1;
     completionHandler(newRequest);
 }
Ejemplo n.º 21
0
        void OnUploadCompleted(object sender, NSUrlEventArgs e)
        {
            _wrapper.UploadResponse = new ChangeSetResponse();

            FileStream fileStream = null;

            string filePath = null;

            try {
                if (e.Error == null)
                {
                    string            responseDescription = "response is  null";
                    NSHttpUrlResponse response            = (NSHttpUrlResponse)_currentTask.Response;
                    if (response != null)
                    {
                        responseDescription = response.Description;
                    }

                    filePath = e.FilePath.Replace("file://", "").Replace("%20", " ");
                    if (File.Exists(filePath))
                    {
                        fileStream = File.OpenRead(filePath);
                        fileStream.Seek(0, SeekOrigin.Begin);

                        // Create the SyncReader
                        _syncReader = (SyncReader) new ODataAtomReader(fileStream, _knownTypes);

                        // Read the response
                        while (_syncReader.Next())
                        {
                            switch (_syncReader.ItemType)
                            {
                            case ReaderItemType.Entry:
                                IOfflineEntity entity      = _syncReader.GetItem();
                                IOfflineEntity ackedEntity = entity;
                                string         tempId      = null;

                                if (_syncReader.HasTempId() && _syncReader.HasConflictTempId())
                                {
                                    throw new CacheControllerException(string.Format("Service returned a TempId '{0}' in both live and conflicting entities.",
                                                                                     _syncReader.GetTempId()));
                                }

                                if (_syncReader.HasTempId())
                                {
                                    tempId = _syncReader.GetTempId();
                                    CheckEntityServiceMetadataAndTempIds(entity, tempId);
                                }

                                if (_syncReader.HasConflict())
                                {
                                    Conflict       conflict       = _syncReader.GetConflict();
                                    IOfflineEntity conflictEntity = (conflict is SyncConflict) ?
                                                                    ((SyncConflict)conflict).LosingEntity : ((SyncError)conflict).ErrorEntity;

                                    if (this._syncReader.HasConflictTempId())
                                    {
                                        tempId = _syncReader.GetConflictTempId();
                                        CheckEntityServiceMetadataAndTempIds(conflictEntity, tempId);
                                    }

                                    _wrapper.UploadResponse.AddConflict(conflict);

                                    if (_syncReader.HasConflictTempId() && entity.ServiceMetadata.IsTombstone)
                                    {
                                        conflictEntity.ServiceMetadata.IsTombstone = true;
                                        ackedEntity = conflictEntity;
                                    }
                                }

                                if (!String.IsNullOrEmpty(tempId))
                                {
                                    _wrapper.UploadResponse.AddUpdatedItem(ackedEntity);
                                }

                                break;

                            case ReaderItemType.SyncBlob:
                                _wrapper.UploadResponse.ServerBlob = _syncReader.GetServerBlob();
                                break;
                            }
                        }

                        if (_wrapper.TempIdToEntityMapping != null && _wrapper.TempIdToEntityMapping.Count != 0)
                        {
                            StringBuilder builder = new StringBuilder("Server did not acknowledge with a permanent Id for the following tempId's: ");
                            builder.Append(string.Join(",", _wrapper.TempIdToEntityMapping.Keys.ToArray()));
                            throw new CacheControllerException(builder.ToString());
                        }
                    }
                    else
                    {
                        _wrapper.Error = new FileNotFoundException(String.Format("Downloaded data file not found! {0}, Description: {1}", e.FilePath, responseDescription));
                    }
                }
                else
                {
                    NSHttpUrlResponse response = _currentTask.Response as NSHttpUrlResponse;
                    HandleError(e.Error, response);
                }

                _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper);
            } catch (Exception ex) {
                if (ExceptionUtility.IsFatal(ex))
                {
                    throw ex;
                }

                _wrapper.Error = ex;

                _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper);
            } finally {
                if (fileStream != null)
                {
                    fileStream.Close();
                }

                if (filePath != null && File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }
        }
		public override void WillPerformHttpRedirection (NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action<NSUrlRequest> completionHandler)
		{
			Console.WriteLine("[NSUrlSessionManager] WillPerformHttpRedirection");
		}
Ejemplo n.º 23
0
 public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action <NSUrlRequest> completionHandler)
 {
     Console.WriteLine("[NSUrlSessionManager] WillPerformHttpRedirection");
 }
Ejemplo n.º 24
0
        void OnDownloadCompleted(object sender, NSUrlEventArgs e)
        {
            FileStream fileStream = null;
            string     filePath   = null;

            try {
                if (e.Error == null)
                {
                    filePath = e.FilePath.Replace("file://", "").Replace("%20", " ");

                    NSHttpUrlResponse response = (NSHttpUrlResponse)_currentTask.Response;
                    if (response != null)
                    {
                        HttpStatusCode code = (HttpStatusCode)response.StatusCode;
                        if (code == HttpStatusCode.OK)
                        {
                            NSDictionary headers = response.AllHeaderFields;
                            if (string.IsNullOrWhiteSpace(_behaviors.UserId))
                            {
                                _behaviors.UserId = headers ["userid"].ToString();
                            }
                            if (string.IsNullOrWhiteSpace(_behaviors.UserEmail))
                            {
                                _behaviors.UserEmail = headers ["email"].ToString();
                            }
                            ;
                            _behaviors.SaveUserSession();

                            if (File.Exists(filePath))
                            {
                                fileStream = File.OpenRead(filePath);

                                fileStream.Seek(0, SeekOrigin.Begin);
                                int contentLength;
                                if (!int.TryParse(headers ["unzippedcontentlength"].ToString(), out contentLength))
                                {
                                    contentLength = -1;
                                }
                                Stream responseStream = new ProgressStream(fileStream, contentLength, _behaviors.ReadProgressCallback);

                                // Create the SyncReader
                                _syncReader = (SyncReader) new ODataAtomReader(responseStream, _knownTypes);

                                _wrapper.DownloadResponse = new ChangeSet();

                                // Read the response
                                while (this._syncReader.Next())
                                {
                                    switch (this._syncReader.ItemType)
                                    {
                                    case ReaderItemType.Entry:
                                        _wrapper.DownloadResponse.AddItem(_syncReader.GetItem());
                                        break;

                                    case ReaderItemType.SyncBlob:
                                        _wrapper.DownloadResponse.ServerBlob = _syncReader.GetServerBlob();
                                        break;

                                    case ReaderItemType.HasMoreChanges:
                                        _wrapper.DownloadResponse.IsLastBatch = !_syncReader.GetHasMoreChangesValue();
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                _wrapper.Error = new FileNotFoundException(String.Format("Downloaded data file not found! {0}, Description: {1}", e.FilePath, response.Description));
                            }
                        }
                        else
                        {
                            _wrapper.Error = new CacheControllerWebException(string.Format("Remote service returned error status. Status: {0}, Description: {1}", code, response.Description), code);
                        }
                    }
                    else
                    {
                        _wrapper.Error = new CacheControllerException("Response is null");
                    }
                }
                else
                {
                    NSHttpUrlResponse response = _currentTask.Response as NSHttpUrlResponse;
                    HandleError(e.Error, response);
                }

                // If we get here then it means we completed the request. Return to the original caller
                _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper);
            } catch (Exception ex) {
                if (ExceptionUtility.IsFatal(ex))
                {
                    throw;
                }

                _wrapper.Error = ex;

                _workerManager.CompleteWorkRequest(_wrapper.WorkerRequest, _wrapper);
            } finally {
                if (fileStream != null)
                {
                    fileStream.Close();
                }

                if (filePath != null && File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
            }
        }
 public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action <NSUrlRequest> completionHandler)
 {
     if (this.This.AllowAutoRedirect)
     {
         completionHandler(newRequest);
     }
     else
     {
         completionHandler(null);
     }
 }
Ejemplo n.º 26
0
 public virtual void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, [BlockProxy(typeof(Trampolines.NIDActionArity1V1))] Action <NSUrlRequest> completionHandler)
 {
     throw new NotImplementedException();
 }
        //this is a test
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
        {
            var urlRequest = new NSMutableUrlRequest
            {
                HttpMethod           = request.Method.Method,
                Url                  = NSUrl.FromString(request.RequestUri.AbsoluteUri),
                AllowsCellularAccess = true,
            };


            var dictionary = new NSMutableDictionary();

            if (request.Headers != null && request.Headers.Count() > 0)
            {
                foreach (var item in request.Headers)
                {
                    dictionary.SetValueForKey((NSString)item.Value.First(), (NSString)item.Key);
                }
            }

            if (request.Content != null)
            {
                foreach (var item in request.Content.Headers)
                {
                    dictionary.SetValueForKey((NSString)item.Value.First(), (NSString)item.Key);
                }
            }

            urlRequest.Headers = dictionary;

            if (request.Content != null)
            {
                using (Stream requestStream = await request.Content.ReadAsStreamAsync())
                {
                    urlRequest.Body = NSData.FromStream(requestStream);
                }
            }

            try
            {
                NSUrlAsyncResult response = await NSUrlConnection.SendRequestAsync(urlRequest, NSOperationQueue.MainQueue);

                NSHttpUrlResponse httpResponse = response.Response as NSHttpUrlResponse;

                HttpContent responseContent = null;

                if (response.Data == null)
                {
                    responseContent = new StringContent("");
                }

                else
                {
                    responseContent = new StreamContent(response.Data.AsStream());
                }

                HttpResponseMessage responseMessage = new HttpResponseMessage
                {
                    Content        = responseContent,
                    RequestMessage = request,
                    StatusCode     = (HttpStatusCode)int.Parse(httpResponse.StatusCode.ToString())
                };

                var headers = (from p in httpResponse.AllHeaderFields.Keys
                               let key = p.ToString()
                                         let val = httpResponse.AllHeaderFields[p].ToString()
                                                   orderby key
                                                   select new KeyValuePair <string, string>(key, val)).ToList();

                SetHeaders(headers, responseMessage);

                return(responseMessage);
            }

            catch (NSErrorException ex)
            {
                throw new HttpRequestException(ex.Error.LocalizedDescription, ex);
            }

            catch (Exception ex)
            {
                throw new HttpRequestException("An error occurred while sending the request.", ex);
            }
        }
Ejemplo n.º 28
0
 public virtual void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action <NSUrlRequest> completionHandler)
 {
     Console.WriteLine("Redirecting request");
     completionHandler(newRequest);
 }
Ejemplo n.º 29
0
 public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action<NSUrlRequest> completionHandler)
 {
     NSUrlRequest nextRequest = (This.AllowAutoRedirect ? newRequest : null);
     completionHandler(nextRequest);
 }
 public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action<NSUrlRequest> completionHandler)
 {
     // No handle?
 }