コード例 #1
0
		/// <see cref="IAsyncWebClient.DownloadStringAsync"/>
		public Task<string> DownloadStringAsync(Uri address, IProgress<DownloadProgressChangedEventArgs> progress, CancellationToken cancellationToken)
		{
			cancellationToken.Register(() => _webClient.CancelAsync());

			var cookie = Guid.NewGuid();
			var tcs = new TaskCompletionSource<string>();

			DownloadProgressChangedEventHandler progressHandler = CreateProgressHandler(cookie, progress);
			if (progress != null)
				_webClient.DownloadProgressChanged += progressHandler;

			DownloadStringCompletedEventHandler completedHandler = null;
			completedHandler = (o, e) =>
			{
				if (!Equals(e.UserState, cookie))
					return;

				_webClient.DownloadProgressChanged -= progressHandler;
				_webClient.DownloadStringCompleted -= completedHandler;

				tcs.TrySetFromEventArgs(e, args => args.Result);
			};
			_webClient.DownloadStringCompleted += completedHandler;

			_webClient.DownloadStringAsync(address, cookie);
			return tcs.Task;
		}
コード例 #2
0
ファイル: Extensions.cs プロジェクト: yamiM0NSTER/MonoLib
        public static Task <string> DownloadStringTaskAsync(this WebClient wc, Uri address)
        {
            var token = new object();
            var task  = new TaskCompletionSource <string> ();
            DownloadStringCompletedEventHandler handler = null;

            handler = (s, e) =>
            {
                wc.DownloadStringCompleted -= handler;
                if (e.Error != null)
                {
                    task.TrySetException(e.Error);
                }
                else if (e.Cancelled)
                {
                    task.TrySetCanceled();
                }
                else
                {
                    task.TrySetResult(e.Result);
                }
            };
            wc.DownloadStringCompleted += handler;
            wc.DownloadStringAsync(address, token);
            return(task.Task);
        }
コード例 #3
0
    public static Task <string> DownloadStringTaskAsync(this WebClient client,
                                                        Uri address)
    {
        var tcs = new TaskCompletionSource <string>();

        // The event handler will complete the task and unregister itself.
        DownloadStringCompletedEventHandler handler = null;

        handler = (_, e) =>
        {
            client.DownloadStringCompleted -= handler;
            if (e.Cancelled)
            {
                tcs.TrySetCanceled();
            }
            else if (e.Error != null)
            {
                tcs.TrySetException(e.Error);
            }
            else
            {
                tcs.TrySetResult(e.Result);
            }
        };

        // Register for the event and *then* start the operation.
        client.DownloadStringCompleted += handler;
        client.DownloadStringAsync(address);

        return(tcs.Task);
    }
コード例 #4
0
ファイル: HttpConnection.cs プロジェクト: mt2309/Trading-Game
 public static void httpLongPoll(Uri resource, DownloadStringCompletedEventHandler e, int pollInterval)
 {
     try
     {
         if (timer != null)
         {
             timer.Stop();
         }
         WebClient client = new WebClient();
         client.DownloadStringCompleted += e;
         pollClient = new PollClient()
         {
             client = client,
             resource = resource
         };
         timer = new DispatcherTimer();
         timer.Interval = new TimeSpan(0, 0, 0, pollInterval, 0);
         timer.Tick += new EventHandler(tickRequest);
         timer.Start();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
     }
 }
コード例 #5
0
ファイル: Form1.cs プロジェクト: Dak0r/RocketbeansTV-PIP
        public void DownloadStringAsync(string url, DownloadStringCompletedEventHandler oncomplete)
        {
            WebClient webclient = null;

            try
            {
                webclient = new WebClient();

                RemoteCertificateValidationCallback old = ServicePointManager.ServerCertificateValidationCallback;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidRemoteCertificate);
                webclient.DownloadStringCompleted += oncomplete;
                webclient.DownloadStringAsync(new Uri(url));
                ServicePointManager.ServerCertificateValidationCallback = old;
            }
            catch (Exception ex)
            {
                // throw ex;
            }
            finally
            {
                //if (webclient != null)
                //{
                //    // webclient.Dispose();
                //    //  webclient = null;
                //}
            }
        }
