CancelPendingRequests() публичный Метод

public CancelPendingRequests ( ) : void
Результат void
Пример #1
0
        public async Task<BitmapImage> BitmapImageAsync(string url)
        {
            Stream stream = null;
            HttpClient WebClient = new HttpClient();
            BitmapImage image = new BitmapImage();

            try
            {
                stream = new MemoryStream(await WebClient.GetByteArrayAsync(url));
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad; // here
                image.StreamSource = stream;
                image.EndInit();
                image.Freeze();
            }
            catch { }

            if (stream != null)
            {
                stream.Close(); stream.Dispose(); stream = null;
            }

            url = null; WebClient.CancelPendingRequests(); WebClient.Dispose(); WebClient = null;
            return image;
        }
Пример #2
0
        public void OwinCallCancelled(HostType hostType)
        {
            using (ApplicationDeployer deployer = new ApplicationDeployer())
            {
                var serverInstance = new NotificationServer();
                serverInstance.StartNotificationService();

                string applicationUrl = deployer.Deploy(hostType, Configuration);

                try
                {
                    Trace.WriteLine(string.Format("Making a request to url : ", applicationUrl));
                    HttpClient httpClient = new HttpClient();
                    Task<HttpResponseMessage> response = httpClient.GetAsync(applicationUrl);
                    response.Wait(1 * 1000);
                    httpClient.CancelPendingRequests();
                    bool receivedNotification = serverInstance.NotificationReceived.WaitOne(20 * 1000);
                    Assert.True(receivedNotification, "CallCancelled CancellationToken was not issued on cancelling the call");
                }
                finally
                {
                    serverInstance.Dispose();
                }
            }
        }
Пример #3
0
		public void CancelPendingRequests ()
		{
			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			var mre = new ManualResetEvent (false);

			mh.OnSendFull = (l, c) => {
				mre.Set ();
				Assert.IsTrue (c.WaitHandle.WaitOne (1000), "#20");
				Assert.IsTrue (c.IsCancellationRequested, "#21");
				mre.Set ();
				return Task.FromResult (new HttpResponseMessage ());
			};

			var t = Task.Factory.StartNew (() => {
				client.SendAsync (request).Wait (WaitTimeout);
			});

			Assert.IsTrue (mre.WaitOne (500), "#1");
			mre.Reset ();
			client.CancelPendingRequests ();
			Assert.IsTrue (t.Wait (500), "#2");

			request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			mh.OnSendFull = (l, c) => {
				Assert.IsFalse (c.IsCancellationRequested, "#30");
				return Task.FromResult (new HttpResponseMessage ());
			};

			client.SendAsync (request).Wait (WaitTimeout);
		}
Пример #4
0
 private void FreeUpClient(HttpClient client)
 {
     lock (objectLock)
     {
         if (client != null)
         {
             client.CancelPendingRequests();
             client.DefaultRequestHeaders.Clear();
             WorkingClients.Remove(client);
             FreeClients.Add(client);
         }
     }
 }
Пример #5
0
 public void CancelPendingRequests()
 {
     client.CancelPendingRequests();
 }
Пример #6
0
        async Task<IEnumerable<string>> ReadStrings()
        {
            using (var httpClient = new HttpClient())
            {
                using (var registration = _token.Register(() => httpClient.CancelPendingRequests()))
                {
                    var tasks = new Task<string>[100];

                    for (var i = 0; i < tasks.Count() && !_token.IsCancellationRequested; ++i)
                        tasks[i] = TaskEx.Run(() => ReadString(httpClient), _token);

                    var completed = await TaskEx.WhenAll(tasks).ConfigureAwait(false);

                    // Do a little CPU-bound work...
                    return completed.Distinct();
                }
            }
        }
