コード例 #1
0
ファイル: RestClient.Async.cs プロジェクト: zyj0021/RestSharp
        private static void ProcessResponse(IRestRequest request, HttpResponse httpResponse,
                                            RestRequestAsyncHandle asyncHandle, Action <IRestResponse, RestRequestAsyncHandle> callback)
        {
            var restResponse = ConvertToRestResponse(request, httpResponse);

            callback(restResponse, asyncHandle);
        }
コード例 #2
0
        /// <summary>
        /// Executes the request and callback asynchronously, authenticating if needed
        /// </summary>
        /// <param name="request">Request to be executed</param>
        /// <param name="callback">Callback function to be executed upon completion providing access to the async handle.</param>
        public virtual RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action <IRestResponse, RestRequestAsyncHandle> callback)
        {
            var http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);

            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);

            ConfigureHttp(request, http);

            HttpWebRequest webRequest  = null;
            var            asyncHandle = new RestRequestAsyncHandle();

            Action <HttpResponse> response_cb = r => ProcessResponse(request, r, asyncHandle, callback);

            if (UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                var ctx = SynchronizationContext.Current;
                var cb  = response_cb;

                response_cb = resp => ctx.Post(s => cb(resp), null);
            }

            switch (request.Method)
            {
            case Method.GET:
                webRequest = http.GetAsync(response_cb);
                break;

            case Method.POST:
                webRequest = http.PostAsync(response_cb);
                break;

            case Method.PUT:
                webRequest = http.PutAsync(response_cb);
                break;

            case Method.DELETE:
                webRequest = http.DeleteAsync(response_cb);
                break;

            case Method.HEAD:
                webRequest = http.HeadAsync(response_cb);
                break;

            case Method.OPTIONS:
                webRequest = http.OptionsAsync(response_cb);
                break;

            case Method.PATCH:
                webRequest = http.PatchAsync(response_cb);
                break;
            }

            asyncHandle.WebRequest = webRequest;
            return(asyncHandle);
        }
コード例 #3
0
        private RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action <IRestResponse, RestRequestAsyncHandle> callback, string httpMethod, Func <IHttp, Action <HttpResponse>, string, HttpWebRequest> getWebRequest)
        {
            var http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);

            // add Accept header based on registered deserializers
            var accepts = string.Join(", ", AcceptTypes.ToArray());

            this.AddDefaultParameter("Accept", accepts, ParameterType.HttpHeader);

            ConfigureHttp(request, http);

            var asyncHandle = new RestRequestAsyncHandle();

            Action <HttpResponse> response_cb = r => ProcessResponse(request, r, asyncHandle, callback);

            if (UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                var ctx = SynchronizationContext.Current;
                var cb  = response_cb;

                response_cb = resp => ctx.Post(s => cb(resp), null);
            }

            asyncHandle.WebRequest = getWebRequest(http, response_cb, httpMethod);
            return(asyncHandle);
        }
コード例 #4
0
 void DeserializeResponse <T>(
     IRestRequest request,
     Action <IRestResponse <T>, RestRequestAsyncHandle> callback,
     IRestResponse response,
     RestRequestAsyncHandle asyncHandle
     )
 => callback(Deserialize <T>(request, response), asyncHandle);
コード例 #5
0
        public virtual Task <IRestResponse> ExecuteTaskAsync(IRestRequest request, CancellationToken token)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            TaskCompletionSource <IRestResponse> taskCompletionSource = new TaskCompletionSource <IRestResponse>();

            try
            {
                RestRequestAsyncHandle async = ExecuteAsync(request, delegate(IRestResponse response, RestRequestAsyncHandle _)
                {
                    if (token.IsCancellationRequested)
                    {
                        taskCompletionSource.TrySetCanceled();
                    }
                    else
                    {
                        taskCompletionSource.TrySetResult(response);
                    }
                });
                token.Register(delegate
                {
                    async.Abort();
                    taskCompletionSource.TrySetCanceled();
                });
            }
            catch (Exception exception)
            {
                taskCompletionSource.TrySetException(exception);
            }
            return(taskCompletionSource.Task);
        }
コード例 #6
0
    public void ReadHandler(IRestResponse<List<Score>> response, RestRequestAsyncHandle handle)
    {
        Debug.Log("In ReadHandler");
        _scores = response.Data;

        Debug.Log(_scores);
    }