コード例 #6
0
 public void GetNextPageAsync()
 {
     if (HasMorePages)
     {
         var       uri = new Uri(string.Format(SearchLinks.Next, Constants.ApiKey));
         WebClient wc  = new WebClient();
         DownloadStringCompletedEventHandler f = null;
         f = (s, ea) => {
             wc.DownloadStringCompleted -= f;
             dynamic json = DynamicJsonObject.Parse(ea.Result);
             if (Movies == null)
             {
                 Movies = new List <Movie>();
             }
             foreach (var m in json.movies)
             {
                 Movies.Add(new Movie(m, true));
             }
             SearchLinks.Next = new SearchLinks(json.links, json.link_template).Next;
             ++currentPage;
             OnGetNextPageCompleted();
         };
         wc.DownloadStringCompleted += f;
         wc.DownloadStringAsync(uri);
     }
     else
     {
         OnGetNextPageCompleted();
     }
 }
コード例 #7
0
        public static Task <string> DownloadStringTaskAsync(this WebClient client, Uri address)
        {
            var tcs = new TaskCompletionSource <string>();
            //这个时间处理程序完成Task对象,并自行注销
            DownloadStringCompletedEventHandler handler = null;

            handler = (_, e) =>
            {
                client.DownloadStringCompleted -= handler;
                if (e.Cancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (e.Error != null)
                {
                    tcs.TrySetException(e.Error);
                }
                else
                {
                    tcs.TrySetResult(e.Result);
                }
            };
            //登记事件,然后开始操作
            client.DownloadStringCompleted += handler;
            client.DownloadStringAsync(address);
            return(tcs.Task);
        }
コード例 #8
0
        // credit: https://stackoverflow.com/questions/14290988/populate-and-return-entities-from-downloadstringcompleted-handler-in-windows-pho
        public async static Task <string> simpleRequestAsync(string url)
        {
            var tcs    = new TaskCompletionSource <string>();
            var client = new WebClient();

            DownloadStringCompletedEventHandler h = null;

            h = (sender, args) =>
            {
                if (args.Cancelled)
                {
                    tcs.SetCanceled();
                }
                else if (args.Error != null)
                {
                    tcs.SetException(args.Error);
                }
                else
                {
                    tcs.SetResult(args.Result);
                }

                client.DownloadStringCompleted -= h;
            };

            client.DownloadStringCompleted += h;
            client.DownloadString(new Uri(url));

            return(await tcs.Task);
        }
コード例 #9
0
        public static Task <string> DownloadStringAsync(this WebClient webClient, string uri)
        {
            var tcs = new TaskCompletionSource <string>();
            DownloadStringCompletedEventHandler handler = null;

            handler = (s, e) =>
            {
                if (e.Error != null)
                {
                    tcs.SetException(e.Error);
                }
                else if (e.Cancelled)
                {
                    tcs.SetCanceled();
                }
                else
                {
                    tcs.TrySetResult(e.Result);
                }
                webClient.DownloadStringCompleted -= handler;
            };

            webClient.DownloadStringCompleted += handler;
            webClient.DownloadStringAsync(new Uri(uri), webClient);
            return(tcs.Task);
        }
コード例 #10
0
        /// <summary>Downloads the resource with the specified URI as a string, asynchronously.</summary>
        /// <param name="webClient">The WebClient.</param>
        /// <param name="address">The URI from which to download data.</param>
        /// <returns>A Task that contains the downloaded string.</returns>
        public static Task <string> DownloadStringTask(this WebClient webClient, Uri address)
        {
            // Create the task to be returned
            var tcs = new TaskCompletionSource <string>(address);

            // Setup the callback event handler
            DownloadStringCompletedEventHandler handler = null;

            handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => e.Result, () => webClient.DownloadStringCompleted -= handler);
            webClient.DownloadStringCompleted += handler;

            // Start the async work
            try
            {
                webClient.DownloadStringAsync(address, tcs);
            }
            catch (Exception exc)
            {
                // If something goes wrong kicking off the async work,
                // unregister the callback and cancel the created task
                webClient.DownloadStringCompleted -= handler;
                tcs.TrySetException(exc);
            }

            // Return the task that represents the async operation
            return(tcs.Task);
        }
コード例 #11
0
 public void LoadDvdReviewsAsync()
 {
     if (HasMoreDvdReviews)
     {
         WebClient wc = new WebClient();
         DownloadStringCompletedEventHandler f = null;
         f = (s, ea) => {
             wc.DownloadStringCompleted -= f;
             dynamic json = DynamicJsonObject.Parse(ea.Result);
             dvdReviewTotal = DynamicJsonObject.ParseIntFromDyn(json.total);
             if (DvdReviews == null)
             {
                 DvdReviews = new List <Review>();
             }
             foreach (var rev in json.reviews)
             {
                 DvdReviews.Add(new Review(rev));
             }
             OnLoadReviewsCompleted();
         };
         wc.DownloadStringCompleted += f;
         wc.DownloadStringAsync(new Uri(nextDvdReviewLink));
     }
     else
     {
         OnLoadReviewsCompleted();
     }
 }