Пример #7
0
        public static async Task<ImageSize> FetchImageSizeAsync(string imgurl)
        {
            var rtn = new ImageSize();
            using (var client = new HttpClient(new HttpClientHandler()
            {
                AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
            }))
            {
                var resp = await client.GetAsync(imgurl, HttpCompletionOption.ResponseHeadersRead);
                if (!resp.IsSuccessStatusCode)
                    return rtn;
                try
                {
                    var stream = await resp.Content.ReadAsStreamAsync();

                    var buffer = new byte[8];
                    var read = await stream.ReadAsync(buffer, 0, 1);
                    if (read != 1)
                        return rtn;
                    if (buffer[0] == 0x42) //bitmap
                    {
                        read = await stream.ReadAsync(buffer, 0, 1);
                        if (read == 1 && buffer[0] == 0x4D)//BITMAP magic match
                        {
                            //var b = new byte[8];
                            read = await stream.ReadAsync(buffer, 0, 8);
                            if (read == 8)
                            {
                                rtn.Width = BitConverter.ToInt32(buffer, 0);
                                rtn.Height = BitConverter.ToInt32(buffer, 4);
                            }
                        }
                    }
                    else if (buffer[0] == 0x47) //gif
                    {
                        // var b = new byte[5];
                        read = await stream.ReadAsync(buffer, 0, 5);
                        if (read == 5 && buffer[0] == 0x49 && buffer[1] == 0x46 && buffer[2] == 0x38 && buffer[4] == 0x61)// gif magic match
                        {
                            await stream.ReadAsync(buffer, 0, 2);
                            rtn.Width = BitConverter.ToInt16(buffer, 0);
                            await stream.ReadAsync(buffer, 0, 2);
                            rtn.Height = BitConverter.ToInt16(buffer, 0);
                        }
                    }
                    else if (buffer[0] == 0x89) //png
                    {
                        //var b = new byte[8];
                        read = await stream.ReadAsync(buffer, 0, 7);
                        if (read == 7 && buffer[0] == 0x50 && buffer[1] == 0x4E && buffer[2] == 0x47
                            && buffer[3] == 0x0D && buffer[4] == 0x0A && buffer[5] == 0x1A && buffer[6] == 0x0A)//png match
                        {
                            await stream.ReadAsync(buffer, 0, 8);
                            rtn.Width = LittleEndianInt32(buffer, 0);
                            rtn.Height = LittleEndianInt32(buffer, 4);
                        }
                    }
                    else if (buffer[0] == 0xff) //jpeg/jfif 
                    {
                        read = await stream.ReadAsync(buffer, 0, 1);
                        if (read == 1 && buffer[0] == 0xd8)//jfif match SOI/FFD8
                        {
                            for (; ; )
                            {
                                await stream.ReadAsync(buffer, 0, 4);//mark + marksize
                                var chunksize = LittleEndianInt16(buffer, 2);
                                if (buffer[0] == 0xff && buffer[1] == 0xc0)
                                {
                                    await stream.ReadAsync(buffer, 0, 5);
                                    rtn.Width = LittleEndianInt16(buffer, 1);
                                    rtn.Height = LittleEndianInt16(buffer, 3);
                                    break;
                                }
                                var b = new byte[chunksize];
                                await stream.ReadAsync(b, 0, chunksize - 2);
                            }

                        }
                    }
                }
                catch(HttpRequestException e)
                {
                    Debug.WriteLine(e.InnerException.Message);
                }finally
                {
                    client.CancelPendingRequests();
                }
            }
            return rtn;
        }
