//2
        private async Task <WebSiteModel> DownloadWebsiteAsync(string url)
        {
            WebClient    webClient    = new WebClient();
            WebSiteModel webSiteModel = new WebSiteModel()
            {
                Url  = url,
                Data = await webClient?.DownloadStringTaskAsync(url)
            };

            return(webSiteModel);
        }
Beispiel #2
0
        private async void GetFiles(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(urlTextBox.Text))
            {
                MessageBox.Show("Введите URL");
                return;
            }
            using (WebClient client = new WebClient())
            {
                try
                {
                    string html = await client.DownloadStringTaskAsync(new Uri(urlTextBox.Text));

                    HtmlParser parser   = new HtmlParser();
                    var        document = await parser.ParseDocumentAsync(html);

                    var filesList = document.QuerySelectorAll("*");
                    foreach (var file in filesList)
                    {
                        foreach (var attribute in file.Attributes)
                        {
                            if (attribute.Name == "href")
                            {
                                if (attribute.Value.Contains(".exe") || attribute.Value.Contains(".rar") || attribute.Value.Contains(".png") || attribute.Value.Contains(".jpg") || attribute.Value.Contains(".gif"))
                                {
                                    filesListBox.Items.Add(attribute.Value);
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    logTextBox.Text += "\nНе удалось подключиться к " + urlTextBox.Text;
                }
            }
        }
        public static async Task <List <Game> > Reload()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            WebClient webClient = new WebClient();
            string    mainPage;

            try
            {
                mainPage = await webClient.DownloadStringTaskAsync(GamesList.BaseURL);
            }
            catch (Exception e)
            {
                ThcrapDll.log_print("Could not download games list: " + e.Message + "\n");
                return(null);
            }
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(mainPage);

            var domGamesTable = doc.DocumentNode.SelectSingleNode("//table[@class='progtable']");
            var domGamesList  = domGamesTable.SelectNodes("tr").Skip(1);

            var gamesList = new List <Game>();

            foreach (var domGame in domGamesList)
            {
                gamesList.Add(await GameDomToObject(webClient, domGame));
            }

            string gamesListJs = JsonSerializer.Serialize(gamesList, new JsonSerializerOptions {
                WriteIndented = true
            });

            File.WriteAllText("res\\games_list.js", gamesListJs);

            return(gamesList);
        }
Beispiel #4
0
        /// <summary>
        /// 支付宝手机回调校验方法
        /// </summary>
        /// <param name="config"></param>
        /// <param name="parameter"></param>
        /// <param name="sign"></param>
        /// <returns></returns>
        public static async Task <bool> VerifyMobileNotify(AlipayConfig config, Dictionary <string, string> parameter, string sign)
        {
            if (config.SignType == "00001")
            {
                parameter["notify_data"] = RSAFromPkcs8.DecryptData(parameter["notify_data"], config.PublicKey, config.InputCharset);
            }
            string responseTxt = "true";

            try
            {
                //XML解析notify_data数据,获取notify_id
                string      notifyId = "";
                XmlDocument xmlDoc   = new XmlDocument();
                xmlDoc.LoadXml(parameter["notify_data"]);

                notifyId = xmlDoc.SelectSingleNode("/notify/notify_id")?.InnerText;

                if (notifyId != "")
                {
                    string veryfyUrl = config.VerifyUrl + "partner=" + config.Partner + "&notify_id=" + notifyId;
                    using (WebClient client = new WebClient())
                    {
                        responseTxt = await client.DownloadStringTaskAsync(veryfyUrl);
                    }
                }
            }
            catch (Exception e)
            {
                responseTxt = e.ToString();
            }

            //获取返回时的签名验证结果
            bool isSign = GetSignVeryfy(config, parameter, sign, false);


            return(responseTxt == "true" && isSign);
        }
Beispiel #5
0
        internal static async Task <T> GetAsync <T>(string url, bool withoutMetadata = true)
        {
            var tryCount = 0;
            var result   = default(T);

            while (result == null && tryCount < MaxRetries)
            {
                try
                {
                    using (var webClient = new WebClient())
                    {
                        webClient.Headers.Add("user-agent", WebHelper.UserAgent);
                        result = JsonConvert.DeserializeObject <T>(await webClient.DownloadStringTaskAsync(new Uri(url)));
                    }
                }
                catch (WebException ex)
                {
                    var response = ex.Response as HttpWebResponse;
                    if (response?.StatusCode == HttpStatusCode.NotFound)
                    {
                        Trace.WriteLine($"GetAsync: 404 Response For url [{ url }]", "Warning");
                        return(result);
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine($"GetAsync: [{ ex.ToString() }]", "Warning");
                    Thread.Sleep(100);
                }
                finally
                {
                    tryCount++;
                }
            }

            return(result);
        }
Beispiel #6
0
        /// <summary>
        /// 获取accessToken 异步方法
        /// </summary>
        /// <param name="wc"></param>
        /// <param name="appID"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public string GetWeChatAccessToken(WebClient wc, string appID, string appSecret)
        {
            try
            {
                JObject jObj         = null;
                var     access_token = "";
                var     timeOut      = 0;
                var     response     = wc.DownloadStringTaskAsync($"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appID}&secret={appSecret}");

                jObj = JsonConvert.DeserializeObject <JObject>(response.Result);

                JToken at;
                if (jObj.TryGetValue("access_token", out at))
                {
                    access_token = at.ToString();
                }
                else
                {
                    access_token = null;
                }
                JToken ei;
                if (jObj.TryGetValue("expires_in", out ei))
                {
                    timeOut = Convert.ToInt32(ei.ToString());
                }
                else
                {
                    timeOut = 0;
                }
                return(access_token);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Beispiel #7
0
            private async Task LoadNotification()
            {
                await Task.Delay(100);

                string url = "";

                try
                {
                    if (ETC.locale.Language == "ko")
                    {
                        url = Path.Combine(ETC.server, "Android_Notification.txt");
                    }
                    else
                    {
                        url = Path.Combine(ETC.server, "Android_Notification_en.txt");
                    }

                    if (ETC.isServerDown)
                    {
                        notificationView.Text = "& Server is Maintenance &";
                    }
                    else
                    {
                        using (var wc = new WebClient())
                        {
                            notificationView.Text = await wc.DownloadStringTaskAsync(url);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ETC.LogError(ex, Activity);

                    notificationView.Text = "& Notification Load Error &";
                }
            }
Beispiel #8
0
        private async void checkIR(Uri uri)
        {
            string str = "";

            while (!this._stop)
            {
                try
                {
                    str = await client.DownloadStringTaskAsync(uri);

                    if (!string.IsNullOrEmpty(str) && str != "{ }")
                    {
                        this.bindData(str);
                    }

                    await Task.Delay(3000);
                }
                catch (Exception ex)
                {
                    this.AddLog(ex.Message);

                    this._stop = true;

                    break;
                }
            }

            this.Dispatcher.Invoke(new Action(() => {
                if (this.cache != null)
                {
                    this.cache.Clear();
                }
            }));

            this.AddLog("Stop.");
        }
        async Task <string> fnDownloadString(string strUri)
        {
            WebClient webclient     = new WebClient();
            string    strResultData = "";

            try
            {
                strResultData = await webclient.DownloadStringTaskAsync(new Uri(strUri));
            }
            catch (Exception ex)
            {
                strResultData = "Exception";
                RunOnUiThread(() =>
                {
                    Toast.MakeText(this, "Unable to connect to server!!!", ToastLength.Short).Show();
                });
            }
            finally
            {
                webclient.Dispose();
                webclient = null;
            }
            return(strResultData);
        }
        private async void LoadNearbyPOIs(Position center)
        {
            var pins = new List <GeoPoint>();

            var queryUrl = string.Format(poiSearchUrlTemplate, AzureMapsSubscriptionKey, "hospital", center.Latitude, center.Longitude, poiSearchRadiusMeters);

            var wc       = new WebClient();
            var response = await wc.DownloadStringTaskAsync(new Uri(queryUrl));

            var d = JObject.Parse(response);

            var results = d["results"];

            if (results != null)
            {
                foreach (var r in results)
                {
                    var props = r["address"].ToObject <Dictionary <string, object> >();

                    if (r["poi"] != null)
                    {
                        props.Add("name", r["poi"]["name"].Value <string>());
                    }

                    pins.Add(new GeoPoint(new Position(r["position"]["lon"].Value <double>(), r["position"]["lat"].Value <double>()))
                    {
                        Properties = props
                    });
                }

                if (pins.Count > 0)
                {
                    (hospitalLayer.Source as GeoJsonSource).AddRange(pins);
                }
            }
        }
        public static async Task <Response <DateTime> > GetNowFromServerAsync(WebProxy proxy = null)
        {
            WebClient client = new WebClient();

            if (proxy != null)
            {
                client.Proxy = proxy;
            }

            try
            {
                var response = await client.DownloadStringTaskAsync("https://nist.time.gov/actualtime.cgi?lzbc=siqm9b");

                string time         = Regex.Match(response, @"(?<=\btime="")[^""]*").Value;
                double milliseconds = Convert.ToInt64(time) / 1000.0;
                var    result       = new DateTime(1970, 1, 1).AddMilliseconds(milliseconds).ToLocalTime();

                return(ResponseFactory.Create(result));
            }
            catch (Exception ex)
            {
                return(ResponseFactory.CreateError <DateTime>(ex.GetMessagePlus()));
            }
        }
Beispiel #12
0
        public static async Task CallApi(int number, bool runAsyncronously)
        {
            var stopWatch = new Stopwatch();

            stopWatch.Start();
            string result;

            try
            {
                using (var client = new WebClient())
                {
                    var url = runAsyncronously ? "http://localhost:60383/api/SearchBingAsync" : "http://localhost:60383/api/SearchBingSync";
                    await client.DownloadStringTaskAsync(url);

                    result = "Success!";
                }
            }
            catch (Exception)
            {
                result = "Failure!";
            }
            stopWatch.Stop();
            Console.WriteLine($"{number} - {result} - {stopWatch.ElapsedMilliseconds}ms");
        }
Beispiel #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ActionUpdater"/> class
        /// </summary>
        /// <param name="fullRawAssemblyInfoLink">The link to the assemblyinfo.cs file that can be found in your github. This has to be a raw link</param>
        /// <param name="localVersion">The local version of the assembly to compare</param>
        /// <param name="assemblyName">The name of the <see cref="Assembly"/></param>
        public ActionUpdater(string fullRawAssemblyInfoLink, Version localVersion, string assemblyName) : base(fullRawAssemblyInfoLink)
        {
            // Don't try to download or invoke anything if the developer couldn't even provide a proper link...
            if (!IsLinkValid)
            {
                return;
            }


            new Action(
                async delegate
            {
                using (var client = new WebClient())
                {
                    var match = AssemblyVersionRegex.Match(await client.DownloadStringTaskAsync(Link));

                    RaiseEvent(
                        new CheckPerformedEventArgs(
                            match.Success ? new Version(match.Groups[1].Value) : null,
                            localVersion,
                            assemblyName));
                }
            }).Invoke();
        }
Beispiel #14
0
        /// <summary>
        /// Downloads a file from the given URL, returns as string or writes it to the given destination
        /// </summary>
        /// <param name="url">The URL to download from</param>
        /// <param name="outFileName">File to output contents to</param>
        /// <returns>content or null</returns>
        private static async Task <string> download(string url, string outFileName = null)
        {
            using (WebClient client = new WebClient())
            {
                client.Headers.Add("User-Agent", "ASB");

                Debug.WriteLine("URL: " + url);
                Debug.WriteLine("Out File: " + outFileName);

                if (string.IsNullOrEmpty(outFileName))
                {
                    return(await client.DownloadStringTaskAsync(url));
                }

                await client.DownloadFileTaskAsync(url, outFileName);

                if (!File.Exists(outFileName))
                {
                    throw new FileNotFoundException($"Downloading file from {url} failed", outFileName);
                }

                return(null);
            }
        }
Beispiel #15
0
        public async Task <string> GetRemoteBuild()
        {
            try
            {
                WebClient webClient = new WebClient();
                string    remoteUrl = "https://launchermeta.mojang.com/mc/game/version_manifest.json";
                string    html      = await webClient.DownloadStringTaskAsync(remoteUrl);

                Regex regex   = new Regex("\"latest\":.{\"release\":.\"(.*?)\"");
                var   matches = regex.Matches(html);

                if (matches.Count == 1 && matches[0].Groups.Count == 2)
                {
                    return(matches[0].Groups[1].Value);
                }
            }
            catch
            {
                //ignore
            }

            Error = $"Fail to get remote build";
            return("");
        }
        private async Task <string> GetPageStringContentAsync(string partUri, bool ignoreNotFound = false)
        {
            var uri = new Uri(string.Concat(_configuration.BaseUri, partUri));

            string data    = null;
            int    attemps = 0;

            while (attemps < _configuration.PageAttemps)
            {
                using (var webClient = new WebClient())
                {
                    try
                    {
                        data = await webClient
                               .DownloadStringTaskAsync(uri)
                               .ConfigureAwait(false);

                        attemps = _configuration.PageAttemps;
                    }
                    catch (Exception ex)
                    {
                        if (ignoreNotFound && ex.IsWebNotFound())
                        {
                            return(data);
                        }
                        attemps++;
                        if (attemps == _configuration.PageAttemps)
                        {
                            throw;
                        }
                    }
                }
            }

            return(data);
        }
Beispiel #17
0
        public async Task <string> GetRemoteBuild()
        {
            try
            {
                WebClient webClient = new WebClient();
                string    remoteUrl = "https://jenkins.pmmp.io/job/PocketMine-MP/lastStableBuild/artifact/build_info.json";
                string    html      = await webClient.DownloadStringTaskAsync(remoteUrl);

                Regex regex   = new Regex("\"build_number\":\\D{0,}(.*?),");
                var   matches = regex.Matches(html);

                if (matches.Count == 1 && matches[0].Groups.Count == 2)
                {
                    return(matches[0].Groups[1].Value);
                }
            }
            catch
            {
                //ignore
            }

            Error = $"Fail to get remote build";
            return("");
        }
        private static async Task LoadProjectInfoFromApi(TeamCityProject project, WebClient webClient)
        {
            try
            {
                var projectDetailsUrl = new Uri(project.RootUrl + project.Href);
                _log.Debug("Retrieving project info for " + project.Name + " at " + projectDetailsUrl);
                var projectDetailsStr = await webClient.DownloadStringTaskAsync(projectDetailsUrl);

                XDocument projectDoc = XDocument.Parse(projectDetailsStr);
                if (projectDoc.Root == null)
                {
                    throw new Exception("Could not get project build definitions");
                }

                var parentProjectElement = projectDoc.Root.Element("parentProject");
                if (parentProjectElement != null)
                {
                    project.ParentProjectId = parentProjectElement.Attribute("id").Value;
                }

                XElement buildTypes = projectDoc.Root.Element("buildTypes");
                if (buildTypes == null)
                {
                    throw new ArgumentException(string.Format("buildTypes was null for {0}, this shouldn't happen", project.Name));
                }
                project.BuildDefinitions = buildTypes
                                           .Elements("buildType")
                                           .Select(buildTypeXml => new TeamCityBuildDefinition(project.RootUrl, buildTypeXml))
                                           .ToList();
            }
            catch (Exception ex)
            {
                _log.Error(string.Format("Error parsing project info for project {0} ({1})", project.Name, project.Id), ex);
                throw;
            }
        }
Beispiel #19
0
        //Function to get the stock current stock price and details
        public static async Task <string> GetStockPrice(string stockName)
        {
            //External call to find the stock value
            var url = "http://finance.google.com/finance/info?client=ig&q=NASDAQ:" + stockName;

            string stockOnlyPrice;

            //Get the stock Price
            using (WebClient client = new WebClient())
            {
                try
                {
                    var stockValue = await client.DownloadStringTaskAsync(url);

                    stockOnlyPrice = GetOnlyPrice(stockValue, "NASDAQ", "l_fix");
                }
                catch (Exception)
                {
                    // ignored
                    stockOnlyPrice = string.Empty;
                }
            };
            return(stockOnlyPrice);
        }
Beispiel #20
0
        public static async Task RequestHeaders_SpecialHeaders_RequestSucceeds()
        {
            var wc = new WebClient();

            wc.Headers["Accept"]      = "text/html";
            wc.Headers["Connection"]  = "close";
            wc.Headers["ContentType"] = "text/html; charset=utf-8";
            wc.Headers["Expect"]      = "100-continue";
            wc.Headers["Referer"]     = "http://localhost";
            wc.Headers["User-Agent"]  = ".NET";
            wc.Headers["Host"]        = "http://localhost";

            await LoopbackServer.CreateServerAsync(async (server, url) =>
            {
                Task <string> download = wc.DownloadStringTaskAsync(url.ToString());
                Assert.Null(wc.ResponseHeaders);
                await LoopbackServer.ReadRequestAndSendResponseAsync(server,
                                                                     "HTTP/1.1 200 OK\r\n" +
                                                                     $"Date: {DateTimeOffset.UtcNow:R}\r\n" +
                                                                     $"Content-Length: 0\r\n" +
                                                                     "\r\n");
                await download;
            });
        }
Beispiel #21
0
        private static async Task <string> GetStockTickerName(string strCompanyName)
        {
            string strRet = string.Empty;
            string url    = $"http://d.yimg.com/autoc.finance.yahoo.com/autoc?query={strCompanyName}&region=1&lang=en&callback=YAHOO.Finance.SymbolSuggest.ssCallback";
            string sJson  = string.Empty;

            using (WebClient client = new WebClient())
            {
                sJson = await client.DownloadStringTaskAsync(url).ConfigureAwait(false);
            }

            sJson = StripJsonString(sJson);
            YhooCompanyLookup lookup = null;

            try
            {
                lookup = JsonConvert.DeserializeObject <YhooCompanyLookup>(sJson);
            }
            catch (Exception e)
            {
            }

            if (null != lookup)
            {
                foreach (lResult r in lookup.ResultSet.Result)
                {
                    if (r.exch == "NAS")
                    {
                        strRet = r.symbol;
                        break;
                    }
                }
            }

            return(strRet);
        }
Beispiel #22
0
        /// <summary>
        /// Check for update
        /// </summary>
        /// <returns></returns>
        public async void CheckForUpdate()
        {
            var updateInfoString = string.Empty;

            using (WebClient wc = new WebClient())
            {
                wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.BypassCache);
                try
                {
                    updateInfoString = await wc.DownloadStringTaskAsync(new Uri(updateInfoUrl));

                    var currentVersion = Assembly.GetEntryAssembly().GetName().Version;

                    updateInfo = TryToParseUpdateInfo(updateInfoString);

                    if (updateInfo?.Version?.CompareTo(currentVersion) > 0)
                    {
                        if (UpdateConfirmation() == MessageResult.Yes)
                        {
                            Update();
                        }
                    }
                    else if (!IsStartUp)
                    {
                        this.messageBoxService.ShowMessageBox("You're already running the latest version", "Update", MessageButton.OK, MessageImage.Information);
                    }
                }
                catch
                {
                    if (IsStartUp == false)
                    {
                        this.messageBoxService.ShowMessageBox("Fail to get update infomation. Please check your internet connection!");
                    }
                }
            }
        }
Beispiel #23
0
        public async Task InstallFiveM(string path)
        {
            Console.WriteLine(" Searching for latest FiveM windows version...");

            using (var client = new WebClient())
            {
                var result = await client.DownloadStringTaskAsync(
                    "https://runtime.fivem.net/artifacts/fivem/build_server_windows/master/");

                var regex    = new Regex("href=\"(\\d{3})-([^\"]*)/\"", RegexOptions.IgnoreCase);
                var versions = new List <Tuple <string, string> >();

                for (var match = regex.Match(result); match.Success; match = match.NextMatch())
                {
                    versions.Add(new Tuple <string, string>(match.Groups[1].Value, match.Groups[2].Value));
                }

                var latest = versions.Max();

                Console.WriteLine($" Found latest build: {latest.Item1}, downloading!");

                var downloaded = await client.DownloadDataTaskAsync(
                    $"https://runtime.fivem.net/artifacts/fivem/build_server_windows/master/{latest.Item1}-{latest.Item2}/server.zip");

                Console.WriteLine(" Download complete, installing the files.");
                Directory.CreateDirectory(path);

                using (var stream = new MemoryStream(downloaded))
                    using (var zip = ZipFile.Read(stream))
                    {
                        zip.ExtractAll(path, ExtractExistingFileAction.OverwriteSilently);
                    }

                Console.WriteLine(" Installed successfully!");
            }
        }
 public async Task <Exception> TryReachProxy()
 {
     using (var client = new WebClient())
     {
         client.Proxy = Program.GetProxy().GetWebProxy();
         string respString;
         try
         {
             respString = await client.DownloadStringTaskAsync("http://www.wiiuusbhelper.com/session");
         }
         catch (WebException e)
         {
             return(e);
         }
         if (Guid.TryParse(respString, out Guid guid))
         {
             if (Program.GetSessionGuid() == guid)
             {
                 return(null);
             }
         }
         return(new InvalidOperationException("Invalid response: " + Regex.Replace(string.Concat(respString.Take(40)), @"\s+", " ") + "..."));
     }
 }
        private async Task <IEnumerable <Label> > DownloadLabelsAsync()
        {
            Logger.Info("Downloading labels...");

            string jsonString;

            using (WebClient wc = new WebClient())
            {
                try
                {
                    jsonString = await wc.DownloadStringTaskAsync(LABELS_URI.ToString());
                }
                catch (Exception e)
                {
                    InvokeOnRequestError(new RequestErrorEventArgs(e));
                    Logger.Error("Failed to download labels string.", e);
                    return(null);
                }
            }

            JsonArray json;

            try
            {
                json = JsonArray.Parse(jsonString);
                IEnumerable <Label> labels = json.Select(x => LoadLablesFromJson(x.GetObject()));
                Logger.Info("Successfully downloaded " + labels.Count() + " labels.");
                return(labels);
            }
            catch (Exception e)
            {
                InvokeOnRequestError(new RequestErrorEventArgs(e));
                Logger.Error("Failed to parse downloaded labels.", e);
                return(null);
            }
        }
        public async Task <ListResult <Transaction> > GetTransactions(string accountNumber, int?index = null, int?length = null, DateTime?startDate = null, DateTime?endDate = null)
        {
            var sb = new StringBuilder();

            sb.Append($"https://{_hostName}/Bank/Api/v2/Transactions/{_userId}/{accountNumber}");

            if (index != null)
            {
                sb.Append($"?index={index}");
            }
            if (length != null)
            {
                sb.Append($"{QueryCharacter(sb.ToString())}length={length}");
            }
            if (startDate != null)
            {
                sb.Append($"{QueryCharacter(sb.ToString())}startDate={startDate.Value:yyyy-MM-dd}");
            }
            if (endDate != null)
            {
                sb.Append($"{QueryCharacter(sb.ToString())}endDate={endDate.Value:yyyy-MM-dd}");
            }

            var transactionsUrl = sb.ToString();
            var token           = await IdentityServer.GetToken(_userId, _clientId, _secret, _hostName);

            using (var wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.Authorization] = $"Bearer {token.access_token}";
                wc.Headers[HttpRequestHeader.Accept]        = "application/json";
                var result = await wc.DownloadStringTaskAsync(transactionsUrl);

                var list = JsonConvert.DeserializeObject <ListResult <Transaction> >(result);
                return(list);
            }
        }
Beispiel #27
0
        public static async Task <Version> CheckForUpdates(bool beta)
        {
            var betaString = beta ? "BETA" : "LIVE";

            Logger.WriteLine("Checking for " + betaString + " updates...", "Helper");

            var versionXmlUrl = beta
                                                    ? @"https://raw.githubusercontent.com/Epix37/HDT-Data/master/beta-version"
                                                    : @"https://raw.githubusercontent.com/Epix37/HDT-Data/master/live-version";

            var currentVersion = GetCurrentVersion();

            if (currentVersion != null)
            {
                try
                {
                    Logger.WriteLine("Current version: " + currentVersion, "Helper");
                    string xml;
                    using (var wc = new WebClient())
                        xml = await wc.DownloadStringTaskAsync(versionXmlUrl);

                    var newVersion = new Version(XmlManager <SerializableVersion> .LoadFromString(xml).ToString());
                    Logger.WriteLine("Latest " + betaString + " version: " + newVersion, "Helper");

                    if (newVersion > currentVersion)
                    {
                        return(newVersion);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show("Error checking for new " + betaString + " version.\n\n" + e.Message + "\n\n" + e.InnerException);
                }
            }
            return(null);
        }
 public async Task <ContainerStat> GetContainerStatByIdAsync(string containerId)
 {
     try
     {
         string json = string.Empty;
         using (var webClient = new WebClient())
         {
             json = await webClient.DownloadStringTaskAsync($"{_apiLocation}containers/{containerId}/stats?stream=false");
         }
         if (!string.IsNullOrEmpty(json))
         {
             return(JsonConvert.DeserializeObject <ContainerStat>(json));
         }
         else
         {
             return(null);
         }
     }
     catch (Exception ex)
     {
         _logger.LogError(ex, "Failed to donwload stats for container with Id: {containerId}", containerId);
         return(null);
     }
 }
        public async Task <PackageInfoCollection> GetPackageInfoCollectionAsync(string ipAddress, string scope, long from)
        {
            var port    = 80;
            var callUrl = new Uri($"http://{ipAddress}:{port}/api/package/info?from={from}");

            try
            {
                using (var client = new WebClient())
                {
                    // Get packages from server

                    var json = await client.DownloadStringTaskAsync(callUrl);

                    var packageInfoCollection = JsonConvert.DeserializeObject <PackageInfoCollection>(json);

                    return(packageInfoCollection);
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"Failed to get packages from server {ipAddress} - Error : {ex.Message}");
                return(null);
            }
        }
Beispiel #30
0
        public async Task <NextLanInfo> GetNextLanInfo()
        {
            string htmlContents = "";

            using (var client = new WebClient())
            {
                htmlContents = await client.DownloadStringTaskAsync(new Uri("https://lan.lsucs.org.uk/"));
            }
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(htmlContents);

            var lanName      = doc.DocumentNode.SelectSingleNode("//*[@id=\"lan\"]").InnerText;
            var startDatestr = doc.DocumentNode.SelectSingleNode("//*[@id=\"title-container\"]/script").InnerText;

            startDatestr = startDatestr.Replace("var countdown_start = \"", "");
            startDatestr = startDatestr.Replace("\";", "");

            var startDate = DateTime.Parse(startDatestr);

            return(new NextLanInfo()
            {
                StartDate = startDate, Name = lanName
            });
        }
Beispiel #31
0
        public static void DownloadString_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();

            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadString((string)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadString((Uri)null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringAsync((Uri)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringAsync((Uri)null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringTaskAsync((string)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadStringTaskAsync((Uri)null); });
        }
Beispiel #32
0
 protected override Task<string> DownloadStringAsync(WebClient wc, string address) => wc.DownloadStringTaskAsync(address);
Beispiel #33
0
 public static async Task ConcurrentOperations_Throw()
 {
     await LoopbackServer.CreateServerAsync((server, url) =>
     {
         var wc = new WebClient();
         Task ignored = wc.DownloadDataTaskAsync(url); // won't complete
         Assert.Throws<NotSupportedException>(() => { wc.DownloadData(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadDataTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadString(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadStringTaskAsync(url); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.DownloadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadData(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadDataTaskAsync(url, new byte[42]); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadString(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadStringTaskAsync(url, "42"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFile(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadFileTaskAsync(url, "path"); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValues(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesAsync(url, new NameValueCollection()); });
         Assert.Throws<NotSupportedException>(() => { wc.UploadValuesTaskAsync(url, new NameValueCollection()); });
         return Task.CompletedTask;
     });
 }
Beispiel #34
0
        public static async Task RequestHeaders_SpecialHeaders_RequestSucceeds()
        {
            var wc = new WebClient();

            wc.Headers["Accept"] = "text/html";
            wc.Headers["Connection"] = "close";
            wc.Headers["ContentType"] = "text/html; charset=utf-8";
            wc.Headers["Expect"] = "100-continue";
            wc.Headers["Referer"] = "http://localhost";
            wc.Headers["User-Agent"] = ".NET";
            wc.Headers["Host"] = "http://localhost";

            await LoopbackServer.CreateServerAsync(async (server, url) =>
            {
                Task<string> download = wc.DownloadStringTaskAsync(url.ToString());
                Assert.Null(wc.ResponseHeaders);
                await LoopbackServer.ReadRequestAndSendResponseAsync(server,
                        "HTTP/1.1 200 OK\r\n" +
                        $"Date: {DateTimeOffset.UtcNow:R}\r\n" +
                        $"Content-Length: 0\r\n" +
                        "\r\n");
                await download;
            });
        }