コード例 #12
0
        public void DeleteFolder(String accessToken, DownloadStringCompletedEventHandler eventHandler, string currentPath)
        {
            var client = new WebClient();

            client.DownloadStringCompleted += eventHandler;
            client.DownloadStringAsync(new Uri(string.Format("https://api.dropboxapi.com/1/fileops/delete/?path={0}&root=sandbox&access_token={1}", currentPath, accessToken)));
        }
    /// <summary>Downloads the resource with the specified URI as a string, asynchronously.</summary>
    /// <param name="webClient">The WebClient.</param>
    /// <param name="address">The URI from which to download data.</param>
    /// <returns>A Task that contains the downloaded string.</returns>
    public static Task <string> DownloadStringTaskAsync(this WebClient webClient, Uri address)
    {
        // Create the task to be returned
        var tcs = new TaskCompletionSource <string>(address);

        // Setup the callback event handler
        DownloadStringCompletedEventHandler completedHandler = null;

        completedHandler = (sender, e) => TaskServices.HandleEapCompletion(tcs, true, e, () => e.Result, () => webClient.DownloadStringCompleted -= completedHandler);
        webClient.DownloadStringCompleted += completedHandler;

        // Start the async operation.
        try
        {
            webClient.DownloadStringAsync(address, tcs);
        }
        catch
        {
            webClient.DownloadStringCompleted -= completedHandler;
            throw;
        }

        // Return the task that represents the async operation
        return(tcs.Task);
    }
コード例 #14
0
 private void loadPage(String url , DownloadStringCompletedEventHandler x)
 {
     WebClient wClient;
     wClient = new WebClient();
     wClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(x);
     wClient.DownloadStringAsync(new Uri(url));
 }
コード例 #15
0
        private static Task <string> DumpWebPageAsync(WebClient client, Uri uri)
        {
            //si utilizza TaskCompletionSource che gestisce un task figlio
            var tcs = new TaskCompletionSource <string>();

            DownloadStringCompletedEventHandler handler = null;

            handler = (sender, args) =>
            {
                client.DownloadStringCompleted -= handler;

                if (args.Cancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (args.Error != null)
                {
                    tcs.TrySetException(args.Error);
                }
                else
                {
                    tcs.TrySetResult(args.Result);
                }
            };

            client.DownloadStringCompleted += handler;
            client.DownloadStringAsync(uri);

            return(tcs.Task);
        }
コード例 #16
0
        private void getCar2GoAccounts(string token, string token_secret, DownloadStringCompletedEventHandler requestCallback)
        {
            var car2GoRequestEndpoint = "https://www.car2go.com/api/v2.1/accounts";

            var parameters = new WebParameterCollection();

            parameters.Add("oauth_callback", "oob");
            parameters.Add("oauth_signature_method", "HMAC-SHA1");
            parameters.Add("oauth_token", token);
            parameters.Add("oauth_version", "1.0");
            parameters.Add("oauth_consumer_key", FreeCarsCredentials.Car2Go.ConsumerKey);
            parameters.Add("oauth_timestamp", OAuthTools.GetTimestamp());
            parameters.Add("oauth_nonce", OAuthTools.GetNonce());
            parameters.Add("format", "json");
            parameters.Add("loc", Car2Go.City);
            //parameters.Add("test", "1");
            var signatureBase = OAuthTools.ConcatenateRequestElements("GET", car2GoRequestEndpoint, parameters);
            var signature     = OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha1, OAuthSignatureTreatment.Escaped, signatureBase, FreeCarsCredentials.Car2Go.SharedSecred, token_secret);

            var requestParameters = OAuthTools.NormalizeRequestParameters(parameters);
            var requestUrl        = new Uri(car2GoRequestEndpoint + "?" + requestParameters + "&oauth_signature=" + signature, UriKind.Absolute);

            var webClient = new WebClient();

            webClient.DownloadStringCompleted += requestCallback;

            webClient.DownloadStringAsync(requestUrl);
        }
コード例 #17
0
        /// <summary>
        /// 从指定url以Get方式获取数据
        /// </summary>
        /// <param name="url"></param>
        /// <param name="completedHandler"></param>
        public void Get(string url, DownloadStringCompletedEventHandler completedHandler)
        {
            WebClient client = new WebClient();

            client.DownloadStringCompleted += completedHandler;
            client.DownloadStringAsync(new Uri(url));
        }