Пример #8
0
        /// <summary>
        ///  Send a SetValue request to the sever
        ///   (e.g. url = http://localhost/sys/Home/Kitchen/Overheadlight?e?PowerState, message contains
        ///   "0" or "1"), no response message-body
        /// </summary>
        public async void SetValueAsync(string location, string property, string value) {
            try {
                HttpClient webclient =
                    new HttpClient(new HttpClientHandler() {Credentials = new NetworkCredential(Username, Password)});
                var uri = new Uri(GetUrlFromSysUri(location) + "?e?" + property);
                Debug.WriteLine("SetValue: " + uri + ": " + value);

                // Premise's implementation of HTTP POST does not return an HTTP response.
                // HttpClient will wait for a response and if it doesn't get one, crash the app
                // Work around this by cancelling the request after sending it.
                webclient.PostAsync(uri, new StringContent(value)); // no await; return immediately. 
                await TaskEx.Delay(100);
                webclient.CancelPendingRequests();
            } catch (System.Net.Http.HttpRequestException httpRequestException) {
                return;
            } catch (Exception ex) {
                throw ex;
            }
        }
    private void GetUserInfoGoogle()
    {
        String url = Request.Url.Query;

        String strIp;

        if (url != null)
        {

            Char[] delimiterChars = { '=' };
            String[] words = url.Split(delimiterChars);
            String code = Request.QueryString["code"];
            String redirect_uri = "http://localhost:59573/Paneles.aspx";
            String mail=String.Empty;
            String name=String.Empty;
            Controlador.Registro registro = new Controlador.Registro();

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://accounts.google.com/o/oauth2/token");
            webRequest.Method = "POST";
            String Parameters = "code=" + code;
            Parameters = Parameters + "&client_id=" + _client_id;
            Parameters = Parameters + "&client_secret=" + _client_secret;
            Parameters = Parameters + "&redirect_uri=" + redirect_uri;
            Parameters = Parameters + "&grant_type=authorization_code";
            Byte[] byteArray = Encoding.UTF8.GetBytes(Parameters);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = byteArray.Length;
            Stream postStream = webRequest.GetRequestStream();
            //Add the post data to the web request
            postStream.Write(byteArray, 0, byteArray.Length);
            postStream.Close();

            WebResponse response = webRequest.GetResponse();
            postStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(postStream);
            String responseFromServer = reader.ReadToEnd();

            Controlador.GooglePlusAccessToken serStatus = JsonConvert.DeserializeObject<Controlador.GooglePlusAccessToken>(responseFromServer);

            if (serStatus != null)
            {
                String accessToken = String.Empty;
                accessToken = serStatus.access_token;
                var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken;
                if (!String.IsNullOrEmpty(accessToken))
                {
                    HttpClient client = new HttpClient();
                    client.CancelPendingRequests();
                    HttpResponseMessage output = client.GetAsync(urlProfile).Result;

                    if (output.IsSuccessStatusCode)
                    {
                        String outputData = output.Content.ReadAsStringAsync().Result;
                        Controlador.GoogleUserOutputData serStatus2 = JsonConvert.DeserializeObject<Controlador.GoogleUserOutputData>(outputData);

                        if (serStatus2 != null)
                        {
                            mail = serStatus2.email;
                            name = serStatus2.name;

                            String geoposicion = "";
                            strIp = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                            if (strIp == null)
                            {
                                strIp = Request.ServerVariables["REMOTE_ADDR"];
                            }

                            String usrIP = Request.UserHostAddress;

                            String apiUrl = "http://api.ipinfodb.com/v3/ip-city/?key=04e88385a9c161c8c3dbfbe8ae5ac070873e6e0a1a27014dd4aabfcfc1655aa4&ip=212.128.152.144&format=xml";

                            XmlDocument respon = GetXmlResponse(apiUrl);
                            // Display each entity's info.
                            geoposicion = ProcessEntityElements(respon);

                            Int64 idPersona=registro.Insertar(name, mail,geoposicion);
                            posOculto.Value = idPersona.ToString();

                            entrar.Visible = false;

                        }
                    }

                }

            }

        }

        entrar.Visible = false;
        salir.Visible = true;
    }
Пример #10
0
        //============ HttpClient based methods ==================

        /// <summary>
        ///  Send a SetValue request to the sever
        ///   (e.g. url = http://localhost/sys/Home/Kitchen/Overheadlight?e?PowerState, message contains
        ///   "0" or "1"), no response message-body
        /// </summary>
        public void SetValue(string location, string property, string value) {
            HttpClient webclient =
                new HttpClient(new HttpClientHandler() {Credentials = new NetworkCredential(Username, Password)});
            var uri = new Uri(GetUrlFromSysUri(location) + "?e?" + property);
            Debug.WriteLine("SetValue: " + uri + ": " + value);

            // Premise's implementation of HTTP POST does not return an HTTP response.
            // HttpClient will wait for a response and if it doesn't get one, crash the app
            // Work around this by cancelling the request after sending it.
            webclient.PostAsync(uri, new StringContent(value));
            TaskEx.Delay(100).ContinueWith(task => webclient.CancelPendingRequests());
        }