コード例 #7
0
        private RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action <IRestResponse, RestRequestAsyncHandle> callback, string httpMethod, Func <IHttp, Action <HttpResponse>, string, HttpWebRequest> getWebRequest)
        {
            IHttp http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);
            ConfigureHttp(request, http);
            RestRequestAsyncHandle asyncHandle = new RestRequestAsyncHandle();
            Action <HttpResponse>  action      = delegate(HttpResponse r)
            {
                ProcessResponse(request, r, asyncHandle, callback);
            };

            if (UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                SynchronizationContext ctx = SynchronizationContext.Current;
                Action <HttpResponse>  cb  = action;
                action = delegate(HttpResponse resp)
                {
                    ctx.Post(delegate
                    {
                        cb(resp);
                    }, null);
                };
            }
            asyncHandle.WebRequest = getWebRequest(http, action, httpMethod);
            return(asyncHandle);
        }
コード例 #8
0
ファイル: Main.cs プロジェクト: endel/hook-csharp
        static void Main(string[] args)
        {
            Client client = new Client("2", "a18632aa82be8e925ef349164314311a", "http://hook.dev/public/index.php/");
            Collection posts = client.Collection ("posts");

            var post = new Post ();
            post.title = "Hello there!";
            post.score = 15;
            post.date = new DateTime (2014, 07, 07, 17, 30, 0);

            posts.Create (post).ContinueWith<Post> (result => {
                Console.WriteLine(result.ToString());
            });

            posts.Get ().ContinueWith<Post[]> (result => {
                Console.WriteLine(result.ToString());
            });

            req = posts.Sort ("created_at", Order.DESCENDING).Limit(1).First().ContinueWith<Post> (data => {
                Console.WriteLine("Post id: ");
                Console.WriteLine(data._id);
            });

            NSApplication.Init ();
            NSApplication.Main (args);
        }
コード例 #9
0
        private RestRequestAsyncHandle ExecuteAsync(IRestRequest request,
                                                    Action <IRestResponse, RestRequestAsyncHandle> callback, string httpMethod,
                                                    Func <IHttp, Action <HttpResponse>, string, HttpWebRequest> getWebRequest)
        {
            var http = HttpFactory.Create();

            AuthenticateIfNeeded(this, request);

            ConfigureHttp(request, http);

            var asyncHandle = new RestRequestAsyncHandle();

            Action <HttpResponse> response_cb = r => ProcessResponse(request, r, asyncHandle, callback);

#if !PocketPC
            if (UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                var ctx = SynchronizationContext.Current;
                var cb  = response_cb;

                response_cb = resp => ctx.Post(s => cb(resp), null);
            }
#endif

            asyncHandle.WebRequest = getWebRequest(http, response_cb, httpMethod);
            return(asyncHandle);
        }
コード例 #10
0
        public GitHubRequestAsyncHandle(GitHubRequest request,
                                        RestRequestAsyncHandle handle)
        {
            Requires.ArgumentNotNull(request, "request");
            Requires.ArgumentNotNull(handle, "handle");

            _request = request;
            _handle = handle;
        }
コード例 #11
0
        private RestRequestAsyncHandle ExecuteAsyncInternal <T>(IRestRequest request, Action <IRestResponse <T>, RestRequestAsyncHandle> callback)
        {
            var asyncHandle = new RestRequestAsyncHandle(new CancellationTokenSource());

            //  Start a task here to do the Http Request and then return asyncHandle that client can use to cancel
            Task.Factory.StartNew(() => ExecuteAsync <T>(request, callback, asyncHandle), asyncHandle.CancelToken.Token);

            return(asyncHandle);
        }
コード例 #12
0
 // Constructor
 public MainPage()
 {
     //progress.IsHitTestVisible = false;
     InitializeComponent();
     rrah = null;
     settings = IsolatedStorageSettings.ApplicationSettings;
     xmlCache = IsolatedStorageFile.GetUserStoreForApplication();
     this.Loaded += new RoutedEventHandler(MainPage_Loaded);
 }
コード例 #13
0
        private static void ProcessResponse(
            IRestRequest request, IHttpResponse httpResponse,
            RestRequestAsyncHandle asyncHandle, Action <IRestResponse, RestRequestAsyncHandle> callback
            )
        {
            var restResponse = RestResponse.FromHttpResponse(httpResponse, request);

            callback(restResponse, asyncHandle);
        }