コード例 #18
0
        public static Task <string> DownloadAsync(this WebClient wc, string url)
        {
            TaskCompletionSource <string>       tcs       = new TaskCompletionSource <string>();
            DownloadStringCompletedEventHandler completed = null;

            completed = (s, e) =>
            {
                try
                {
                    tcs.SetResult(e.Result);
                }
                catch (Exception ex)
                {
                    tcs.SetException(ex.InnerException ?? ex);
                }
                finally
                {
                    wc.DownloadStringCompleted -= completed;
                }
            };

            wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows; U; Windows NT 6.1; de; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12";
            wc.DownloadStringCompleted += completed;
            wc.DownloadStringAsync(new Uri(url));

            return(tcs.Task);
        }
コード例 #19
0
        static Task <string> Get()
        {
            WebClient client = new WebClient();

            var tcs = new TaskCompletionSource <string>();
            DownloadStringCompletedEventHandler handler = null;

            handler = (_, e) =>
            {
                client.DownloadStringCompleted -= handler;
                if (e.Cancelled)
                {
                    tcs.TrySetCanceled();
                }
                else if (e.Error != null)
                {
                    tcs.TrySetException(e.Error);
                }
                else
                {
                    tcs.TrySetResult(e.Result);
                }
            };
            client.DownloadStringCompleted += handler;
            client.DownloadStringAsync(new Uri("http://www.baidu.com"));
            return(tcs.Task);
        }
 public static void GetAsync(string inputUri, DownloadStringCompletedEventHandler downloadStringCompleted)
 {
     CommunicationHelper(inputUri, (client, uri) =>
     {
         client.DownloadStringCompleted += downloadStringCompleted;
         client.DownloadStringAsync(uri);
     });
 }
コード例 #21
0
 public void DownloadStringAsync(System.Uri url, DownloadStringCompletedEventHandler webClient_DownloadStringCompleted)
 {
     using (var webClient = new WebClient())
     {
         webClient.DownloadStringCompleted += webClient_DownloadStringCompleted;
         webClient.DownloadStringAsync(url);
     }
 }
コード例 #22
0
ファイル: App.cs プロジェクト: Dev9er/CSharpStudy
        public static bool CallUrl(string url, DownloadStringCompletedEventHandler handler, TimeoutContext tc)
        {
            WebClient wc = new WebClient();

            // wc.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);

            if (handler != null)
            {
                wc.DownloadStringCompleted += handler;
            }

            Uri uri = null;

            try
            {
                uri = new Uri(url);
            }
            catch (FormatException)
            {
                return(false);
            }

            wc.DownloadStringAsync(uri, tc);
            if (tc != null)
            {
                wc.DownloadProgressChanged += tc.wc_DownloadProgressChanged;
                tc.Tag = wc;

                ThreadPool.QueueUserWorkItem(
                    (obj) =>
                {
                    TimeoutContext timeContext = obj as TimeoutContext;
                    if (timeContext == null)
                    {
                        return;
                    }

                    WebClient wcInProgress = timeContext.Tag as WebClient;
                    if (wcInProgress == null)
                    {
                        return;
                    }

                    Thread.Sleep(timeContext.Timeout);
                    if (timeContext.Connected == true)
                    {
                        return;
                    }

                    if (timeContext.Completed == false)
                    {
                        wcInProgress.CancelAsync();
                    }
                }, tc);
            }

            return(true);
        }
コード例 #23
0
        public void GetAppUser(DownloadStringCompletedEventHandler handler)
        {
            string    fql    = "SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = " + UserId + ") AND is_app_user = 1";
            string    test   = "https://graph.facebook.com/fql?q=" + HttpUtility.UrlEncode(fql) + "&access_token=" + FacebookClient.Instance.Token;
            WebClient client = new WebClient();

            client.DownloadStringCompleted += handler;
            client.DownloadStringAsync(new Uri(test));
        }
コード例 #24
0
        private void InvokeSearchComplete(DownloadStringCompletedEventArgs e)
        {
            DownloadStringCompletedEventHandler handler = SearchComplete;

            if (handler != null)
            {
                handler(this, e);
            }
        }
コード例 #25
0
        public void Download(DownloadStringCompletedEventHandler handler)
        {
            Downloader client = new Downloader("hash", null, null);

            client.DownloadString(new List <DownloadStringCompletedEventHandler>()
            {
                new DownloadStringCompletedEventHandler(SetHash), handler
            });
        }