Пример #11
0
        public void Disconnect_ClientDisconnects_EventFires()
        {
            var requestReceived = new ManualResetEvent(false);
            var requestCanceled = new ManualResetEvent(false);

            OwinHttpListener listener = CreateServer(
                async env =>
                {
                    GetCallCancelled(env).Register(() => requestCanceled.Set());
                    requestReceived.Set();
                    Assert.True(requestCanceled.WaitOne(1000));
                },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                var requestTask = client.GetAsync(HttpClientAddress);
                Assert.True(requestReceived.WaitOne(1000));
                client.CancelPendingRequests();
                Assert.True(requestCanceled.WaitOne(1000));
                Assert.Throws<AggregateException>(() => requestTask.Result);
            }
        }
Пример #12
0
 public void CancelPendingRequests()
 {
     _inner.CancelPendingRequests();
 }
Пример #13
0
		public void CancelPendingRequests_BeforeSend ()
		{
			var ct = new CancellationTokenSource ();
			ct.Cancel ();
			var rr = CancellationTokenSource.CreateLinkedTokenSource (new CancellationToken (), ct.Token);


			var mh = new HttpMessageHandlerMock ();

			var client = new HttpClient (mh);
			var request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			client.CancelPendingRequests ();

			mh.OnSendFull = (l, c) => {
				Assert.IsFalse (c.IsCancellationRequested, "#30");
				return Task.FromResult (new HttpResponseMessage ());
			};

			client.SendAsync (request).Wait (WaitTimeout);

			request = new HttpRequestMessage (HttpMethod.Get, "http://xamarin.com");
			client.SendAsync (request).Wait (WaitTimeout);
		}
Пример #14
0
		/// <summary>
		/// Opens a long-poll modeled connection to retrieve updated information from the Steam server.
		/// </summary>
		private async void BeginPoll() {

			IndicateConnectionState( ClientConnectionStatus.Connecting );

			SteamRequest requestBase = new SteamRequest( "ISteamWebUserPresenceOAuth", "Poll", "v0001", HttpMethod.Post );
			requestBase.AddParameter( "umqid", ChatSession.ChatSessionID, ParameterType.GetOrPost );
			requestBase.AddParameter( "sectimeout", 20, ParameterType.GetOrPost );

			if( Authenticator != null ) {
				Authenticator.Authenticate( this, requestBase );
			}

			try {

				using( var client = new HttpClient() ) {

					Cancellation.Token.Register( () => client.CancelPendingRequests() );
					client.Timeout = TimeSpan.FromSeconds( 25 );

					while( true ) {

						requestBase.AddParameter( "message", LastMessageSentID, ParameterType.GetOrPost );

						using( var httpRequest = BuildHttpRequest( requestBase ) ) {

							try {

								using( var response = await client.SendAsync( httpRequest, HttpCompletionOption.ResponseContentRead ).ConfigureAwait( false ) ) {

									SteamChatPollResult result = SteamInterface.VerifyAndDeserialize<SteamChatPollResult>( ConvertToResponse( requestBase, response, null ) );

									IndicateConnectionState( ClientConnectionStatus.Connected );

									if( result.PollStatus == ChatPollStatus.OK ) {
										LastMessageSentID = result.PollLastMessageSentID;
										if( result.Messages != null )
											ProcessMessagesReceived( result );
									}

									await Task.Delay( 1000, Cancellation.Token );

								}

							} catch( Exception e ) {
								System.Diagnostics.Debug.WriteLine( e.ToString() );
								throw e;
							}

						}

					}

				}

			} catch( Exception e ) {
				System.Diagnostics.Debug.WriteLine( e.ToString() );
				IndicateConnectionState( ClientConnectionStatus.Disconnected );
				if( e is OperationCanceledException || e is TaskCanceledException ) {
					Cancellation.Dispose();
					Cancellation = new CancellationTokenSource();
					return;
				} else if( e is SteamRequestException ) {
					if( ( e as SteamRequestException ).StatusCode == HttpStatusCode.NotFound ) {
						// Network Problem
						return;
					}else if( ( e as SteamRequestException ).StatusCode == HttpStatusCode.Unauthorized ){
						// User is Unauthorized
						throw new SteamAuthenticationException( "SteamChat Client: User is Unauthorized", e );
					}
					// Likely a transient Steam API problem
					System.Diagnostics.Debug.WriteLine( "SteamRequestException Encountered: " + ( e as SteamRequestException ).StatusCode );
				}
				System.Diagnostics.Debug.WriteLine( "Encountered Unexpected Exception: " + e.StackTrace );
				throw e;
			}

		}
