Exemple #1
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //http://google.com
            //http://countdown.api.tfl.gov.uk/interfaces/ura/instant_V1
            //http://countdown.api.tfl.gov.uk/interfaces/ura/instant_V1?StopCode1=52053&DirectionID=1&VisitNumber=1&ReturnList=StopCode1,StopPointName,LineName,DestinationText,EstimatedTime,MessageUUID,MessageText,MessagePriority,MessageType,ExpireTime

            //53347 - Queens Avenue towards Archway

            var serviceUrl = "http://countdown.api.tfl.gov.uk/interfaces/ura/instant_V1?StopCode1=52053&DirectionID=1&VisitNumber=1&ReturnList=StopCode1,StopPointName,LineName,DestinationText,EstimatedTime,MessageUUID,MessageText,MessagePriority,MessageType,ExpireTime";
            var client = new System.Net.Http.HttpClient();
  
            //var responseStream = await client.GetStreamAsync(serviceUrl);
            //var reader = new StringReader(responseText);
            //while(reader.I.ReadLine())

            var responseText = await client.GetStringAsync(serviceUrl);
            responseText = responseText.Replace("]", "],");
            responseText = string.Format("[{0}]", responseText);

            var ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseText));

            var serializer = new DataContractJsonSerializer(typeof(object[][]));
            var response = (object[][])serializer.ReadObject(ms);

            textResult.Text = response.Length.ToString();
        }
Exemple #2
0
 public async Task<System.Net.IPAddress> DetectPublicIP(int timeoutMs)
 {
     string url = $"https://api.ipify.org?ticks={System.DateTime.Now.Ticks}";
     var client = new System.Net.Http.HttpClient();
     client.Timeout = TimeSpan.FromMilliseconds(timeoutMs);
     var response = await client.GetStringAsync(url);
     return System.Net.IPAddress.Parse(response);
 }
        public async Task ネットからのデータ取得テスト()
        {
            var client = new System.Net.Http.HttpClient();
            var text = await client.GetStringAsync("http://www.yahoo.co.jp/");

            // 意図したデータが取得できているかの確認(以下の確認は適当です)
            Assert.AreNotEqual(text.Length, 0, "取得したテキストの長さは0にならない");
        }
Exemple #4
0
        public DTO.MainData Query(string text, string apikey = AppId, string lang = "ru_RU", string type = "biz", int results = 10)
        {
            DTO.MainData myData = null;
            var client = new System.Net.Http.HttpClient();
            var queryString = string.Format("https://search-maps.yandex.ru/v1/?text={0}&type={1}&lang={2}&apikey={3}&results={4}", text, type, lang, apikey, results);

            var result = client.GetStringAsync(queryString).Result;
            myData = JsonConvert.DeserializeObject<DTO.MainData>(result);

            return myData;
        }
Exemple #5
0
 // <ExceptionFilter>
 public static async Task<string> MakeRequest()
 { 
     var client = new System.Net.Http.HttpClient();
     var streamTask = client.GetStringAsync("https://localHost:10000");
     try {
         var responseText = await streamTask;
         return responseText;
     } catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("301"))
     {
         return "Site Moved";
     }
 }
Exemple #6
0
        private async void init_hotsearct()
        {
            var httpclient = new System.Net.Http.HttpClient();
            var jsondata   = await httpclient.GetStringAsync("http://mobilecdn.kugou.com/api/v3/search/hot?count=8&plat=0");

            var obj     = Windows.Data.Json.JsonObject.Parse(jsondata);
            var arryobj = obj.GetNamedObject("data").GetNamedArray("info");

            for (int i = 0; i < 8; i++)
            {
                var item   = (GridViewItem)(HotSearchView.Items[i]);
                var button = (Button)item.Content;
                button.Content = arryobj[i].GetObject().GetNamedString("keyword");
            }
            HotSearchView.Visibility = Visibility.Visible;
            var result = SearchBox.Focus(FocusState.Pointer);
        }