コード例 #26
0
ファイル: App.cs プロジェクト: stjeong/OfficePresenter
        public static bool CallUrl(string url, DownloadStringCompletedEventHandler handler, TimeoutContext tc)
        {
            WebClient wc = new WebClient();
            // wc.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);

            if (handler != null)
            {
                wc.DownloadStringCompleted += handler;
            }

            Uri uri = null;

            try
            {
                uri = new Uri(url);
            }
            catch (FormatException)
            {
                return false;
            }

            wc.DownloadStringAsync(uri, tc);
            if (tc != null)
            {
                wc.DownloadProgressChanged += tc.wc_DownloadProgressChanged;
                tc.Tag = wc;

                ThreadPool.QueueUserWorkItem(
                    (obj) =>
                    {
                        TimeoutContext timeContext = obj as TimeoutContext;
                        if (timeContext == null)
                        {
                            return;
                        }

                        WebClient wcInProgress = timeContext.Tag as WebClient;
                        if (wcInProgress == null)
                        {
                            return;
                        }

                        Thread.Sleep(timeContext.Timeout);
                        if (timeContext.Connected == true)
                        {
                            return;
                        }

                        if (timeContext.Completed == false)
                        {
                            wcInProgress.CancelAsync();
                        }
                    }, tc);
            }

            return true;
        }
コード例 #27
0
        private void ReturnToThisPhone(object sender, RoutedEventArgs e)
        {
            firstStep = new DownloadStringCompletedEventHandler(DidDownloadCurrentState);
            secondStep = new UploadStringCompletedEventHandler(DidTakeOver);

            var x = new WebClient();
            x.DownloadStringCompleted += firstStep;
            x.DownloadStringAsync(new Uri("http://localhost:8008/services/music"));
        }
        /// <summary>
        /// Extends BeginInvoke so that when a state object is not needed, null does not need to be passed.
        /// <example>
        /// downloadstringcompletedeventhandler.BeginInvoke(sender, e, callback);
        /// </example>
        /// </summary>
        public static IAsyncResult BeginInvoke(this DownloadStringCompletedEventHandler downloadstringcompletedeventhandler, Object sender, DownloadStringCompletedEventArgs e, AsyncCallback callback)
        {
            if (downloadstringcompletedeventhandler == null)
            {
                throw new ArgumentNullException("downloadstringcompletedeventhandler");
            }

            return(downloadstringcompletedeventhandler.BeginInvoke(sender, e, callback, null));
        }
コード例 #29
0
ファイル: Get.cs プロジェクト: asebak/rapbattleonline
 /// <summary>
 ///     Initializes a new instance of the <see cref="Get" /> class.
 /// </summary>
 /// <param name="controllerName">Name of the controller.</param>
 /// <param name="id">The identifier.</param>
 /// <param name="e">The e.</param>
 /// <param name="methodUrl">The method URL.</param>
 public Get(string controllerName, int id, DownloadStringCompletedEventHandler e = null, string methodUrl = "")
 {
     var api = new WebApi(controllerName);
     var webClient = new RapWebClient {CookieContainer = RapClientCookie.Current};
     webClient.DownloadStringCompleted += e;
     webClient.DownloadStringAsync(string.IsNullOrEmpty(methodUrl)
         ? new Uri(api.Get(id))
         : new Uri(api.GetByAction(id, methodUrl)));
 }
コード例 #30
0
        public void DownloadJsonAsync <T>(Uri uri, Action <object> onDownloadComplete, Action <Exception> onError)
        {
            Interlocked.Increment(ref procCounter);

            DownloadStringCompletedEventHandler handler = null;

            handler = (_, e) =>
            {
                DownloadStringCompleted -= handler;

                if (e.Error != null)
                {
                    onError.Invoke(e.Error);
                    Interlocked.Decrement(ref procCounter);
                    return;
                }

                string result      = e.Result;
                bool   typeIsArray = typeof(T).IsArray;
                bool   jsonIsArray = result[0] == '[';

                object obj = null;
                try
                {
                    // Make json object an array of 1 if the caller expects an array
                    if (typeIsArray && !jsonIsArray)
                    {
                        result      = $"[{result}]";
                        jsonIsArray = true;
                    }

                    // If json returned was an array when caller expected an object, return the first element if array is size of array is 1, else dont return anything
                    // Else return the expected type
                    if (!typeIsArray && jsonIsArray)
                    {
                        obj = ToolBox.ArrToObj(JsonConvert.DeserializeObject <T[]>(result, settings));
                    }
                    else
                    {
                        obj = JsonConvert.DeserializeObject <T>(result, settings);
                    }
                }
                catch (Exception ex)
                {
                    onError.Invoke(ex);
                    Interlocked.Decrement(ref procCounter);
                    return;
                }

                onDownloadComplete?.Invoke(obj);
                Interlocked.Decrement(ref procCounter);
            };

            DownloadStringCompleted += handler;
            DownloadStringAsync(uri);
        }