Пример #15
0
        private async Task<Tile> GetImage(Tile tile)
        {
            if (!string.IsNullOrEmpty(tile.TileKey))
            {
                try
                {
                    tile.CancellationTokenSource = new CancellationTokenSource(5000);
                    tile.MapImage = await Task.Run<MapImage>(() => GetTile(tile.Column, tile.Row, tile.Level, tile.Resolution, tile.CancellationTokenSource.Token)).AsAsyncOperation<MapImage>();
                    if (tile.CancellationTokenSource.IsCancellationRequested)
                    {
                        tile.CancellationTokenSource.Token.ThrowIfCancellationRequested();
                    }
                    if (tile.MapImage.MapImageType == MapImageType.Url)
                    {
                        HttpClient client = new HttpClient();
                        tile.CancellationTokenSource.Token.Register(() =>
                            {
                                try
                                {
                                    //可能出现的情况是,client已经Dispose了,但是CancellationTokenSource还没来得及Dispose
                                    //这时候Cancel了,此处client由于已经Disopose了,再Cancel会异常。
                                    //需要有方法在client调用Dispose时,先Dispose掉CancellationTokenSource。或者移除掉此函数。
                                    client.CancelPendingRequests();
                                }
                                catch
                                {

                                }
                            });
                        try
                        {
                            tile.MapImage.Data = await client.GetByteArrayAsync(tile.MapImage.Url);
                        }
                        finally
                        {
                            client.Dispose();
                        }
                        if (tile.CancellationTokenSource.IsCancellationRequested)
                        {
                            tile.CancellationTokenSource.Token.ThrowIfCancellationRequested();
                        }
                    }
                    if (tile.MapImage.Data != null && tile.MapImage.Data.Length > 0)
                    {
                        tile.IsSuccessd = true;
                    }
                    return tile;
                }
                catch (Exception ex)
                {
                    //出现异常。

                    return tile;
                }
                finally
                {
                    if (tile.CancellationTokenSource != null)
                    {
                        if (tile.CancellationTokenSource.IsCancellationRequested)
                        {
                            tile.IsCanceled = true;
                        }
                        tile.CancellationTokenSource.Dispose();
                        tile.CancellationTokenSource = null;
                    }
                }
            }
            return null;
        }
Пример #16
0
 public void CancelPendingRequests()
 {
     _builtInHttpClient.CancelPendingRequests();
 }
Пример #17
-7
        public void sendPost()
        {
            // Définition des variables qui seront envoyés
            HttpContent stringContent1 = new StringContent(param1String); // Le contenu du paramètre P1
            HttpContent stringContent2 = new StringContent(param2String); // Le contenu du paramètre P2
            HttpContent fileStreamContent = new StreamContent(paramFileStream);
            //HttpContent bytesContent = new ByteArrayContent(paramFileBytes);

            using (var client = new HttpClient())
            using (var formData = new MultipartFormDataContent())
            {
                formData.Add(stringContent1, "P1"); // Le paramètre P1 aura la valeur contenue dans param1String
                formData.Add(stringContent2, "P2"); // Le parmaètre P2 aura la valeur contenue dans param2String
                formData.Add(fileStreamContent, "FICHIER", "RETURN.xml");
                //  formData.Add(bytesContent, "file2", "file2");
                try
                {
                    var response = client.PostAsync(actionUrl, formData).Result;
                    MessageBox.Show(response.ToString());
                    if (!response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("Erreur de réponse");
                    }
                }
                catch (Exception Error)
                {
                    MessageBox.Show(Error.Message);
                }
                finally
                {
                    client.CancelPendingRequests();
                }
            }
        }