コード例 #14
0
        /// <summary>
        /// Executes the request asynchronously, authenticating if needed
        /// </summary>
        /// <param name="request">Request to be executed</param>
        /// <param name="token">The cancellation token</param>
        public virtual Task <IRestResponse> ExecuteTaskAsync(IRestRequest request, CancellationToken token)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            TaskCompletionSource <IRestResponse> taskCompletionSource = new TaskCompletionSource <IRestResponse>();

            try
            {
                RestRequestAsyncHandle async = this.ExecuteAsync(
                    request,
                    (response, _) =>
                {
                    if (token.IsCancellationRequested)
                    {
                        taskCompletionSource.TrySetCanceled();
                    }
                    // Don't run TrySetException, since we should set Error
                    // properties and swallow exceptions to be consistent
                    // with sync methods
                    else
                    {
                        taskCompletionSource.TrySetResult(response);
                    }
                });

#if !WINDOWS_PHONE
                CancellationTokenRegistration registration =
#endif
                token.Register(() =>
                {
                    async.Abort();
                    taskCompletionSource.TrySetCanceled();
                });

#if !WINDOWS_PHONE
                taskCompletionSource.Task.ContinueWith(t => registration.Dispose(), token);
#endif
            }
            catch (Exception ex)
            {
                taskCompletionSource.TrySetException(ex);
            }

            return(taskCompletionSource.Task);
        }
コード例 #15
0
        RestRequestAsyncHandle ExecuteAsync(
            IRestRequest request,
            Action <IRestResponse, RestRequestAsyncHandle> callback,
            string httpMethod,
            Func <IHttp, Action <HttpResponse>, string, HttpWebRequest> getWebRequest
            )
        {
            request.SerializeRequestBody(Serializers, request.XmlSerializer, request.JsonSerializer);

            AuthenticateIfNeeded(request);

            var http = ConfigureHttp(request);

            request.OnBeforeRequest?.Invoke(http);

            var asyncHandle = new RestRequestAsyncHandle();

            Action <HttpResponse> responseCb = ProcessResponse;

            if (UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                var ctx = SynchronizationContext.Current;
                var cb  = responseCb;

                responseCb = resp => ctx.Post(s => cb(resp), null);
            }

            asyncHandle.WebRequest = getWebRequest(http, responseCb, httpMethod);

            return(asyncHandle);

            void ProcessResponse(IHttpResponse httpResponse)
            {
                var restResponse = RestResponse.FromHttpResponse(httpResponse, request);

                restResponse.Request.IncreaseNumAttempts();
                callback(restResponse, asyncHandle);
            }
        }
コード例 #16
0
        private void DeserializeResponse <T>(IRestRequest request,
                                             Action <IRestResponse <T>, RestRequestAsyncHandle> callback, IRestResponse response,
                                             RestRequestAsyncHandle asyncHandle)
        {
            IRestResponse <T> restResponse;

            try
            {
                restResponse = Deserialize <T>(request, response);
            }
            catch (Exception ex)
            {
                restResponse = new RestResponse <T>
                {
                    Request        = request,
                    ResponseStatus = ResponseStatus.Error,
                    ErrorMessage   = ex.Message,
                    ErrorException = ex
                };
            }

            callback(restResponse, asyncHandle);
        }
コード例 #17
0
        private RestRequestAsyncHandle ExecuteAsync(IRestRequest request,
                                                    Action <IRestResponse, RestRequestAsyncHandle> callback, string httpMethod,
                                                    Func <IHttp, Action <HttpResponse>, string, HttpWebRequest> getWebRequest)
        {
            IHttp http = this.HttpFactory.Create();

            this.AuthenticateIfNeeded(this, request);
            this.ConfigureHttp(request, http);

            RestRequestAsyncHandle asyncHandle = new RestRequestAsyncHandle();
            Action <HttpResponse>  responseCb  = r => ProcessResponse(request, r, asyncHandle, callback);

            if (this.UseSynchronizationContext && SynchronizationContext.Current != null)
            {
                SynchronizationContext ctx = SynchronizationContext.Current;
                Action <HttpResponse>  cb  = responseCb;

                responseCb = resp => ctx.Post(s => cb(resp), null);
            }

            asyncHandle.WebRequest = getWebRequest(http, responseCb, httpMethod);

            return(asyncHandle);
        }