コード例 #31
0
        public void GetProfile(string id, DownloadStringCompletedEventHandler handler)
        {
            string    profileUri = API_BASE_URL_SECURE + "streams/user/" + id + ".json";
            WebClient client     = new WebClient();

            client.Encoding = System.Text.Encoding.UTF8;
            client.Headers[HttpRequestHeader.UserAgent] = API_USER_AGENT;
            client.DownloadStringCompleted += handler;
            client.DownloadStringAsync(new Uri(profileUri));
        }
コード例 #32
0
        public void SearchGeneral(string query, DownloadStringCompletedEventHandler handler)
        {
            string    queryUri = API_BASE_URL_SECURE + "search.json?access_token=" + AccessToken + "&q=" + query;
            WebClient client   = new WebClient();

            client.Encoding = System.Text.Encoding.UTF8;
            client.Headers[HttpRequestHeader.UserAgent] = API_USER_AGENT;
            client.DownloadStringCompleted += handler;
            client.DownloadStringAsync(new Uri(queryUri));
        }
コード例 #33
0
        protected virtual void OnDownloadStringCompleted(DownloadStringCompletedEventArgs args)
        {
            CompleteAsync();
            DownloadStringCompletedEventHandler handler = DownloadStringCompleted;

            if (handler != null)
            {
                handler(this, args);
            }
        }
コード例 #34
0
        public void HttpGet(string uri, DownloadStringCompletedEventHandler downloadStringCompleted)
        {
            WebClient webClient = new WebClient();

            using (webClient)
            {
                webClient.DownloadStringCompleted += downloadStringCompleted;
                webClient.DownloadStringAsync(new Uri(uri));
            }
        }
コード例 #35
0
        /**
         * http://stocktwits.com/developers/docs/api#streams-watchlist-docs
         */
        public void GetStreamOfWatchlist(int watchlist_id, DownloadStringCompletedEventHandler handler, int since = 0, int max = 30)
        {
            Uri query = new Uri("https://api.stocktwits.com/api/2/streams/watchlist/" + watchlist_id.ToString() + ".json?access_token=" + AccessToken);

            WebClient client = new WebClient();

            client.Encoding = System.Text.Encoding.UTF8;
            client.Headers[HttpRequestHeader.UserAgent] = API_USER_AGENT;
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(handler);
            client.DownloadStringAsync(query);
        }
コード例 #36
0
        /// <summary>
        ///     Downloads the HTML with progress.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="downloadProgress">The download progress.</param>
        /// <param name="downloadString">The downloaded string.</param>
        /// <returns></returns>
        public static string DownloadHtmlWithProgress(string url, DownloadProgressChangedEventHandler downloadProgress,
                                                      DownloadStringCompletedEventHandler downloadString)
        {
            using (var wc = new WebClient())
            {
                wc.DownloadProgressChanged += downloadProgress;
                wc.DownloadStringCompleted += downloadString;

                return(wc.DownloadString(url));
            }
        }
コード例 #37
0
ファイル: GramotaDownloader.cs プロジェクト: piotrosz/RuDict
        public void DownloadAsync(
            DownloadStringCompletedEventHandler downloadCompetedHandler, string word)
        {
            string url = string.Format("http://gramota.ru/slovari/dic/?word={0}&all=x", HttpUtility.UrlEncode(word, Encoding.GetEncoding("windows-1251")));

            using (var client = new WebClient())
            {
                client.Encoding = Encoding.GetEncoding("windows-1251");

                client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(downloadCompetedHandler);
                client.DownloadStringAsync(new Uri(url));
            }
        }
コード例 #38
0
        public void DownloadAsync(
            DownloadStringCompletedEventHandler downloadCompetedHandler, 
            string word)
        {
            string url = string.Format("http://www.babelpoint.org/russian/glance.php?q={0}", HttpUtility.UrlEncode(word, Encoding.UTF8));

            using (var client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;

                client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(downloadCompetedHandler);
                client.DownloadStringAsync(new Uri(url));
            }
        }
コード例 #39
0
ファイル: GoogleDownloader.cs プロジェクト: piotrosz/RuDict
        public void DownloadAsync(
            DownloadStringCompletedEventHandler downloadCompetedHandler, 
            string word)
        {
            string url = string.Format("http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q={0}&sl=ru&tl=ru&restrict=pr%2Cde&client=te", HttpUtility.UrlEncode(word));

            using (var client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;

                client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(downloadCompetedHandler);
                client.DownloadStringAsync(new Uri(url));
            }
        }