Exemple #7
0
        private static async Task <IEnumerable <Uri> > ProcessHtml(System.Net.Http.HttpClient client, string path, string fileName, Uri uri, System.Threading.CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                throw new OperationCanceledException(cancellationToken);
            }

            var html = await client.GetStringAsync(uri);

            // create the directory
            System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(fileName));

            // save the HTML
            System.IO.File.WriteAllText(fileName, html);

            return(GetLinks(html, uri));
        }
        internal static async Task <string> DownloadStringAsyncCookie(Int32 TimeOut, string UserAgent, string[][] RequestHeader, Uri DownloadUrl, string cookieString)
        {
            try
            {
                //Set the cookies to container
                System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
                foreach (string cookieSingle in cookieString.Split(','))
                {
                    Match cookieMatch = Regex.Match(cookieSingle, "(.+?)=(.+?);");
                    if (cookieMatch.Captures.Count > 0)
                    {
                        string CookieName  = cookieMatch.Groups[1].ToString().Replace(" ", String.Empty);
                        string CookieValue = cookieMatch.Groups[2].ToString().Replace(" ", String.Empty);
                        cookieContainer.Add(DownloadUrl, new System.Net.Cookie(CookieName, CookieValue));
                    }
                }

                using (System.Net.Http.HttpClientHandler httpHandler = new System.Net.Http.HttpClientHandler())
                {
                    httpHandler.CookieContainer = cookieContainer;
                    using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient(httpHandler))
                    {
                        httpClient.Timeout = TimeSpan.FromMilliseconds(TimeOut);
                        httpClient.DefaultRequestHeaders.Add("User-Agent", UserAgent);
                        httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache, no-store");
                        if (RequestHeader != null)
                        {
                            foreach (String[] StringArray in RequestHeader)
                            {
                                httpClient.DefaultRequestHeaders.Add(StringArray[0], StringArray[1]);
                            }
                        }

                        string ConnectTask = await httpClient.GetStringAsync(DownloadUrl);

                        Debug.WriteLine("DownloadStringAsyncCookie succeeded for url: " + DownloadUrl + " / " + ConnectTask.Length + "bytes");
                        return(ConnectTask);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("DownloadStringAsyncCookie exception for url: " + DownloadUrl + " / " + ex.Message);
                return(String.Empty);
            }
        }
Exemple #9
0
            public async Task Load()
            {
                try
                {
                    if (isInternetAvailable)
                    {
                        MoreListVisibility = "Collapsed";
                        var httpclient = new System.Net.Http.HttpClient();
                        var json       = await httpclient.GetStringAsync("http://www.kuaidi100.com/query?type=" + com + "&postid=" + num);

                        var obj = Windows.Data.Json.JsonObject.Parse(json);
                        message = obj.GetNamedString("message");
                        if (message == "ok")
                        {
                            ischeck = obj.GetNamedString("ischeck");
                            var array = obj.GetNamedArray("data");
                            data = new List <Data>();
                            foreach (var item in array)
                            {
                                data.Add(new Data()
                                {
                                    time = item.GetObject()["time"].GetString(), context = item.GetObject()["context"].GetString()
                                });
                            }
                            var tempkdfile = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("tempkdfile", Windows.Storage.CreationCollisionOption.OpenIfExists);

                            var temparray = Windows.Data.Json.JsonArray.Parse(await Windows.Storage.FileIO.ReadTextAsync(tempkdfile));
                            for (int i = 0; i < temparray.Count; i++)
                            {
                                if (temparray[i].GetObject().GetNamedString("num") == num)
                                {
                                    temparray[i].GetObject().Remove("time");
                                    temparray[i].GetObject().Add("time", Windows.Data.Json.JsonValue.CreateStringValue(newdata.time));
                                    await Windows.Storage.FileIO.WriteTextAsync(tempkdfile, temparray.ToString());

                                    break;
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
Exemple #10
0
        private async static Task AnalyzeSite(string urlPart, byte trys)
        {
            trys--;
            if (trys < 0)
            {
                return;
            }

            string content = "";

            using (var hc = new System.Net.Http.HttpClient()) {
                try {
                    content = await hc.GetStringAsync(ROOT_URL + urlPart);
                } catch (Exception e) {
                    Console.WriteLine(ROOT_URL + urlPart + ": " + e.Message);
                }
            }

            var tasks = new List <Task>();

            foreach (Match match in Regex.Matches(content, "href=\"/([^\"#\\?:.]*)[\"#\\?]"))
            {
                lock (knownSites) {
                    if (knownSites.Contains(match.Groups[1].Value) || match.Groups[1].Value.Contains("node"))
                    {
                        continue;
                    }
                    else
                    {
                        knownSites.Add(match.Groups[1].Value);
                    }
                }

                tasks.Add(AnalyzeSite(match.Groups[1].Value, trys));
            }

            await Task.WhenAll(tasks.ToArray());

            var count = Regex.Matches(content, "(?:^|\\W)Game(?:$|\\W)", RegexOptions.IgnoreCase).Count;

            Interlocked.Add(ref ocurrences, count);
            Console.WriteLine("Try Nr. " + (3 - trys) + ": Reading from " + ROOT_URL + urlPart + " Words " + count);

            return;
        }
        public async void GetSingerInfo(string singerid)
        {
            try
            {
                var httpclient = new System.Net.Http.HttpClient();
                var json       = await httpclient.GetStringAsync("http://mobilecdn.kugou.com/api/v3/singer/info?singerid=" + singerid);

                json = json.Replace("{size}", "150");
                var obj = Windows.Data.Json.JsonObject.Parse(json);
                singerimg.ImageSource = new Windows.UI.Xaml.Media.Imaging.BitmapImage()
                {
                    UriSource = new Uri(obj.GetNamedObject("data").GetNamedString("imgurl"))
                };
            }
            catch (Exception)
            {
            }
        }
        public async void UpdateContent()
        {
            using (System.Net.Http.HttpClient cli = new System.Net.Http.HttpClient())
            {
                var input = await cli.GetStringAsync(ThreadUri);

                var doc = new HtmlDocument();
                doc.LoadHtml(input);

                var content = doc.DocumentNode.SelectNodes("//*[contains(@class,'thread-message-content-body-text thread-full-message')]");
                Description     = WebUtility.HtmlDecode(content[0].InnerText.Trim());
                HtmlDescription = content[0].InnerHtml;

                var img = doc.DocumentNode.SelectNodes("//*[contains(@class,'profile-image hidden-rsp')]");
                var url = WebUtility.HtmlDecode(img[0].Attributes["src"].Value.Trim());
                AuthorPicture = new Uri(url);
            }
        }
Exemple #13
0
        /// <summary>
        /// Async background method
        /// <para>Calls Zephyr API for ZephyrData structure to evaluate and add result to OutputData</para>
        /// </summary>
        private async void DoBackgroundWork(CancellationToken cancelToken)
        {
            try
            {
                var JSONSerializer = new JavaScriptSerializer();
                using (var HttpClient = new System.Net.Http.HttpClient())
                    while (true)
                    {
                        cancelToken.ThrowIfCancellationRequested();
                        string JSON = await HttpClient.GetStringAsync(URL);

                        var Data = JSONSerializer.Deserialize <ZephyrData>(JSON);
                        OutputData.Items.Insert(0, SelectedOutputMethod(Data.Evaluate()));
                        await Task.Delay(1000);
                    }
            }
            catch (OperationCanceledException) { }
        }
Exemple #14
0
        public static async Task <bool?> AdSoyadZatenVarMı(string adSoyad)
        {
            try
            {
                using (var istemci = new System.Net.Http.HttpClient())
                {
                    var jsonStr = await istemci.GetStringAsync(KullanıcılarUrl + $"/AdSoyadZatenVarMı/{adSoyad}");

                    return(Newtonsoft.Json.JsonConvert.DeserializeObject <bool>(jsonStr));
                }
            }
            catch (Exception ex)
            {
                await HazırlaWebYardımcı.HataKaydet(ex);

                throw ex;
            }
        }
Exemple #15
0
        private static async Task <string> GetWebPageTitle(string url)
        {
            Stopwatch watch = new Stopwatch();

            watch.Restart();
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            Task <string> task     = client.GetStringAsync(url);
            string        contents = await task;

            Match match = regex.Match(contents);

            if (match.Success)
            {
                watch.Stop();
                return(match.Groups[1].Captures[0].Value + " elapsed: " + watch.Elapsed);
            }
            return(string.Empty);
        }
Exemple #16
0
        async void btnTestRESTService_Onclicked(object sender, EventArgs e)
        {
            try
            {
                filePath.Text    = "";
                aiBusy.IsRunning = true;

                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
                filePath.Text = await client.GetStringAsync("http://content.nitware.com.ng/api/values");

                aiBusy.IsRunning = false;
            }
            catch (Exception ex)
            {
                aiBusy.IsRunning = false;
                await DisplayAlert("ERROR", ex.ToString(), "Ok");
            }
        }
        public async Task <string> GetSharedAccessSignature()
        {
            try
            {
                functionUrl = DefaultSettings.FunctionAppUrl;

                System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

                var sas = await client.GetStringAsync($"{functionUrl}/getsastoken");

                return(sas);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
            return("");
        }
            public static async Task <SongLsitData> GetData(string id)
            {
                try
                {
                    var httpclient = new System.Net.Http.HttpClient();
                    var json       = await httpclient.GetStringAsync("http://mobilecdn.kugou.com/api/v3/special/song?pagesize=-1&plat=0&page=1&version=8150&specialid=" + id);

                    json = json.Replace("320hash", "hash320");
                    var obj  = Windows.Data.Json.JsonObject.Parse(json);
                    var data = new SongLsitData();
                    data.List = Class.data.DataContractJsonDeSerialize <ObservableCollection <SongData> >(obj.GetNamedObject("data").GetNamedArray("info").ToString());
                    return(data);
                }
                catch (Exception)
                {
                    return(null);
                }
            }
Exemple #19
0
        public async Task <CoordServiceResult> Lookup(string location)
        {
            var result = new CoordServiceResult()
            {
                Success = false,
                Message = "Undetermined failure while looking up coordinates"
            };

            //lookup coordinates

            var bingKey     = Startup.Configuration["AppSettings:BingKey"];
            var encodedName = WebUtility.UrlEncode(location);
            var url         = $"http://dev.virtualearth.net/REST/v1/Locations?q={encodedName}&key={bingKey}";

            var client = new System.Net.Http.HttpClient();

            var json = await client.GetStringAsync(url);

            var results   = JObject.Parse(json);
            var resources = results["resourceSets"][0]["resources"];

            if (!resources.HasValues)
            {
                result.Message = $"Could not find '{location}' as a location";
            }
            else
            {
                var confidence = (string)resources[0]["confidence"];
                if (confidence != "High")
                {
                    result.Message = $"Could not find a confident match for '{location}' as a location";
                }
                else
                {
                    var coords = resources[0]["geocodePoints"][0]["coordinates"];
                    result.Latitude  = (double)coords[0];
                    result.Longitude = (double)coords[1];
                    result.Success   = true;
                    result.Message   = "Success";
                }
            }

            return(result);
        }
Exemple #20
0
        async void GetJoke(string category)
        {
            Joke myJoke = new Joke();

            string url = "https://sv443.net/jokeapi/v2/joke/" + category + "?type=single";

            var handler = new System.Net.Http.HttpClientHandler();

            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler);
            string result = await client.GetStringAsync(url);

            myJoke = Newtonsoft.Json.JsonConvert.DeserializeObject <Joke>(result);

            Intent listView = new Intent(this, typeof(viewDetails));

            listView.PutExtra("category", category);
            listView.PutExtra("joke", myJoke.joke);
            StartActivity(listView);
        }
Exemple #21
0
        private void getMetadata(Movie movie)
        {
            var name   = movie.name;
            var url    = $"http://www.omdbapi.com/?t={name.Replace(' ', '+')}&y=&plot=short&r=json";
            var client = new System.Net.Http.HttpClient();
            var source = client.GetStringAsync(url).Result;

            var json = JsonConvert.DeserializeObject <omdb>(source);

            if (json.Response == "False")
            {
                return;
            }
            movie.year        = int.Parse(Regex.Replace(json.Year, @"[^\d]", ""));
            movie.director    = json.Director;
            movie.description = json.Plot;
            movie.genre       = json.Genre.Split(',').First();
            movie.poster      = json.Poster;
        }
Exemple #22
0
        public async Task <string> GetJsonAsync(Uri uri, string selectToken = "", Formatting format = Formatting.None)
        {
            try
            {
                //await Task.CompletedTask;
                var strg = await _client.GetStringAsync(uri);

                var json = JToken.Parse(strg).SelectToken(selectToken);
                return(json?.ToString(format));
            }
            catch (System.Net.Http.HttpRequestException)
            {
                throw;
            }
            finally
            {
                //_client?.Dispose();
            }
        }
Exemple #23
0
        public async void GetCurrentPriceAndModel(string url)
        {
            var httpClient = new System.Net.Http.HttpClient();
            var html       = await httpClient.GetStringAsync(url);

            var htmlDocument = new HtmlDocument();

            htmlDocument.LoadHtml(html);

            var model = htmlDocument.DocumentNode.Descendants("div")
                        .Where(node => node.GetAttributeValue("class", "")
                               .Contains("description-panel js-block-video-to-hide left-position active")).ToList();

            if (htmlDocument.DocumentNode.Descendants("div").Any(n => n.GetAttributeValue("class", "").Contains("description-panel js-block-video-to-hide left-position active")))
            {
                var modelName = htmlDocument.DocumentNode.SelectSingleNode("//h2");
                Console.WriteLine(modelName.InnerHtml);

                var nuo = htmlDocument.DocumentNode.SelectSingleNode("//small");

                foreach (var item in model)
                {
                    if (item.Descendants("span").Any(n => n.GetAttributeValue("itemprop", "").Contains("lowPrice")))
                    {
                        var price = Regex.Match(
                            item.Descendants("span")
                            .Where(node => node.GetAttributeValue("itemprop", "")
                                   .Equals("lowPrice")).FirstOrDefault().InnerText.Trim()
                            , @"\d+.\d+");

                        Console.WriteLine($"Price: {nuo.InnerHtml} {price} Eur.");
                    }
                    else
                    {
                        Console.WriteLine("No price in this page!");
                    }
                }
            }
            else
            {
                Console.WriteLine("Is this car model from Paugeot salon! Please, check it and try again.");
            }
        }
Exemple #24
0
        public static async Task <MVData> get_mv_url(string hash)
        {
            try
            {
                var sign    = MD5.GetMd5String(hash + "kugoumvcloud");
                var request = new System.Net.Http.HttpClient();
                var json    = await request.GetStringAsync("http://trackermv.kugou.com/interface/index?cmd=100&pid=2&ext=mp4&hash=" + hash + "&quality=3&key=" + sign);

                JsonObject obj = JsonObject.Parse(json);
                obj.GetNamedObject("mvdata").Add("songname", JsonValue.CreateStringValue(obj.GetNamedString("songname")));
                obj.GetNamedObject("mvdata").Add("singer", JsonValue.CreateStringValue(obj.GetNamedString("singer")));
                json = obj.GetNamedObject("mvdata").ToString();
                return(data.DataContractJsonDeSerialize <MVData>(json));
            }
            catch (Exception)
            {
                return(null);
            }
        }
        public Task <IEnumerable <ISearchItem <string> > > GetItemsTask(string query, IReadOnlyList <Candidate> addedItems)
        {
            return(Task.Run(() =>
            {
                List <ISearchItem <string> > items = new List <ISearchItem <string> >();
                if (query.Contains("quote"))
                {
                    if (quote == null)
                    {
                        using (var client = new System.Net.Http.HttpClient())
                        {
                            client.GetStringAsync("https://zenquotes.io/api/today").ContinueWith(t => {
                                dynamic json = Newtonsoft.Json.Linq.JArray.Parse(t.Result);
                                quote = (string)json[0]["q"] + " - " + (string)json[0]["a"];
                                t.Dispose();
                            }, TaskContinuationOptions.OnlyOnRanToCompletion).Wait(10000);
                        }
                    }
                    items.Add(new CommandItem("Quote of the Day", () => Process.Start("https://zenquotes.io"), quote, "Go to Url")
                    {
                        TopRight = "Inspirational quotes provided by https://zenquotes.io/ ZenQuotes API", IconChar = ''
                    });

                    string random = null;
                    using (var client = new System.Net.Http.HttpClient())
                    {
                        client.GetStringAsync("https://zenquotes.io/api/random").ContinueWith(t => {
                            dynamic json = Newtonsoft.Json.Linq.JArray.Parse(t.Result);
                            random = (string)json[0]["q"] + " - " + (string)json[0]["a"];
                            t.Dispose();
                        }, TaskContinuationOptions.OnlyOnRanToCompletion).Wait(10000);
                    }
                    if (random is string)
                    {
                        items.Add(new CommandItem("Random Quote", () => Process.Start("https://zenquotes.io"), random, "Go to Url")
                        {
                            TopRight = "Inspirational quotes provided by https://zenquotes.io/ ZenQuotes API", IconChar = ''
                        });
                    }
                }
                return items.AsEnumerable();
            }));
        }
        private async Task <List <Period> > GetWeather(string URL, int rows)
        {
            Forecast Forecast = new Forecast();

            try
            {
                var WeatherJson = await client.GetStringAsync(URL);

                var w       = JsonConvert.DeserializeObject <Weather>(WeatherJson);
                var periods = w.properties.periods.Take(rows);

                return(periods.ToList());
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return(new List <Period>());
        }
Exemple #27
0
        public async Task <IMarketData> GetMarketDataAsync(string stockTicker)
        {
            try
            {
                var url = $"{_serviceEntryPoint}{stockTicker}/quote";
                using (System.Net.Http.HttpClient hc = new System.Net.Http.HttpClient())
                {
                    var resultStr = await hc.GetStringAsync(url);

                    var marketData = JsonConvert.DeserializeObject <IexMarketData>(resultStr);
                    return(marketData);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        public async Task <bool> Init()
        {
            bool bResult = true;

            using (var client = new System.Net.Http.HttpClient())
            {
                string sIpfsUrl = String.Format("{0}/{1}", CONST_INFURA_IPFS_GATEWAY_URL, "QmXcsGDQthxbGW8C3Sx9r4tV9PGSj4MxJmtXF7dnXN5XUT");

                msRulesContents = await client.GetStringAsync(sIpfsUrl).ConfigureAwait(false);
            }

            // By setting the addresses to NULL, we indicates that we want the API to deploy the contracts for us
            if (msContractAddress == null)
            {
                msEngineContractAddress   = null;
                msRegistryContractAddress = null;
                msTestContractAddress     = null;
            }
            // By using the indicator "DEPLOY" here, we will manually deploy the contracts ourselves
            else if (msContractAddress == "DEPLOY")
            {
                msEngineContractAddress = await DeployWonka().ConfigureAwait(false);
            }
            // Else, we will use existing contracts on the test chain
            else
            {
                if (msContractAddress == "")
                {
                    msEngineContractAddress = "0xfB419DEA1f28283edAD89103fc1f1272f7573E6A";
                }
                else
                {
                    msEngineContractAddress = msContractAddress;
                }

                msRegistryContractAddress = "0x7E618a3948F6a5D2EA6b92D8Ce6723a468540CaA";
                msTestContractAddress     = "0x4092bc250ef6c384804af2f871Af9c679b672d0B";
            }

            await InitEngineAsync(mbInitChainEnv).ConfigureAwait(false);

            return(bResult);
        }
Exemple #29
0
        public static async Task <string> MakeRequestWithNotModifiedSupport()
        {
            var client     = new System.Net.Http.HttpClient();
            var streamTask = client.GetStringAsync("https://localHost:10000");

            try
            {
                var responseText = await streamTask;
                return(responseText);
            }
            catch (System.Net.Http.HttpRequestException e) when(e.Message.Contains("301"))
            {
                return("Site Moved");
            }
            catch (System.Net.Http.HttpRequestException e) when(e.Message.Contains("304"))
            {
                return("Use the Cache");
            }
        }
Exemple #30
0
 // </HandleNotChanged>
 
 // <AwaitFinally>
 public static async Task<string> MakeRequestAndLogFailures()
 { 
     await logMethodEntrance();
     var client = new System.Net.Http.HttpClient();
     var streamTask = client.GetStringAsync("https://localHost:10000");
     try {
         var responseText = await streamTask;
         return responseText;
     } catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("301"))
     {
         await logError("Recovered from redirect", e);
         return "Site Moved";
     }
     finally
     {
         await logMethodExit();
         client.Dispose();
     }
 }
Exemple #31
0
        public async Task <PreviouslySubmitted> PreviouslySubmittedAsyncByJobId(string jobId)
        {
            //String content = null;
            try
            {
                string url = @"http://localhost:56491/api/GetSubmittedByJobId?jobId=" + jobId;

                //response = await httpClient.GetStringAsync( url );

                var response = await httpClient.GetStringAsync(url).ConfigureAwait(false);

                PreviouslySubmitted previouslySubmitted = JsonConvert.DeserializeObject <PreviouslySubmitted>(response);
                return(previouslySubmitted);
                //
            }
            catch (System.Net.Http.HttpRequestException ex)
            {
                ConEx.Log(ex.StackTrace);
            }
            catch (TaskCanceledException ex)
            {
                ConEx.Log(ex.StackTrace);
            }
            catch (System.Exception ex)
            {
                ConEx.Log(ex.StackTrace);
            }

            /*
             * try
             * {
             *  PreviouslySubmitted previouslySubmitted = JsonConvert.DeserializeObject<PreviouslySubmitted>( content );
             *  return previouslySubmitted;
             * }
             * catch (Exception ex)
             * {
             *  return null;
             * }
             */
            return(null);
            //
        }
Exemple #32
0
        public static async Task CountWordsOnPageRecursive(string url, int depth = 3)
        {
            string content;

            using (var hc = new System.Net.Http.HttpClient())
            {
                try
                {
                    content = await hc.GetStringAsync(url);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(url + ": " + exception.Message);
                    return;
                }
            }

            Console.WriteLine("{2} -> {0}: {1}", url, Regex.Matches(content, "Game", RegexOptions.IgnoreCase).Count, depth);

            if (depth >= 0)
            {
                List <Task> tasks = new List <Task>();

                foreach (Match match in Regex.Matches(content, "href=\"/([^\"#\\?:.]*)[\"#\\?]"))
                {
                    var link = baseUrl + match.Groups[1].Value;

                    lock (checkedLinks)
                    {
                        if (checkedLinks.Contains(link) || link.Contains("node"))
                        {
                            continue;
                        }
                        checkedLinks.Add(link);
                    }

                    tasks.Add(Task.Run(() => CountWordsOnPageRecursive(link, depth - 1)));
                }

                await Task.WhenAll(tasks.ToArray());
            }
        }
Exemple #33
0
            public async Task LoadData()
            {
                try
                {
                    page = page + 1;
                    var httpclient = new System.Net.Http.HttpClient();
                    var json       = await httpclient.GetStringAsync("http://mobilecdn.kugou.com/api/v3/singer/mv?pagesize=20&singerid=" + singerid + "&plat=0&page=" + page.ToString() + "&version=8150");

                    var obj  = Windows.Data.Json.JsonObject.Parse(json);
                    var data = Class.data.DataContractJsonDeSerialize <ObservableCollection <MVData> >(obj.GetNamedObject("data").GetNamedArray("info").ToString());
                    foreach (var item in data)
                    {
                        List.Add(item);
                    }
                }
                catch (Exception)
                {
                    page = page - 1;
                }
            }
Exemple #34
0
        // <ExceptionFilterOld>
        public static async Task <string> MakeRequest()
        {
            var client     = new System.Net.Http.HttpClient();
            var streamTask = client.GetStringAsync("https://localHost:10000");

            try {
                var responseText = await streamTask;
                return(responseText);
            } catch (System.Net.Http.HttpRequestException e)
            {
                if (e.Message.Contains("301"))
                {
                    return("Site Moved");
                }
                else
                {
                    throw;
                }
            }
        }
        async Task <int> ICityBikeDataFetcher.GetBikeCountInStation(string stationName)
        {
            if (stationName.Any(c => char.IsDigit(c)))
            {
                throw new System.ArgumentException();
            }

            System.Net.Http.HttpClient Client = new System.Net.Http.HttpClient();
            string data = await Client.GetStringAsync("http://api.digitransit.fi/routing/v1/routers/hsl/bike_rental");

            BikeRentalStationList list    = JsonConvert.DeserializeObject <BikeRentalStationList>(data);
            BikeRentalStation     station = list.getStationByName(stationName);

            if (station == null)
            {
                throw new NotFoundException();
            }

            return(station.BikesAvailable);
        }
Exemple #36
0
        public async void FetchXMLFeed()
        {
            // Fetch the XML from the web
            System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
            string response = await client.GetStringAsync("http://www.massdot.state.ma.us/feeds/qmaticxml/qmaticXML.aspx");

            // Convert the response into an XML document
            var xmlDoc = System.Xml.Linq.XDocument.Load((new System.IO.StringReader(response)));

            // Iterate through the branches in the document and update the times
            foreach (var item in xmlDoc.Descendants("branch"))
            {
                if (this.Items.Any(c => c.Town == (string)item.Element("town")))
                {                    
                    Branch location = this.Items.First(c => c.Town == (string)item.Element("town"));
                    location.LicensingWait = ((string)item.Element("licensing"));
                    location.RegistrationWait = ((string)item.Element("registration"));
                }
            }
        }
Exemple #37
0
        public static async Task <bool?> GirişİsimZatenKullanıldıMı(string girişİsim)
        {
            try
            {
                await HazırlaWebYardımcı.AyıklamaKaydet("Into...");

                using (var istemci = new System.Net.Http.HttpClient())
                {
                    var jsonStr = await istemci.GetStringAsync(KullanıcılarUrl + $"/GirişİsimZatenKullanıldıMı/{girişİsim}");

                    return(Newtonsoft.Json.JsonConvert.DeserializeObject <bool>(jsonStr));
                }
            }
            catch (Exception ex)
            {
                await HazırlaWebYardımcı.HataKaydet(ex);

                throw ex;
            }
        }
 public async System.Threading.Tasks.Task<OwnCarousel> GetLessonPreviewAds(int id)
 {
     using (var http = new System.Net.Http.HttpClient())
     {
         var result = await http.GetStringAsync($"{ _appConfig.ManagementPortalUrl }/api/lessonpreview/{ id }/ads");
         var ads = Newtonsoft.Json.JsonConvert.DeserializeObject<OwnCarousel>(result);
         return ads;
     }
 }
		private async Task DoProcessLanguageData ()
		{
			Translation.RefreshAllText ();
			if (Translation.IsTextReady) {
				SetLabelStage (l1, l11, l12, ProcessStep.Ready);
				if (step == 0)
					step++;
				await DoStep ();
				return;
			}
			System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient ();
			httpClient.Timeout = new TimeSpan (0, 0, 0, 10, 500);
			httpClient.DefaultRequestHeaders.ExpectContinue = false;
			string url = string.Format ("{0}Content/Languages/{1}.txt", Global.BaseUrl, Translation.Language);
			//Tools.Trace("Url: " + url);
			string ImmediateResult = string.Empty;
			Tools.Trace ("Loading : " + url);
			try {
				ImmediateResult = await httpClient.GetStringAsync (url);
				//Tools.Trace("Result : " + ImmediateResult);
			} catch (Exception err) {
				Tools.Trace ("Loading language error: " + err.Message);
				//try {
				//    ImmediateResult = await httpClient.GetStringAsync (url);
				//} catch (Exception err2) {
				//    Tools.Trace("Second Loading language error: " + err2.Message);
				SetLabelStage (l1, l11, l12, ProcessStep.Broken);
				//}
			}
			if (ImmediateResult.Length > 0) {
				SetLabelStage (l1, l11, l12, ProcessStep.Processing);
				Translation.NewTranslation (ImmediateResult);
				SetLabelStage (l1, l11, l12, ProcessStep.Ready);
			}
			if (step == 0)
				step++;
			await DoStep ();
		}
        private string GetUserName(ICookieGetter cookieGetter)
        {
            try
            {
                System.Net.CookieContainer container = new CookieContainer();
                Cookie cookie = cookieGetter.GetCookie(new Uri(VerifyUrl), CookieKey);
                string res = null;
                if (cookie != null)
                {
                    container.Add(cookie);
                    using (var client = new System.Net.Http.HttpClient(
                        new System.Net.Http.HttpClientHandler() { CookieContainer = container })
                        { Timeout = TimeSpan.FromMilliseconds(VerifyTimeout) })
                        res = client.GetStringAsync(VerifyUrl).Result;
                }

                if (!string.IsNullOrEmpty(res))
                {
                    System.Text.RegularExpressions.Match namem = System.Text.RegularExpressions.Regex.Match(res, VerifyRegex, System.Text.RegularExpressions.RegexOptions.Singleline);
                    if (namem.Success)
                    {
                        return namem.Groups[1].Value;
                    }
                }

            }
            catch { }
            return null;
        }
 private async void UpdateCheck()
 {
     string getVersion = "nil";
     try
     {
         System.Net.Http.HttpClient hct = new System.Net.Http.HttpClient();
         getVersion = await hct.GetStringAsync("https://bitbucket.org/IceLitty/minecraftcommandhelperversioncheck/raw/master/version.ini");
     }
     catch (Exception) { error1 = true; }
     getversion = getVersion;
     string[] getVS = getVersion.Split('.');
     string[] nowVS = version.Split('.');
     try
     {
         int[] getV = { int.Parse(getVS[0]), int.Parse(getVS[1]), int.Parse(getVS[2]), int.Parse(getVS[3]) };
         int[] nowV = { int.Parse(nowVS[0]), int.Parse(nowVS[1]), int.Parse(nowVS[2]), int.Parse(nowVS[3]) };
         if (nowV[0] < getV[0]) { isUpdate = true; }
         else if (nowV[0] == getV[0])
         {
             if (nowV[1] < getV[1]) { isUpdate = true; }
             else if (nowV[1] == getV[1])
             {
                 if (nowV[2] < getV[2]) { isUpdate = true; }
                 else if (nowV[2] == getV[2])
                 {
                     if (nowV[3] < getV[3]) { isUpdate = true; } else if (nowV[3] > getV[3]) { preview = true; }
                 }
                 else { preview = true; }
             }
             else { preview = true; }
         }
         else { preview = true; }
     } catch (Exception) { isUpdate = false; error2 = true; }
     string[] passVS = passversion.Split('.');
     if (getVS[0] == passVS[0] && getVS[1] == passVS[1] && getVS[2] == passVS[2] && getVS[3] == passVS[3])
     {
         isNeedUpdate = false;
     }
     else if (isUpdate)
     {
         isNeedUpdate = true;
     }
 }
        private static void DownloadDataAsync(string method, string baseUrl, string data, string contentType,
                                              string authHeader, Action<FlickrResult<string>> callback)
        {
            #if NETFX_CORE
            var client = new System.Net.Http.HttpClient();
            if (!String.IsNullOrEmpty(contentType)) client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", contentType);
            if (!String.IsNullOrEmpty(authHeader)) client.DefaultRequestHeaders.Add("Authorization", authHeader);

            if (method == "POST")
            {
                var content = client.PostAsync(baseUrl, new System.Net.Http.StringContent(data, System.Text.Encoding.UTF8, contentType)).Result.Content;
                var stringContent = content as System.Net.Http.StringContent;
                var result = new FlickrResult<string> {Result = content.ReadAsStringAsync().Result};
                callback(result);
            }
            else
            {
                var content = client.GetStringAsync(baseUrl).Result;
                var result = new FlickrResult<string> {Result = content};
                callback(result);
            }
            #else
            var client = new WebClient();
            if (!String.IsNullOrEmpty(contentType)) client.Headers["Content-Type"] = contentType;
            if (!String.IsNullOrEmpty(authHeader)) client.Headers["Authorization"] = authHeader;

             if (method == "POST")
            {
                client.UploadStringCompleted += delegate(object sender, UploadStringCompletedEventArgs e)
                                                    {
                                                        var result = new FlickrResult<string>();
                                                        if (e.Error != null)
                                                        {
                                                            result.Error = e.Error;
                                                            callback(result);
                                                            return;
                                                        }

                                                        result.Result = e.Result;
                                                        callback(result);
                                                        return;
                                                    };

                client.UploadStringAsync(new Uri(baseUrl), data);
            }
            else
            {
                client.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e)
                                                      {
                                                          var result = new FlickrResult<string>();
                                                          if (e.Error != null)
                                                          {
                                                              result.Error = e.Error;
                                                              callback(result);
                                                              return;
                                                          }

                                                          result.Result = e.Result;
                                                          callback(result);
                                                          return;
                                                      };

                client.DownloadStringAsync(new Uri(baseUrl));
            }
            #endif
        }
 public async Task<ActionResult> AsyncAwaitGood()
 {
     var client = new System.Net.Http.HttpClient();
     string result = await client.GetStringAsync("http://api.duckduckgo.com/?q=DuckDuckGo&format=json&pretty=1");
     return Content(result);
 }
 public async System.Threading.Tasks.Task<OwnCarousel> GetPreviewads(string id)
 {
     using (var http = new System.Net.Http.HttpClient())
     {
         var result = await http.GetStringAsync($"{ _appConfig.ManagementPortalUrl }/api/CourseCatalog/{ id }/ads");
         var courseCatalog = JsonConvert.DeserializeObject<OwnCarousel>(result);
         return courseCatalog;
     }
 }
        public async System.Threading.Tasks.Task<LessonContentRespond> GetLessonPreview(string id)
        {
            using (var http = new System.Net.Http.HttpClient())
            {
                var result = await http.GetStringAsync($"{ _appConfig.ManagementPortalUrl }/api/lessonpreview/{ id }/lesson");
                var lessonCatalog = Newtonsoft.Json.JsonConvert.DeserializeObject<LessonContentRespond>(result);

                lessonCatalog.StudentItems = lessonCatalog.StudentItems.OrderBy(it => it.Order);
                lessonCatalog.TeacherItems = lessonCatalog.TeacherItems.OrderBy(it => it.Order);
                lessonCatalog.PostAssessments = lessonCatalog.PostAssessments.OrderBy(it => it.Order);
                lessonCatalog.PreAssessments = lessonCatalog.PreAssessments.OrderBy(it => it.Order);
                return lessonCatalog;
            }
        }