コード例 #18
0
ファイル: turnosModel.cs プロジェクト: xmalmorthen/turnosRC
        public static Boolean turnoState()
        {
            try
            {
                client.Timeout = turnosDashboard.Properties.Settings.Default.RESTRequestTimeOut;
                // client.Authenticator = new HttpBasicAuthenticator(username, password);

                string method = string.Format("{0}?Oficina={1}","obtener/turno",turnosDashboard.Properties.Settings.Default.IdOficina.ToString().Trim());

                var request = new RestRequest(method, Method.GET);
                request.AddHeader("Accept", "application/json");

                try
                {
                    asyncHandle.Abort();
                }
                catch (Exception){}

                asyncHandle = client.ExecuteAsync<RESTTurno>(request, response =>
                {
                    try
                    {
                        if (response.ResponseStatus == ResponseStatus.Completed)
                        {
                            if (response.Data.REST_Service.Status_response.ToString().Trim().Equals("ok", StringComparison.CurrentCultureIgnoreCase) == true)
                            {
                                try
                                {
                                    if (TurnoActual.Ventanilla.Equals(response.Data.response.SingleOrDefault().NombreVentanilla, StringComparison.CurrentCultureIgnoreCase) == false)
                                    {
                                        changeTurno(response.Data.response.SingleOrDefault().Turno, response.Data.response.SingleOrDefault().NombreVentanilla, response.Data.response.SingleOrDefault().Tramite);
                                    }
                                    else if (TurnoActual.Turno.Equals(response.Data.response.SingleOrDefault().Turno) == false)
                                    {
                                        changeTurno(response.Data.response.SingleOrDefault().Turno, response.Data.response.SingleOrDefault().NombreVentanilla, response.Data.response.SingleOrDefault().Tramite);
                                    }
                                }
                                catch (Exception)
                                {
                                    changeTurno(response.Data.response.SingleOrDefault().Turno, response.Data.response.SingleOrDefault().NombreVentanilla, response.Data.response.SingleOrDefault().Tramite);
                                }

                            }
                            else
                            {
                                //throw new Exception(response.Data.REST_Service.Message.ToString());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger logger = LogManager.GetCurrentClassLogger();
                        logger.Error(ex, ex.Message);
                    }
                });
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex, ex.Message);
                return false;
            }
            return true;
        }
コード例 #19
0
ファイル: turnosModel.cs プロジェクト: xmalmorthen/turnosRC
        private static void changeTurno(int turno, string ventanilla, string tramite)
        {
            TurnosAtendiendo.Clear();

            try
            {
                client.Timeout = turnosDashboard.Properties.Settings.Default.RESTRequestTimeOut;
                // client.Authenticator = new HttpBasicAuthenticator(username, password);

                string method = string.Format("{0}?Oficina={1}", "obtener/ultimos3turnos", turnosDashboard.Properties.Settings.Default.IdOficina.ToString().Trim());

                var request = new RestRequest(method, Method.GET);
                request.AddHeader("Accept", "application/json");

                try
                {
                    asyncHandle3Turnos.Abort();
                }
                catch (Exception) { }

                asyncHandle3Turnos = client.ExecuteAsync<RESTTurno>(request, response =>
                {
                    try
                    {

                        if (response.ResponseStatus == ResponseStatus.Completed)
                        {
                            if (response.Data.REST_Service.Status_response.ToString().Trim().Equals("ok", StringComparison.CurrentCultureIgnoreCase) == true)
                            {
                                short cont = 0;
                                foreach (strctTurno item in response.Data.response)
                                {
                                    if (cont > 0) {
                                        turno _item = new turno();
                                        _item.Turno = item.Turno;
                                        _item.Ventanilla = item.NombreVentanilla;
                                        _item.Tramite = item.Tramite;
                                        TurnosAtendiendo.Add(_item);
                                    }
                                    cont++;
                                }
                                Program.main.refreshControls();
                            }
                            else
                            {
                                //throw new Exception(response.Data.REST_Service.Message.ToString());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger logger = LogManager.GetCurrentClassLogger();
                        logger.Error(ex, ex.Message);
                    }
                });
            }
            catch (Exception ex)
            {
                Logger logger = LogManager.GetCurrentClassLogger();
                logger.Error(ex, ex.Message);
            }

            TurnoActual.Turno = turno;
            TurnoActual.Ventanilla = ventanilla;
            TurnoActual.Tramite = tramite;

            TurnoChanged = true;
        }
コード例 #20
0
        private void DeserializeResponse <T>(IRestRequest request, Action <IRestResponse <T>, RestRequestAsyncHandle> callback, IRestResponse response, RestRequestAsyncHandle asyncHandle)
        {
            IRestResponse <T> restResponse = Deserialize <T>(request, response);

            callback(restResponse, asyncHandle);
        }
コード例 #21
0
        protected void SynchronizedPerform()
        {
            _killSwitch = _httpClient.ExecuteAsync(GetHttpRequest(), response => {
                var y = new OKServiceResponse();

                if (response.ResponseStatus == ResponseStatus.Aborted)
                    y.Status = OKIOStatus.Cancelled;
                else {
                    switch (response.StatusCode) {
                        case HttpStatusCode.OK:
                            y.Status = OKIOStatus.Succeeded;
                            y.Obj = JSONObjectExt.decode(response.Content);
                            break;
                        case HttpStatusCode.Forbidden:
                            y.Status = OKIOStatus.FailedWithError;
                            y.Err = new OKException("Forbidden: Verify that your key and secret are correct.");
                            break;
                        default:
                            y.Status = OKIOStatus.FailedWithError;
                            y.Err = new OKException("OKServiceRequest failed.  Response body: " + response.Content);
                            break;
                    }
                }

                SynchronizationContext c = OKCtx.Ctx;
                if (c == null)
                    _didFinish(y);
                else
                    c.Post(s => _didFinish(y), null);

                _killSwitch = null;
            });
        }
コード例 #22
0
ファイル: TCHttpRequest.cs プロジェクト: borain89vn/demo2
		public void remove (RestRequestAsyncHandle requestHandle)
		{
			this.httpRequests.Remove (requestHandle);
		}
コード例 #23
0
        public static IPromise <IRestResponse> ExecuteAsync(this RestClient client, RestRequest request, out RestRequestAsyncHandle handle)
        {
            Promise <IRestResponse> promise = new Promise <IRestResponse>();

            handle = client.ExecuteAsync(request, (response, handler) => promise.Resolve(response));
            return(promise);
        }
コード例 #24
0
ファイル: TCHttpRequest.cs プロジェクト: borain89vn/demo2
		public void send ()
		{
			try {
				this.restRequestAsyncHandle = this.restClient.ExecuteAsync (this.restRequest, response => {
				
					#if DEBUG
					Console.Out.WriteLine (response.ResponseStatus.ToString ().ToUpper () + " : " + this.restClient.BaseUrl);
					Console.Out.WriteLine("Respone content" +response.Content);
					#endif

					if (response.ResponseStatus == ResponseStatus.Completed) {
						if (this.responseSuccessful != null) {
							this.responseSuccessful (response.Content);
						}
					} else if (response.ResponseStatus != ResponseStatus.Aborted) { 
						if (this.responseFailure != null) {
							this.responseFailure (response.Content);
						}
					}

					if (MApplication.getInstance ().isLogedIn) {
						TCRequestManager.getInstance ().remove (this.restRequestAsyncHandle);
					}
				});

				TCRequestManager.getInstance ().add (this.restRequestAsyncHandle);
			} catch (Exception ex) {
				#if DEBUG
				Console.Write (ex.Message);
				#endif
				if (this.responseFailure != null)
					this.responseFailure (null);
			}
		}
コード例 #25
0
        private void DeserializeResponse <T>(IRestRequest request, Action <IRestResponse <T>, RestRequestAsyncHandle> callback, IRestResponse response, RestRequestAsyncHandle asyncHandle)
        {
            IRestResponse <T> restResponse = response as RestResponse <T>;

            if (response.ResponseStatus != ResponseStatus.Aborted)
            {
                restResponse = Deserialize <T>(request, response);
            }

            callback(restResponse, asyncHandle);
        }
コード例 #26
0
 private void DeserializeResponse <T> (
     IRestRequest request, Action <IRestResponse <T>,
                                   RestRequestAsyncHandle> callback, IRestResponse response, RestRequestAsyncHandle asyncHandle
     ) where T : new()
 {
     callback(Deserialize <T> (request, response), asyncHandle);
 }
コード例 #27
0
        public void ReadHandler(IRestResponse<List<Score>> response, RestRequestAsyncHandle handle)
        {
            //Debug.Log("In ReadHandler");
            //leaderBoardData.scores = response.Data;

            //Debug.Log(_scores);
        }
コード例 #28
0
        private void DeserializeResponse <T>(IRestRequest request, Action <IRestResponse <T>, RestRequestAsyncHandle> callback, IRestResponse response, RestRequestAsyncHandle asyncHandle)
        {
            IRestResponse <T> arg;

            try
            {
                arg = Deserialize <T>(request, response);
            }
            catch (Exception ex)
            {
                RestResponse <T> restResponse = new RestResponse <T>();
                restResponse.Request        = request;
                restResponse.ResponseStatus = ResponseStatus.Error;
                restResponse.ErrorMessage   = ex.Message;
                restResponse.ErrorException = ex;
                arg = restResponse;
            }
            callback(arg, asyncHandle);
        }
コード例 #29
0
        private async Task ExecuteAsync <T>(IRestRequest request, Action <IRestResponse <T>, RestRequestAsyncHandle> callback, RestRequestAsyncHandle handle)
        {
            RestResponse <T> response;

            try
            {
                //  Set up a HttpRequestMessage based on the request properties
                HttpRequestMessage reqMessage = ConfigureHttp(request);
                HttpClient         client     = Client;

                //  Make the request and wait until response is read
                HttpResponseMessage responseMessage = await client.SendRequestAsync(reqMessage, HttpCompletionOption.ResponseContentRead);

                //  Convert response to IRestResponse
                response = await ConvertToRestResponse <T>(request, responseMessage);
            }
            catch (Exception e)
            {
                response = new RestResponse <T>();
                response.ResponseStatus    = ResponseStatus.Error;
                response.ErrorException    = e;
                response.StatusDescription = "Exception Occurred when executing the request.  Check the ErrorException for details";
            }

            callback(response, handle);
        }
コード例 #30
0
    private void UpdateHighScoreHandler(IRestResponse<List<Score>> response, RestRequestAsyncHandle handle)
    {
        List<Score> items = response.Data;

        Debug.Log("In UpdateHighSCoreHandler");
        if (items != null && items.Count == 1)
        {
            Score currentItem = items[0];
            Debug.Log(currentItem.Id.ToString());
            if (_score > currentItem.Value)
            {
                currentItem.Value = _score;
                Debug.Log(currentItem.CreatedDate.ToString());

                try
                {
                    var json = JsonWriter.Serialize(currentItem);
                    var request = (IRestRequest)(new RestRequest("http://stratusleaderboard.azure-mobile.net/tables/HighScoreItem/" + currentItem.Id, Method.PATCH));
                    request.RequestFormat = DataFormat.Json;
                    request.AddParameter("application/json", json, ParameterType.RequestBody);

                    request.AddHeader("X-ZUMO-APPLICATION", "zmZrsoLIQZhkIRFGkUsxqKiykXdkLO82");
                    _client.ExecuteAsync(request, PatchHandler);
                }
                catch (Exception e)
                {
                    Debug.LogException(e);
                }
            }
        }
        Debug.Log("High Score Updated");
    }
コード例 #31
0
        /// <summary>
        /// Executes the request asynchronously using a Task
        /// </summary>
        /// <param name="request">The request to be executed</param>
        /// <param name="handle">A handle to allow aborting the execution</param>
        /// <returns>A Task for the response</returns>
        public static Task <IRestResponse> ExecuteAsync(this RestClient client, RestRequest request, out RestRequestAsyncHandle handle)
        {
            var task = new TaskCompletionSource <IRestResponse>();

            handle = client.ExecuteAsync(request, response => task.SetResult(response));
            return(task.Task);
        }
コード例 #32
0
        private void ProcessResponse(IRestRequest request, HttpResponse httpResponse, RestRequestAsyncHandle asyncHandle, Action <IRestResponse, RestRequestAsyncHandle> callback)
        {
            RestResponse arg = ConvertToRestResponse(request, httpResponse);

            callback(arg, asyncHandle);
        }
コード例 #33
0
        /// <summary>
        ///     The data grid view 1 selection changed.
        /// </summary>
        /// <param name="sender">
        ///     The sender.
        /// </param>
        /// <param name="e">
        ///     The e.
        /// </param>
        private void DataGridView1SelectionChanged(object sender, EventArgs e)
        {
            var dgv = (DataGridView)sender;

            // Don't do anything if there are no rows.
            if (dgv.Rows.Count <= 0)
            {
                return;
            }

            var formattedValue = dgv.SelectedCells[0].OwningRow.Cells["Catalog ID"].FormattedValue;

            // Check to make sure that the value isn't null
            if (formattedValue != null)
            {
                var catId = formattedValue.ToString();

                // If there is a current handle abort its operation before starting the next one
                if (this.asyncHandle != null)
                {
                    this.asyncHandle.Abort();
                }

                // Url of the image finder's thumbnail.
                var url = string.Format(
                    "/imagefinder/showBrowseImage?catalogId={0}&imageHeight=512&imageWidth=512",
                    catId);

                var request = new RestRequest(url, Method.GET);

                // Check to see the image has already been retrieved.  if it has use that instead of making the network call.
                if (this.cachedImages.ContainsKey(catId))
                {
                    this.thumbnailPictureBox.Image = this.cachedImages[catId];
                    return;
                }

                // Throw up the please wait image
                this.thumbnailPictureBox.Image = new Bitmap(GbdxResources.PleaseStandBy, this.thumbnailPictureBox.Size);

                // get the image asynchronsly
                this.asyncHandle = this.client.ExecuteAsync(
                    request,
                    response =>
                        {
                            if (response.RawBytes == null)
                            {
                                return;
                            }

                            var ms = new MemoryStream(response.RawBytes);
                            var returnImage = Image.FromStream(ms);
                            this.thumbnailPictureBox.Image = returnImage;
                            if (!this.cachedImages.ContainsKey(catId))
                            {
                                this.cachedImages.Add(catId, returnImage);
                            }
                        });
            }
        }
コード例 #34
0
ファイル: TCHttpRequest.cs プロジェクト: borain89vn/demo2
		public void add (RestRequestAsyncHandle requestHandle)
		{
			this.httpRequests.Add (requestHandle);
		}
コード例 #35
0
ファイル: EtcdClient.cs プロジェクト: haimn100/etcetera
 private Uri getResponseBaseUri(IRestRequest restResponse, RestRequestAsyncHandle response)
 {
     if(response!=null&&response.WebRequest!=null && response.WebRequest.Host!=null)
         return new Uri("http://" + response.WebRequest.Host);
     return new Uri("http://" + restResponse.Parameters.First((a)=>a.Name == "target" ).Value);
 }
コード例 #36
0
 private void OnResponse(IRestResponse response, RestRequestAsyncHandle handle) {
     string requestUrl = response.ResponseUri != null ? response.ResponseUri.ToString() : "Could not get response URI";
     ValidateResponse(requestUrl, response, true);
 }
コード例 #37
0
        private void execute_refresh(RestClient client, RestRequest request)
        {
            progress.Visibility = Visibility.Visible;
            // get visibility

            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = true; // enable stop
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = false; // disable refresh

            rrah = client.ExecuteAsync(request, (response) =>
            {
                if (response.ResponseStatus != ResponseStatus.Completed || response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    //current_condition.Text = "Could not load latest data, make sure you are connected to the internet.";
                    DateTime last_updated = DateTime.Now;
                    if (settings.Contains("lastUpdated"))
                    {
                         last_updated = (DateTime)settings["lastUpdated"];
                    }
                    refresh_from_cache(last_updated);
                    // lastUpdatedText.Text = AppResources.last_updated + " " + AppResources.never; // override
                } else {
                    int temp_format = WeatherHelper.WeatherHelper.FAREN;
                    if (settings.Contains("tempFormat"))
                    {
                        temp_format = (int)settings["tempFormat"];
                    }
                    current_condition.Text = response.StatusDescription;
                    var resource = response.Content;
                    // parse out the info
                    // update from info
                    if (settings.Contains("lastUpdated"))
                    {
                        settings["lastUpdated"] = DateTime.Now;
                    }
                    else
                    {
                        settings.Add("lastUpdated", DateTime.Now);
                    }
                    lastUpdatedText.Text = String.Format(AppResources.last_updated + " 0 " + AppResources.minutes_ago);
                    using (StreamWriter writer = new StreamWriter(new IsolatedStorageFileStream("xmlCache.xml", FileMode.Create, FileAccess.Write, xmlCache)))
                    {
                        writer.Write(resource);
                        writer.Close();
                    }
                    refresh_from_xml(resource, temp_format);
                }
                if (watcher != null)
                {
                    watcher.Stop();
                }
                progress.Visibility = Visibility.Collapsed;
                ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).IsEnabled = false; // disable stop
                ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).IsEnabled = true; // enable refresh
                rrah = null;
            });
        }
コード例 #38
0
 private static void ResponseHandler(IRestResponse restResponse, RestRequestAsyncHandle restRequestAsyncHandle)
 {
     // ignore for now;
 }
コード例 #39
0
        private void SynchronizedGet()
        {
            if (Cancelled) {
                // User cancelled before we made it to kick-off.
                var x = new OKMetadataResponse();
                x.Status = OKIOStatus.Cancelled;
                _didFinish(x);
                return;
            }

            var req = new RestRequest(_uri, Method.GET);

            _killSwitch = _httpClient.ExecuteAsync(req, response => {
                var y = new OKMetadataResponse();

                if (response.ResponseStatus == ResponseStatus.Completed)
                    y.Raw = response.RawBytes;
                else if (response.ResponseStatus == ResponseStatus.Aborted)
                    y.Status = OKIOStatus.Cancelled;
                else {
                    y.Status = OKIOStatus.FailedWithError;
                    y.Err = new OKException("Could not get metadata.  RestSharp response code: " + response.ResponseStatus);
                }

                SynchronizationContext c = OKCtx.Ctx;
                if (c == null)
                    _didFinish(y);
                else
                    c.Post(s => _didFinish(y), null);

                // We're all done.  Disable the kill switch:
                _killSwitch = null;
            });
        }
コード例 #40
0
ファイル: Email.cs プロジェクト: carmennegreanu/tnLabs
 private void MailResponse(IRestResponse response, RestRequestAsyncHandle handle)
 {
     //Do nothing if mail failed
 }
コード例 #41
0
        public void SetupClient(Table options)
        {
            Mock<IRestSharpFactory> factoryMock = _container.Mock<IRestSharpFactory>();

            factoryMock.Setup(factory => factory.CreateRequest(It.IsAny<string>(), It.IsAny<Method>()))
                .Returns<string, Method>((resource, method) => (_rest.Request = new RestRequest(resource, method)));

            IRestResponse response = _container.Mock<IRestResponse>().Object;

            var clientMock = _container.Mock<IRestClient>(MockBehavior.Strict);

            clientMock.Setup(client => client.Execute(It.IsAny<IRestRequest>()))
                .Returns(() => response);

            clientMock.Setup(client => client.ExecuteAsync(It.IsAny<IRestRequest>(), It.IsAny<Action<IRestResponse, RestRequestAsyncHandle>>()))
                .Returns<IRestRequest, Action<IRestResponse, RestRequestAsyncHandle>>((request, action) =>
                {
                    var handle = new RestRequestAsyncHandle();
                    action(response, handle);
                    return handle;
                });

            factoryMock.Setup(factory => factory.CreateClient(It.IsAny<string>()))
                .Returns(() => clientMock.Object);

            _container.Update<IStargateOptions>(options.CreateInstance<StargateOptions>());

            _container.Update<IMimeConverter, XmlMimeConverter>();
            _container.Update<IMimeConverterFactory, MimeConverterFactory>();
            _container.Update<IResourceBuilder, ResourceBuilder>();
            _container.Update<ISimpleValueConverter, SimpleValueConverter>();
            _container.Update<ICodec, Base64Codec>();
            _container.Update<IErrorProvider, ErrorProvider>();
            _container.Update<IStargate, Stargate>();
        }
コード例 #42
0
        private void UpdateHighScoreHandler(IRestResponse<List<Score>> response, RestRequestAsyncHandle handle)
        {
            List<Score> items = response.Data;
            int score = 100;
            Debug.Log("In UpdateHighSCoreHandler");
            if (items != null && items.Count == 1)
            {
                Score currentItem = items[0];

                if (score > currentItem.Value)
                {
                    currentItem.Value = score;
                    Debug.Log(currentItem.CreatedDate.ToString());

                    try
                    {
                        var json = JsonWriter.Serialize(currentItem);
                        var request = (IRestRequest)(new RestRequest("tables/HighScoreItem/" + currentItem.Id, Method.PATCH));
                        request.RequestFormat = DataFormat.Json;
                        request.AddParameter("application/json", json, ParameterType.RequestBody);

                        request.AddHeader("X-ZUMO-APPLICATION", serviceKey);
                        //_client.ExecuteAsync(request, PatchHandler);
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                    }
                }
            }
            Debug.Log("High Score Updated");
        }
コード例 #43
0
ファイル: VirtualUser.cs プロジェクト: bevacqua/Swarm
        private void Perform(IRestRequest request)
        {
            DateTime start = DateTime.UtcNow;
            IRestClient client = network.RestClient;
            AutoResetEvent signal = new AutoResetEvent(false);
            RequestItem pending = network.ProfilePending(request, start);

            try
            {
                asyncHandle = client.ExecuteAsync(request, response =>
                {
                    EndProfile(pending, response, signal);
                });
            }
            catch (Exception fault) // sometimes requests just fail.
            {
                IRestResponse response = new FaultedRestResponse(request, fault);
                EndProfile(pending, response, signal);
            }
            int timeout = network.RestClient.Timeout;
            signal.WaitOne(timeout == 0 ? -1 : timeout); // 0 and -1 indicate infinity in RestClient and EventWaitHandle respectively.
        }
コード例 #44
0
        private void ProcessResponse(HttpResponse httpResponse, RestRequestAsyncHandle asyncHandle, Action <RestResponse, RestRequestAsyncHandle> callback)
        {
            var restResponse = ConvertToRestResponse(httpResponse);

            callback(restResponse, asyncHandle);
        }
コード例 #45
0
 private void OnAuthenticateCompleted(RestResponse arg1, RestRequestAsyncHandle arg2)
 {
     try
     {
         var result = JsonConvert.DeserializeObject<dynamic>(arg1.Content);
         string token = result.access_token;
         settings.AccessToken = token;
         settingsService.Save();
         client.Authenticator = new OAuth2UriQueryParameterAuthenticator(token);
         client.Users.GetAuthenticatedUserAsync(MapUser, LogError);
     }
     catch (Exception ex)
     {
         // TODO: notify that the code was not successful
     }
 }