コード例 #40
0
ファイル: RequestService.cs プロジェクト: BurningMan/4sqChat
        public static void MakeGetRequest(AuthData authData, string url, Dictionary<string, string> param, DownloadStringCompletedEventHandler handler)
        {
            url += "?";
            foreach (KeyValuePair<string, string> keyValuePair in param)
            {
                url += String.Format("{0}={1}&", keyValuePair.Key, keyValuePair.Value);
            }

            if (url[url.Length - 1] == '&')
            {
                url = url.Substring(0, url.Length - 1);
            }

            WebClient wc = new WebClient();
            wc.DownloadStringCompleted += handler;
            wc.DownloadStringAsync(new Uri(url));
        }
コード例 #41
0
ファイル: Client.cs プロジェクト: eirikb/extreme-sharepoint
 public static void Request(SPListItem team, IQuestion question, DownloadStringCompletedEventHandler callback)
 {
     var host = "" + team["Host"];
     using (var client = new WebClient())
     {
         var query = string.Format("q={0}", question.Question);
         var url = new UriBuilder(host) {Query = query}.Uri;
         try
         {
             Log.DebugFormat("Sending request to {0}", url);
             client.DownloadStringAsync(url);
             client.DownloadStringCompleted += callback;
         }
         catch (Exception e)
         {
             Log.Error("Request to team " + team.Title, e);
         }
     }
 }
コード例 #42
0
ファイル: WebResourceClient.cs プロジェクト: virmani/Wooter
 public static void GetResourceFromWeb(Uri uri, DownloadStringCompletedEventHandler onDownloadStringCompleted, object userToken)
 {
     WebClient client = new WebClient();
     client.DownloadStringCompleted += onDownloadStringCompleted;
     client.DownloadStringAsync(uri, userToken);
 }
コード例 #43
0
ファイル: KBApiUtil.cs プロジェクト: jarvisji/kanboxwp
 public static void GetFileList(string path, KbToken token, DownloadStringCompletedEventHandler callback)
 {
     Uri pathUrl = new Uri(ListUrl + path);
     WebClient webclient = new WebClient();
     SetHeaderAuthorization(webclient, token);
     webclient.DownloadStringCompleted += callback;
     webclient.DownloadStringAsync(pathUrl);
 }
コード例 #44
0
		/// <summary>
		/// <para>Client performs an initial HTTP POST to obtain a SessionId (sid) assigned to a client, followed
		///  by the heartbeat timeout, connection closing timeout, and the list of supported transports.</para>
		/// <para>The tansport and sid are required as part of the ws: transport connection</para>
		/// </summary>
		/// <param name="uri">http://localhost:3000</param>
		/// <returns>Handshake object with sid value</returns>
		/// <example>DownloadString: 13052140081337757257:15:25:websocket,htmlfile,xhr-polling,jsonp-polling</example>
    protected void requestHandshake(Uri uri, DownloadStringCompletedEventHandler handshakeCallback)
		{
			using (WebClient client = new WebClient())
			{ 
				try
				{
					ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => {
						return true;
					};

          client.DownloadStringCompleted += handshakeCallback;
          Uri handshakeUri = new Uri(string.Format("{0}://{1}:{2}/socket.io/1/{3}", uri.Scheme, uri.Host, uri.Port, uri.Query));
					client.DownloadStringAsync(handshakeUri); // #5 tkiley: The uri.Query is available in socket.io's handshakeData object during authorization
					// 13052140081337757257:15:25:websocket,htmlfile,xhr-polling,jsonp-polling
				}
				catch (Exception ex)
				{
				}
			}
		}
コード例 #45
0
ファイル: Form1.cs プロジェクト: Dakor91/RocketbeansTV-PIP
        public void DownloadStringAsync(string url, DownloadStringCompletedEventHandler oncomplete)
        {
            WebClient webclient = null;
            try
            {
                webclient = new WebClient();

                RemoteCertificateValidationCallback old = ServicePointManager.ServerCertificateValidationCallback;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidRemoteCertificate);
                webclient.DownloadStringCompleted += oncomplete;
                webclient.DownloadStringAsync(new Uri(url));
                ServicePointManager.ServerCertificateValidationCallback = old;

            }
            catch (Exception ex)
            {
                // throw ex;
            }
            finally
            {
                //if (webclient != null)
                //{
                //    // webclient.Dispose();
                //    //  webclient = null;
                //}
            }
        }
コード例 #46
0
ファイル: Game.cs プロジェクト: r-win/XK3Y-Remote-Control
 public void DownloadInfo(DownloadStringCompletedEventHandler handler)
 {
     WebClient c = new WebClient();
     c.DownloadStringCompleted += handler;
     c.DownloadStringAsync(XmlUri);
 }
コード例 #47
0
        private void getCar2GoAccounts(string token, string token_secret, DownloadStringCompletedEventHandler requestCallback)
        {
            var car2GoRequestEndpoint = "https://www.car2go.com/api/v2.1/accounts";

            var parameters = new WebParameterCollection();
            parameters.Add("oauth_callback", "oob");
            parameters.Add("oauth_signature_method", "HMAC-SHA1");
            parameters.Add("oauth_token", token);
            parameters.Add("oauth_version", "1.0");
            parameters.Add("oauth_consumer_key", FreeCarsCredentials.Car2Go.ConsumerKey);
            parameters.Add("oauth_timestamp", OAuthTools.GetTimestamp());
            parameters.Add("oauth_nonce", OAuthTools.GetNonce());
            parameters.Add("format", "json");
            parameters.Add("loc", Car2Go.City);
            //parameters.Add("test", "1");
            var signatureBase = OAuthTools.ConcatenateRequestElements("GET", car2GoRequestEndpoint, parameters);
            var signature = OAuthTools.GetSignature(OAuthSignatureMethod.HmacSha1, OAuthSignatureTreatment.Escaped, signatureBase, FreeCarsCredentials.Car2Go.SharedSecred, token_secret);

            var requestParameters = OAuthTools.NormalizeRequestParameters(parameters);
            var requestUrl = new Uri(car2GoRequestEndpoint + "?" + requestParameters + "&oauth_signature=" + signature, UriKind.Absolute);

            var webClient = new WebClient();
            webClient.DownloadStringCompleted += requestCallback;

            webClient.DownloadStringAsync(requestUrl);
        }
コード例 #48
0
ファイル: HttpConnection.cs プロジェクト: mt2309/Trading-Game
 public static void httpGet(Uri resource, DownloadStringCompletedEventHandler e)
 {
     WebClient client = new WebClient();
     client.DownloadStringCompleted += e;
     client.DownloadStringAsync(resource);
 }
コード例 #49
0
ファイル: Twitter.cs プロジェクト: gaeeyo/Unene
        /*
        private string GenerateSignature(string url, string token, string token_secret, string method,
            out string normalizedUrl, out string normalizedRequestParameters)
        {
            return GenerateSignature(new Uri(url), CONSUMER_KEY, CONSUMER_SECRET,
                token, token_secret, method, GenerateTimeStamp(), GenerateNonce(),
                out normalizedUrl, out normalizedRequestParameters);
        }
         * */
        public void OAuthRequest(string url, string method, string token, string tokenSecret,
            DownloadStringCompletedEventHandler completed)
        {
            string normalizedUrl, normalizedRequestParameters;
            /*
            string hash = GenerateSignature(new Uri(url), CONSUMER_KEY, CONSUMER_SECRET,
                token, tokenSecret, method,
                GenerateTimeStamp(), GenerateNonce(),
                out normalizedUrl, out normalizedRequestParameters);
             * */
            string hash = GenerateSignature(new Uri(url), CONSUMER_KEY, CONSUMER_SECRET,
                token, tokenSecret, method,
                GenerateTimestamp(), GenerateNonce(), out normalizedUrl, out normalizedRequestParameters);

            MyWebClient client = new MyWebClient();

            string signedUrl = normalizedUrl + "?" + normalizedRequestParameters
                + "&" + OAuthSignatureKey + "=" + UrlEncode(hash);

            client.DownloadStringCompleted += completed;
            client.DownloadStringAsync(new Uri(signedUrl));
        }
コード例 #50
0
ファイル: DataLoader.cs プロジェクト: JQE/XK3Y-Remote-Control
        private static void GetData(Uri uri, bool async, DownloadStringCompletedEventHandler handler)
        {
            // First, find the data.xml file, and apply it to the coverloader
            AutoResetEvent evt = async ? null : new AutoResetEvent(false);
            WebClient c = new WebClient();

            c.DownloadStringCompleted += handler;
            c.DownloadStringAsync(uri, evt);

            if (evt != null) evt.WaitOne();
        }
コード例 #51
0
ファイル: Twitter.cs プロジェクト: gaeeyo/Unene
 public bool OAuthRequest(string url, string method, DownloadStringCompletedEventHandler completed)
 {
     if (Account == null || string.IsNullOrEmpty(Account.AccessToken) || string.IsNullOrEmpty(Account.AccessTokenSecret))
     {
         return false;
     }
     OAuthRequest(url, method, Account.AccessToken, Account.AccessTokenSecret, completed);
     return true;
 }