System.Net.WebClient.DownloadString(string)

Here are the examples of the csharp api System.Net.WebClient.DownloadString(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

762 Examples 7

19 Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec

public static void LoadMismatchSearchMatrix(Options o)
        {
            if (o.Warning)
            {
                foreach (var x in (JsonConvert.DeserializeObject<JObject>(new WebClient().DownloadString(o.MitreMatrix))["objects"] as JArray)!
                    .Where(x => x["external_references"] != null && x["external_references"].Any(y => y["source_name"] != null && x["kill_chain_phases"] != null)))
                {
                    var techId = x["external_references"]
                        .First(x => x["source_name"].ToString() == "mitre-attack")["external_id"]
                        .ToString();
                    if (!mismatchSearchMatrix.ContainsKey(techId))
                        mismatchSearchMatrix.Add(techId,
                            x["kill_chain_phases"]!.Select(x => x["phase_name"].ToString()).ToList()
                        );
                    else
                    {
                        mismatchSearchMatrix[techId] = mismatchSearchMatrix[techId].Concat(x["kill_chain_phases"]!.Select(x => x["phase_name"].ToString())).ToList();
                    }
                }
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public static string GetShellcode(string url)
        {
            WebClient client = new WebClient();
            client.Proxy = WebRequest.GetSystemWebProxy();
            client.Proxy.Credentials = CredentialCache.DefaultCredentials;
            string shellcode = client.DownloadString(url);

            return shellcode;
        }

19 Source : MangaDexDownload.cs
with GNU General Public License v3.0
from 9vult

public void StartDownloading()
        {
            File.Create(Path.Combine(chapter.GetChapterRoot().Parent.FullName, "dl" + chapter.GetID())).Close();
            string jsonUrl = MangaDexHelper.MANGADEX_URL + "/api/chapter/" + chapter.GetID();
            string jsonString;

            using (var wc = new WebClient())
            {
                jsonString = wc.DownloadString(jsonUrl);
            }

            JObject jobj = JObject.Parse(jsonString);

            string server = (string)jobj["server"];
            string hash = (string)jobj["hash"];

            // string[] page_array = /* ((string) */ jobj["page_array"]. /* ).Split(',') */;
            List<string> page_array = new List<string>();
            IJEnumerable<JToken> jtokens = jobj["page_array"].Values();
            foreach(JToken t in jtokens)
            {
                page_array.Add((string)t);
            }

            foreach (string file in page_array)
            {
                if (server == "/data/")
                    server = MangaDexHelper.MANGADEX_URL + "/data/";

                string imgUrl = server + hash + "/" + file;

                FileInfo imgFile = new FileInfo(
                    Path.Combine(
                        chapter.GetChapterRoot().FullName, 
                        ConvertToNumericFileName(file)
                ));

                if (File.Exists(imgFile.FullName))
                    if (imgFile.Length <= 0)
                        File.Delete(imgFile.FullName);

                DownloadAsync(new Uri(imgUrl), imgFile.FullName);
            }
        }

19 Source : MangaDexHelper.cs
with GNU General Public License v3.0
from 9vult

public static string GetMangaJSON(string mangaUrl)
        {
            string apiUrl = MANGADEX_URL + "/api/manga/" + GetMangaID(mangaUrl);
            string json;
            using (var wc = new System.Net.WebClient())
            {
                json = wc.DownloadString(apiUrl);
            }
            return json;
        }

19 Source : MangaDexHelper.cs
with GNU General Public License v3.0
from 9vult

public static string GetChapterJSON(string chapterID)
        {
            string apiUrl = MANGADEX_URL + "/api/chapter/" + chapterID;
            string json;
            using (var wc = new System.Net.WebClient())
            {
                json = wc.DownloadString(apiUrl);
            }
            return json;
        }

19 Source : Updater.cs
with GNU General Public License v3.0
from 9vult

public static void Start()
        {
            WFClient.logger.Log("Checking for updates");

            string json;
            using (var wc = new System.Net.WebClient())
            {
                json = wc.DownloadString("https://raw.githubusercontent.com/ninevult/MikuReader/master/MikuReader-WF/updater/wfupdate.json");
            }
            UpdateInfo info = JsonConvert.DeserializeObject<UpdateInfo>(json);

            if (float.Parse(info.Update_major) > float.Parse(WFClient.CLIENT_MAJOR)
                || float.Parse(info.Update_minor) > float.Parse(WFClient.CLIENT_MINOR))
            {
                new FrmUpdate(info).ShowDialog();
            }

            // AutoUpdater.Start("https://raw.githubusercontent.com/ninevult/MikuReader/master/MikuReader-WF/updater/wfupdate.xml");
            // AutoUpdater.RunUpdateAsAdmin = true;
            // AutoUpdater.OpenDownloadPage = true;
        }

19 Source : Download.cs
with GNU General Public License v3.0
from 9vult

public bool StartDownloading()
        {
            Logger.Log("[DL] Starting Download for '" + manga.mangaDirectory.FullName + "\\" + chapterNumber + "'");
            string chapterDirectory = manga.mangaDirectory.FullName + "\\" + chapterNumber;
            Directory.CreateDirectory(chapterDirectory); // Create a directory for this chapter

            switch (type)
            {
                case DownloadType.MANGA:
                    string jsonUrl = "https://mangadex.org/api/chapter/" + chapterID;
                    string json;
                    using (var wc = new System.Net.WebClient())
                        json = wc.DownloadString(jsonUrl);

                    dynamic contents = JsonConvert.DeserializeObject(json);
                    string server = contents.server;
                    string hash = contents.hash;
                    foreach (string file in contents.page_array)
                    {
                        if (server == "/data/")
                        {
                            server = "https://mangadex.org/data/";
                        }
                        string imgUrl = server + hash + "/" + file;
                        string imgFile = chapterDirectory + "\\" + file;

                        if (File.Exists(imgFile))
                        {
                            long length = new FileInfo(imgFile).Length;
                            if (length <= 0)
                            {
                                File.Delete(imgFile);
                            }
                        }
                        try
                        {
                            DownloadAsync(new Uri(imgUrl), imgFile);
                        } catch (Exception ex)
                        {
                            Logger.Error("[DL] Failed to download '" + imgUrl + "' because '" + ex.Message + "'");
                        }
                    }
                    CheckStartNext();
                    return true;

                case DownloadType.HENTAI:
                    string imageUrl = string.Empty;
                    string extension;
                    int pageCount = 0;
                    imageUrl = NHGetImageUrl(url);
                    pageCount = NHGetPageCount(url);
                    extension = NHGetImageExtension(imageUrl);
                    string imgLoc = NHGetImageLocation(imageUrl);

                    for (int page = 1; page <= pageCount; page++)
                    {
                        dlCount++;
                        string curImgUrl = imgLoc + page + "." + extension;
                        string imgFile = chapterDirectory + "\\" + page + "." + extension;
                        if (File.Exists(imgFile))
                        {
                            long length = new FileInfo(imgFile).Length;
                            if (length <= 0)
                            {
                                File.Delete(imgFile);
                                DownloadAsync(new Uri(curImgUrl), imgFile);
                            }
                            else
                            {
                                if (page == pageCount) // last one
                                    CheckStartNext();
                            }
                        }
                        else
                            DownloadAsync(new Uri(curImgUrl), imgFile);
                    }
                    return true;
                default:
                    return false;
            }
        }

19 Source : FrmStartPage.cs
with GNU General Public License v3.0
from 9vult

public void AddManga(string api, string num, bool isUpdate)
        {
            string json;
            if (api != null)
            {
                using (var wc = new System.Net.WebClient())
                {
                    json = wc.DownloadString(api);
                }
            }
            else
            {
                json = File.ReadAllText(homeFolder + "\\" + num + "\\manga.json");
            }

            // Deserialize the JSON file
            dynamic contents = JsonConvert.DeserializeObject(json);
            string mangaName = contents.manga.replacedle;
            string mangaDirectory = homeFolder + "\\" + num;

            if (!Directory.Exists(mangaDirectory))
            {
                Logger.Log("Creating directory '" + mangaDirectory + "' and related files");
                Directory.CreateDirectory(mangaDirectory);
                File.WriteAllText(mangaDirectory + "\\manga.json", json); // Write the JSON to a file
                File.WriteAllText(mangaDirectory + "\\tracker", "1|1"); // Write initial tracking info to a file
            }
            File.WriteAllText(mangaDirectory + "\\downloading", ""); // Create "Downloading" file

            Manga m = new Manga(mangaName, new DirectoryInfo(mangaDirectory), "1", "1");

            if (!isUpdate)
            {
                DialogResult result = new FrmMangaSettings(m).ShowDialog();
                MessageBox.Show("Downloading data...\nYou may close the Browser as you desire.");
            }
            m.LoadSettings();
            downloadManager.AddMDToQueue(m, contents.chapter, isUpdate);
            RefreshContents();
        }

19 Source : GAnalytics.cs
with GNU General Public License v3.0
from AgentRev

public static int GetUniqueID()
        {
            string commentForCodeLurkers = "This is to find the public IPv4 address of the client to use it as unique ID for replacedytics";

            try
            {
                var client = new TimedWebClient();
                var ipAddress = client.DownloadString(ipService);
                ipAddress = Regex.Match(ipAddress, @"([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})").Groups[1].Value;

                return BitConverter.ToInt32(IPAddress.Parse(ipAddress).GetAddressBytes(), 0);
            }
            catch
            {
                Random rnd = new Random();
                return rnd.Next(int.MinValue, int.MaxValue);
            }
        }

19 Source : Updater.cs
with GNU General Public License v3.0
from ahmed605

private static string GetWebString(string url)
        {
            string result;
            try
            {
                var client = new System.Net.WebClient();
                client.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
                result = client.DownloadString(url);
            }
            catch (Exception ex)
            {
                string errorDetails = String.Empty;
                MessageBoxIcon iconsToShow = MessageBoxIcon.Information;

                if (ex.Message.Contains("could not be resolved"))
                {
                    errorDetails =
                        String.Format(
                            "The update check server could not be resolved.\nPlease check your internet connection and try again.");
                    iconsToShow = MessageBoxIcon.Error;
                }
                else if (ex.Message.Contains("404"))
                {
                    errorDetails = "The update check server is currently down. Please try again later.";
                    iconsToShow = MessageBoxIcon.Information;
                }
                MessageBox.Show(errorDetails, "Update check server down", MessageBoxButtons.OK, iconsToShow);
                return null;
            }

            return result;
        }

19 Source : SoftwareUpdater.cs
with MIT License
from AlbertMN

public bool Check(bool debug = false) {
            if (MainProgram.isCheckingForUpdate)
                return false;

            MainProgram.isCheckingForUpdate = true;
            MainProgram.DoDebug("Checking for updates...");

            string latestReleaseJson = null;
            string latestBetaJson = null;

            //Check and get latest
            if (Properties.Settings.Default.LastOpenedDate.Date != DateTime.UtcNow.Date) {
                releaseJsonUrl += "&daily_check";
                betaJsonUrl += "&daily_check";

                Properties.Settings.Default.LastOpenedDate = DateTime.UtcNow;
                Properties.Settings.Default.Save();
            }

            try {
                if (RemoteFileExists(releaseJsonUrl)) {
                    using (WebClient client = new WebClient()) {
                        latestReleaseJson = client.DownloadString(releaseJsonUrl);
                    }
                    if (latestReleaseJson == string.Empty) {
                        latestReleaseJson = null;
                    }
                }

                //Check and get beta
                if (Properties.Settings.Default.BetaProgram && RemoteFileExists(betaJsonUrl)) {
                    using (WebClient client = new WebClient()) {
                        latestBetaJson = client.DownloadString(betaJsonUrl);
                    }
                    if (latestBetaJson == string.Empty)
                        latestBetaJson = null;
                }

                if (latestReleaseJson != null || latestBetaJson != null) {
                    Version newVersion = null,
                        latestRelease,
                        latestBeta;

                    if (latestReleaseJson != null && latestBetaJson != null) {
                        //Beta program enabled; check both release and beta for newest update
                        latestRelease = JsonConvert.DeserializeObject<Version>(latestReleaseJson);
                        latestBeta = JsonConvert.DeserializeObject<Version>(latestBetaJson);

                        if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(MainProgram.releaseDate) ||
                            DateTime.Parse(latestBeta.datetime) > DateTime.Parse(MainProgram.releaseDate)) {
                            //Both latest release and beta is ahead of this current build
                            if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(latestBeta.datetime)) {
                                //Release is newest
                                newVersion = latestRelease;
                            } else {
                                //Beta is newest
                                newVersion = latestBeta;
                            }
                        } else {
                            //None of them are newer. Nothing new
                            MainProgram.DoDebug("Software up to date (beta program enabled)");

                            MainProgram.isCheckingForUpdate = false;
                            return false;
                        }
                    } else if (latestReleaseJson != null && latestBetaJson == null) {
                        //Only check latest
                        latestRelease = JsonConvert.DeserializeObject<Version>(latestReleaseJson);

                        if (DateTime.Parse(latestRelease.datetime) > DateTime.Parse(MainProgram.releaseDate) && latestRelease.version != MainProgram.softwareVersion) {
                            //Newer build
                            newVersion = latestRelease;
                        } else {
                            //Not new, move on
                            MainProgram.DoDebug("Software up to date");
                            MainProgram.isCheckingForUpdate = false;
                            return false;
                        }
                    } else if (latestReleaseJson == null && latestBetaJson != null) {
                        //Couldn't reach "latest" update, but beta-updates are enabled
                        latestBeta = JsonConvert.DeserializeObject<Version>(latestBetaJson);

                        if (latestBeta != null) {
                            if (DateTime.Parse(latestBeta.datetime) > DateTime.Parse(MainProgram.releaseDate)) {
                                //Newer build
                                newVersion = latestBeta;
                            } else {
                                //Not new, move on
                                MainProgram.DoDebug("Software up to date (beta program enabled)");
                                MainProgram.isCheckingForUpdate = false;
                                return false;
                            }
                        }
                    } else {
                        MainProgram.DoDebug("Both release and beta is NULL, no new updates, or no contact to the server.");
                    }

                    if (newVersion != null && newVersion.version != MainProgram.softwareVersion) {
                        //New version available
                        MainProgram.DoDebug("New software version found (" + newVersion.version + ") [" + newVersion.type + "], current; " + MainProgram.softwareVersion);
                        DialogResult dialogResult = MessageBox.Show(Translator.__("new_version_found", "check_for_update").Replace("{version_num}", newVersion.version).Replace("{version_type}", newVersion.type), Translator.__("new_version_found_replacedle", "check_for_update") + " | " + MainProgram.messageBoxreplacedle, MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
                        if (dialogResult == DialogResult.Yes) {
                            MainProgram.DoDebug("User chose \"yes\" to install update");
                            DownloadFile(newVersion.installpath + "&upgrade=true");
                        } else if (dialogResult == DialogResult.No) {
                            MainProgram.DoDebug("User did not want to install update");
                        }
                        MainProgram.isCheckingForUpdate = false;
                        return true;
                    } else {
                        MainProgram.DoDebug("Software up to date");
                        if (debug)
                            MessageBox.Show(Translator.__("no_new_update", "check_for_update"), Translator.__("check_for_update_replacedle", "check_for_update") + " | " + MainProgram.messageBoxreplacedle, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
                    }
                } else {
                    MainProgram.DoDebug("Could not reach the webserver (both 'release' and 'beta' json files couldn't be reached)");
                    if (debug)
                        MessageBox.Show(Translator.__("webservers_offline", "check_for_update"), Translator.__("check_for_update_replacedle", "check_for_update") + " | " + MainProgram.messageBoxreplacedle, MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
                }
            } catch (Exception e) {
                MainProgram.DoDebug("Failed to check for update (exception); " + e.Message + "; " + e.StackTrace);
            }

            MainProgram.isCheckingForUpdate = false;
            return false;
        }

19 Source : UpdatesChecker.cs
with MIT License
from AlexMog

public static bool CheckForUpdate(out string url)
        {
            var client = new WebClient();
            client.Headers.Add("User-Agent: Longship Valheim Mod");
            try
            {
                var lastRelease = JsonUtility.FromJson<LastRelease>(client.DownloadString(RELEASES_URL));
                if (!lastRelease.draft && !lastRelease.prerelease)
                {
                    url = lastRelease.url;
                    return lastRelease.tag_name != Longship.BuildTag;
                }
            }
            catch(Exception e)
            {
                Longship.Instance.Log.LogWarning("Can't check if updates are available.");
                Longship.Instance.Log.LogDebug(e);
            }

            url = null;
            return false;
        }

19 Source : Updater.xaml.cs
with MIT License
from Alkl58

private void ParseJeremyleeJSON()
        {
            try
            {
                string jsonWeb = new WebClient().DownloadString("https://jeremylee.sh/data/bin/packages.json");
                dynamic json = JsonConvert.DeserializeObject(jsonWeb);

                string aomencVersion = json.apps["aomenc.exe"].datetime;
                AomencUpdateVersion = aomencVersion.Replace("-", ".").Remove(aomencVersion.Length - 6);
                LabelUpdateAomencVersion.Content = AomencUpdateVersion;

                string rav1eVersion = json.apps["rav1e.exe"].datetime;
                Rav1eUpdateVersion = rav1eVersion.Replace("-", ".").Remove(rav1eVersion.Length - 6);
                LabelUpdateRav1eVersion.Content = Rav1eUpdateVersion;

                string svtav1Version = json.apps["SvtAv1EncApp.exe"].datetime;
                SVTAV1UpdateVersion = svtav1Version.Replace("-", ".").Remove(svtav1Version.Length - 6);
                LabelUpdateSVTAV1Version.Content = SVTAV1UpdateVersion;
            }
            catch { }
        }

19 Source : base.cs
with GNU General Public License v3.0
from alterNERDtive

private static void UpdateCheck()
        {
            Version latestVersion;
            try
            {
                latestVersion = new Version(new WebClient().DownloadString("https://raw.githubusercontent.com/alterNERDtive/VoiceAttack-profiles/release/VERSION"));
            }
            catch (Exception)
            {
                throw new Exception("Error fetching latest profiles version from Github.");
            }

            Log.Notice($"Local version: {VERSION}, latest release: {latestVersion}.");

            Commands.TriggerEvent("alterNERDtive-base.updateCheck",
                parameters: new dynamic[] { new string[] { VERSION.ToString(), latestVersion.ToString() }, new bool[] { VERSION.CompareTo(latestVersion) < 0 } });
        }

19 Source : frmMain.cs
with GNU General Public License v3.0
from amakvana

private void BtnCheck_Click(object sender, EventArgs e)
        {
            ToggleControls(false);

            // read in current version 
            // get latest version 
            // compare 
            if (!string.IsNullOrWhiteSpace(txtYuzuLocation.Text))
            {
                string yuzuLocation = txtYuzuLocation.Text;

                if (File.Exists(yuzuLocation + "\\version"))
                {
                    // get current version 
                    string currentVersion = "";
                    string latestVersion = "";
                    using (StreamReader sr = File.OpenText(yuzuLocation + "\\version"))
                    {
                        string s = "";
                        while ((s = sr.ReadLine()) != null)
                        {
                            currentVersion = s;
                        }
                    }

                    // get latest version from repo
                    using (var wc = new WebClient())
                    {
                        // fetch latest Yuzu release 
                        string repo = "https://github.com/yuzu-emu/yuzu-mainline/releases/latest";
                        string repoHtml = wc.DownloadString(repo);
                        Regex r = new Regex(@"(?:\/yuzu-emu\/yuzu-mainline\/releases\/download\/[^""]+)");
                        foreach (Match m in r.Matches(repoHtml))
                        {
                            string url = m.Value.Trim();
                            if (url.Contains(".zip") && !url.Contains("debugsymbols"))
                            {
                                latestVersion = url.Split('/')[5].Trim().Remove(0, 11);
                            }
                        }
                    }

                    // compare & tell user 
                    string message = (currentVersion == latestVersion) ? "You have the latest version of Yuzu!" : "Update available, please select Yuzu from the dropdown and click Update";
                    MessageBox.Show(message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Failed to get version, please select Yuzu from the dropdown and click Update", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Please select your Yuzu root folder", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            // enable relevant buttons 
            ToggleControls(true);
            if (cboOptions.SelectedIndex == 0 && DependenciesInstalled())
            {
                btnProcess.Enabled = false;
                btnProcess.Text = "Installed";
            }
        }

19 Source : frmMain.cs
with GNU General Public License v3.0
from amakvana

private async Task ProcessYuzu(string yuzuLocation)
        {
            ToggleControls(false);

            // create temp directory for downloads 
            string tempDir = yuzuLocation + "\\TempUpdate";
            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            // get latest yuzu version & download 
            using (var wc = new WebClient())
            {
                // fetch latest Yuzu release 
                string latestYuzu = "https://github.com";
                string repo = "https://github.com/yuzu-emu/yuzu-mainline/releases/latest";
                string repoHtml = wc.DownloadString(repo);
                string version = "";
                Regex r = new Regex(@"(?:\/yuzu-emu\/yuzu-mainline\/releases\/download\/[^""]+)");
                foreach (Match m in r.Matches(repoHtml))
                {
                    string url = m.Value.Trim();
                    if (url.Contains(".zip") && !url.Contains("debugsymbols"))
                    {
                        latestYuzu += url;
                        version = url.Split('/')[5].Trim().Remove(0, 11);
                    }
                }

                // download it 
                wc.DownloadFileCompleted += (s, e) =>
                {
                    // unpack 
                    SetProgressLabelStatus("Unpacking Yuzu ...");
                    ZipFile.ExtractToDirectory(tempDir + "\\yuzu.zip", yuzuLocation);

                    // update version number 
                    using (StreamWriter sw = File.CreateText(yuzuLocation + "\\version"))
                    {
                        sw.Write(version);
                    }

                    // cleanup 
                    DirectoryUtilities.Copy(yuzuLocation + "\\yuzu-windows-msvc", yuzuLocation, true);
                    Directory.Delete(yuzuLocation + "\\yuzu-windows-msvc", true);
                    Directory.Delete(tempDir, true);
                    Directory.EnumerateFiles(yuzuLocation, "*.xz").ToList().ForEach(item => File.Delete(item));
                    SetProgressLabelStatus("Done!");
                    ToggleControls(true);
                    pbarProgress.Value = 0;
                };
                wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
                SetProgressLabelStatus("Downloading Yuzu ...");
                await wc.DownloadFileTaskAsync(new Uri(latestYuzu), tempDir + "\\yuzu.zip");
            }
        }

19 Source : Form1.cs
with Apache License 2.0
from anadventureisu

private void statusTimer_Tick(object sender, EventArgs e)
        {
            //processRunner.StandardInput.Write('s');
            //processRunner.StandardInput.Flush();
            WebClient wc = new WebClient();
            try {
                string response = wc.DownloadString("http://localhost:7777");
                JsonParser.Parse(response, app);
                app.UpdateGlobalRates();

                //printStatus();
                appStateBindingSource.Clear();
                appStateBindingSource.Add(app);
                
                // TODO: figure out how to make GpuState fire update events.
                gpuStateBindingSource.Clear();
                foreach (int gpu in app.GpuStates.Keys)
                {
                    gpuStateBindingSource.Add(app.GetGpu(gpu));
                }
                

                int restartRate = int.Parse(hashRestart.Text);

                if (autoRestartCheck.Checked && (DateTime.Now - minerStarted > TimeSpan.FromMinutes(5)))
                {
                    foreach (int gpu in app.GpuStates.Keys)
                    {
                        GpuState gs = app.GetGpu(gpu);
                        if (gs.FiveMinHashAvg < restartRate)
                        {
                            consoleLog.AppendText(String.Format("{2}: RESTARTING MINER - rate {0:N0} < {1:N0}\n", gs.FiveMinHashAvg, restartRate, DateTime.Now));
                            statusTimer.Stop();
                            processRunner.Kill();
                            startMiner();
                            statusTimer.Start();
                            restartCount++;
                            restartLabel.Text = ""+restartCount;
                            break;
                        }
                        
                    }
                }
                
            }
            catch (Exception ee)
            {
                consoleLog.AppendText("ERROR: could not query web service: " + ee.Message + "\n");
            }
        }

19 Source : BuildDeployPortal.cs
with MIT License
from anderm

public static bool IsAppRunning(string appName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Preplacedword);
                string query = string.Format(kAPI_ProcessQuery, connectInfo.IP);
                string procListJSON = client.DownloadString(query);

                ProcessList procList = JsonUtility.FromJson<ProcessList>(procListJSON);
                for (int i = 0; i < procList.Processes.Length; ++i)
                {
                    string procName = procList.Processes[i].ImageName;
                    if (procName.Contains(appName))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

19 Source : BuildDeployPortal.cs
with MIT License
from anderm

public static AppInstallStatus GetInstallStatus(ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Preplacedword);
                string query = string.Format(kAPI_InstallStatusQuery, connectInfo.IP);
                string statusJSON = client.DownloadString(query);
                InstallStatus status = JsonUtility.FromJson<InstallStatus>(statusJSON);

                if (status == null)
                {
                    return AppInstallStatus.Installing;
                }
                else if (status.Success == false)
                {
                    Debug.LogError(status.Reason + "(" + status.CodeText + ")");
                    return AppInstallStatus.InstallFail;
                }
                return AppInstallStatus.InstallSuccess;
            }
        }

19 Source : BuildDeployPortal.cs
with MIT License
from anderm

public static AppDetails QueryAppDetails(string packageFamilyName, ConnectInfo connectInfo)
        {
            using (var client = new TimeoutWebClient())
            {
                client.Credentials = new NetworkCredential(connectInfo.User, connectInfo.Preplacedword);
                string query = string.Format(kAPI_PackagesQuery, connectInfo.IP);
                string appListJSON = client.DownloadString(query);

                AppList appList = JsonUtility.FromJson<AppList>(appListJSON);
                for (int i = 0; i < appList.InstalledPackages.Length; ++i)
                {
                    string thisAppName = appList.InstalledPackages[i].PackageFamilyName;
                    if (thisAppName.Equals(packageFamilyName, StringComparison.OrdinalIgnoreCase))
                    {
                        return appList.InstalledPackages[i];
                    }
                }
            }
            return null;
        }

19 Source : Update.cs
with MIT License
from ANF-Studios

public List<Release> GetReleases()
        {
            string response = String.Empty;
            List<Release> releases;
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    webClient.Headers.Add(HttpRequestHeader.UserAgent, "WinPath");
                    response = webClient.DownloadString(Update.releases);
                    #if DEBUG
                        Console.WriteLine("Response: " + response);
                    #endif
                }

                releases = JsonSerializer.Deserialize<List<Release>>(response);
                return releases;
                //Console.WriteLine(releases[(releases.Count - 1)].replacedets[4].DownloadUrl);
            }
            catch (WebException webException)
            {
                Console.WriteLine("Could not make web request!\n" + webException.Message);
                Environment.Exit(exitCode: 1);
            }
            return null;
        }

19 Source : ProductManager.cs
with GNU Lesser General Public License v3.0
from ApexGameTools

private static void DownloadLatest(ApexSettings settings, string manifestPath)
        {
            var client = new WebClient
            {
                BaseAddress = EnsureTrailingSlash(settings.updateCheckBaseUrl)
            };

            string serviceUrl = null;

            try
            {
                client.Headers.Add("Accept", "application/xml");
                var latestUpdate = XmlSingleValue(client.DownloadString("api/Service/GetLatestUpdateTime"));

                if (settings.lastUpdateCheck >= DateTime.Parse(latestUpdate, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.replacedumeUniversal | DateTimeStyles.AdjustToUniversal))
                {
                    settings.UpdateCompleted(null);
                    return;
                }

                client.Headers.Add("Accept", "application/xml");
                var productManifest = client.DownloadString("api/Products/GetProducts");
                using (var w = new StreamWriter(manifestPath))
                {
                    w.Write(productManifest);
                }

                client.Headers.Add("Accept", "application/xml");
                serviceUrl = XmlSingleValue(client.DownloadString("api/Service/GetServiceUrl"));
            }
            catch
            {
                return;
            }

            settings.UpdateCompleted(serviceUrl);
        }

19 Source : ProductManager.cs
with GNU Lesser General Public License v3.0
from ApexGameTools

internal static void ApplyPatches(ProductInfo p, ApexSettings settings)
        {
            var client = new WebClient
            {
                BaseAddress = EnsureTrailingSlash(settings.updateCheckBaseUrl)
            };

            client.Headers.Add("Accept", "application/xml");
            var request = string.Format("api/Products/GetAvailablePatches?productName={0}&version={1}", p.generalName, p.installedVersion);
            var patchList = client.DownloadString(request);

            var doc = XDoreplacedent.Parse(patchList);
            var ns = XNamespace.Get(doc.Root.Attribute("xmlns").Value);
            var patchFiles = from s in XDoreplacedent.Parse(patchList).Root.Elements(ns + "string")
                             select s.Value;

            foreach (var patchFile in patchFiles)
            {
                var patchPath = string.Concat(settings.dataFolder, "/", patchFile);
                var url = string.Concat("content/patches/", patchFile);
                client.DownloadFile(url, patchPath);

                replacedetDatabase.ImportPackage(patchPath, false);
            }
        }

19 Source : SettingsWindow.xaml.cs
with MIT License
from Apollo199999999

private void VisitGithub_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //get the github respository link from the pastebin link
                //github respository link is a pastebin link
                var url = "https://pastebin.com/raw/kjLK23F0";

                //init a webclient
                WebClient client = new WebClient();

                //download all text from the pastebin raw link
                string reply = client.DownloadString(url);

                //start the process
                Process.Start(reply);
            }
            catch
            {
                //show an error message
                System.Windows.MessageBox.Show("Unable to open the github respository. Check that you are connected " +
                    "to the internet, and try again.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

19 Source : PublicVariables.cs
with MIT License
from Apollo199999999

public static void CheckForUpdates(bool ShowInfoMessage)
        {
            //check if there is internet connection
            if (CheckForInternetConnection() == true)
            {
                //Check for updates
                var url = "https://pastebin.com/raw/m3m85kbH";
                WebClient client = new WebClient();
                string reply = client.DownloadString(url);

                if (reply != DynaWinCurrentVersion)
                {
                    //this is the output when an update is available. Modify it if you wish

                    //show the messagebox
                    var result = MessageBox.Show("An update is available for DynaWin, " +
                        "would you like to go to our website to download it?", "Update available", 
                        MessageBoxButton.YesNo, MessageBoxImage.Question);

                    if (result == MessageBoxResult.Yes)
                    {
                        //go to the github page
                        System.Diagnostics.Process.Start("https://github.com/Apollo199999999/DynaWin/releases");

                        //exit the application
                        Application.Current.Shutdown();
                    }
                }
                else if (reply == DynaWinCurrentVersion)
                {
                    //no updates available
                    //only show a messsage if the showinfomessage is true
                    if (ShowInfoMessage == true)
                    {
                        //show a messagebox
                        MessageBox.Show("No updates available for DynaWin.", "You're up to date!", 
                            MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }

            }
            else if (CheckForInternetConnection() == false)
            {
                //show an error message that there is no internet connection (only if showinfomessage is true)
                if (ShowInfoMessage == true)
                {
                    //show error message
                    MessageBox.Show("DynaWin cannot check for updates as there is no internet connection. " +
                    "Connect to the internet and try again", "No internet connection",
                            MessageBoxButton.OK, MessageBoxImage.Error);
                }

            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from approved

private static bool GetChampionBaseValues(string championName)
        {
            string lowerChampionName = championName.ToLower();
            JToken championBinToken = null;
            try
            {
                championBinToken = JToken.Parse(Client.DownloadString($"{ChampionStatsEndpoint}{lowerChampionName}/{lowerChampionName}.bin.json"));
            }
            catch
            {
                return false;
            }
            JToken championRootStats = championBinToken[$"Characters/{championName}/CharacterRecords/Root"];
            ChampionAttackSpeedRatio = championRootStats["attackSpeedRatio"].Value<double>(); ;

            JToken championBasicAttackInfoToken = championRootStats["basicAttack"];
            JToken championAttackDelayOffsetToken = championBasicAttackInfoToken["mAttackDelayCastOffsetPercent"];
            JToken championAttackDelayOffsetSpeedRatioToken = championBasicAttackInfoToken["mAttackDelayCastOffsetPercentAttackSpeedRatio"];

            if (championAttackDelayOffsetSpeedRatioToken?.Value<double?>() != null)
            {
                ChampionAttackDelayScaling = championAttackDelayOffsetSpeedRatioToken.Value<double>();
            }

            if (championAttackDelayOffsetToken?.Value<double?>() == null)
            {
                JToken attackTotalTimeToken = championBasicAttackInfoToken["mAttackTotalTime"];
                JToken attackCastTimeToken = championBasicAttackInfoToken["mAttackCastTime"];

                if (attackTotalTimeToken?.Value<double?>() == null && attackCastTimeToken?.Value<double?>() == null)
                {
                    string attackName = championBasicAttackInfoToken["mAttackName"].ToString();
                    string attackSpell = $"Characters/{attackName.Split(new[] { "BasicAttack" }, StringSplitOptions.RemoveEmptyEntries)[0]}/Spells/{attackName}";
                    ChampionAttackDelayPercent += championBinToken[attackSpell]["mSpell"]["delayCastOffsetPercent"].Value<double>();
                }
                else
                {
                    ChampionAttackTotalTime = attackTotalTimeToken.Value<double>();
                    ChampionAttackCastTime = attackCastTimeToken.Value<double>(); ;

                    ChampionAttackDelayPercent = ChampionAttackCastTime / ChampionAttackTotalTime;
                }
            }
            else
            {
                ChampionAttackDelayPercent += championAttackDelayOffsetToken.Value<double>(); ;
            }

            return true;
        }

19 Source : Program.cs
with GNU General Public License v3.0
from approved

private static void AttackSpeedCacheTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            if (HasProcess && !IsExiting && !IsIntializingValues && !IsUpdatingAttackValues)
            {
                IsUpdatingAttackValues = true;

                JToken activePlayerToken = null;
                try
                {
                    activePlayerToken = JToken.Parse(Client.DownloadString(ActivePlayerEndpoint));
                }
                catch
                {
                    IsUpdatingAttackValues = false;
                    return;
                }

                if (string.IsNullOrEmpty(ChampionName))
                {
                    ActivePlayerName = activePlayerToken?["summonerName"].ToString();
                    IsIntializingValues = true;
                    JToken playerListToken = JToken.Parse(Client.DownloadString(PlayerListEndpoint));
                    foreach (JToken token in playerListToken)
                    {
                        if (token["summonerName"].ToString().Equals(ActivePlayerName))
                        {
                            ChampionName = token["championName"].ToString();
                            string[] rawNameArray = token["rawChampionName"].ToString().Split('_', StringSplitOptions.RemoveEmptyEntries);
                            RawChampionName = rawNameArray[^1];
                        }
                    }

                    if (!GetChampionBaseValues(RawChampionName))
                    {
                        IsIntializingValues = false;
                        IsUpdatingAttackValues = false;
                        return;
                    }

#if DEBUG
                    Console.replacedle = $"({ActivePlayerName}) {ChampionName}";
#endif

                    IsIntializingValues = false;
                }

#if DEBUG
                Console.SetCursorPosition(0, 0);
                Console.WriteLine($"{owStopWatch.ElapsedMilliseconds}\n" +
                    $"Attack Speed Ratio: {ChampionAttackSpeedRatio}\n" +
                    $"Windup Percent: {ChampionAttackDelayPercent}\n" +
                    $"Current AS: {ClientAttackSpeed:0.00####}\n" +
                    $"Seconds Per Attack: {GetSecondsPerAttack():0.00####}\n" +
                    $"Windup Duration: {GetWindupDuration():0.00####}s + {WindupBuffer}s delay\n" +
                    $"Attack Down Time: {(GetSecondsPerAttack() - GetWindupDuration()):0.00####}s");
#endif

                ClientAttackSpeed = activePlayerToken["championStats"]["attackSpeed"].Value<double>();
                IsUpdatingAttackValues = false;
            }
        }

19 Source : PatchTask.cs
with GNU General Public License v3.0
from AtomCrafty

protected override void Execute() {
			// init patch directory
			if(flags.Has("init")) {
				string fetchUrl = arguments.Length > 0 ? arguments[0] : "";
				string gameDirectory = arguments.Length > 1 ? Helpers.AbsolutePath(arguments[1]) : Directory.GetCurrentDirectory();
				string patchDirectory = arguments.Length > 2 ? Helpers.AbsolutePath(arguments[2]) : Path.Combine(gameDirectory, "autopatch");
				string patchFilePath = Path.ChangeExtension(patchDirectory, Constants.ypl);

				Directory.CreateDirectory(patchDirectory);

				dynamic info = new JObject();
				info.gamedir = gameDirectory;
				info.patchdir = patchDirectory;
				info.fetchurl = fetchUrl;
				info.history = new JArray();

				File.WriteAllText(patchFilePath, JsonConvert.SerializeObject(info, Formatting.Indented));

				Console.WriteLine("GameDir:   " + gameDirectory);
				Console.WriteLine("PatchDir:  " + patchDirectory);
				Console.WriteLine("PatchFile: " + patchFilePath);
			}

			else {
				if(arguments.Length == 0) Fail("No target file specified");
				string targetBasePath = Helpers.AbsolutePath(arguments[0]);

				// patch archive
				if(targetBasePath.EndsWith(Constants.ykc, StringComparison.OrdinalIgnoreCase)) {
					if(arguments.Length == 1) Fail("No patch file specified");
					string patchBasePath = Helpers.AbsolutePath(arguments[1]);

					if(!File.Exists(targetBasePath)) Fail("The specified target archive does not exist");
					if(!File.Exists(patchBasePath)) Fail("The specified patch archive does not exist");

					Patch(targetBasePath, patchBasePath);
				}

				// patch file
				else if(targetBasePath.EndsWith(Constants.ypl, StringComparison.OrdinalIgnoreCase)) {
					dynamic info = JsonConvert.DeserializeObject(File.ReadAllText(targetBasePath));
					string gameDirectory = info.gamedir;
					string patchDirectory = info.patchdir;
					string fetchUrl = info.fetchurl;

					List<string> history = new List<string>();
					foreach(string f in info.history) {
						history.Add(f);
					}

					if(!Directory.Exists(gameDirectory)) Fail("Game directory does not exist");
					if(!Directory.Exists(patchDirectory)) Fail("Patch directory does not exist");

					// download new patch files
					int finishedDownloads = 0, skippedDownloads = 0;
					if(fetchUrl != null && fetchUrl.Length > 2) {
						using(WebClient web = new WebClient()) {
							Log("Fetching patch list from " + fetchUrl, ConsoleColor.Cyan);
							string[] remoteFiles = web.DownloadString(fetchUrl).Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

							foreach(string fileUri in remoteFiles) {
								if(fileUri == "") continue;
								string fileName = Path.GetFileName(fileUri);
								string filePath = Path.Combine(patchDirectory, fileName);
								if(File.Exists(filePath)) {
									skippedDownloads++;
								}
								else {
									Log("Downloading " + fileName, ConsoleColor.Yellow);
									web.DownloadFile(fileUri, filePath);
									finishedDownloads++;
								}
							}
						}
					}
					if(skippedDownloads + finishedDownloads > 0) {
						Log("Downloaded " + finishedDownloads + " patches, skipped " + skippedDownloads, ConsoleColor.Green);
					}

					// apply patch files
					int appliedPatches = 0, skippedPatches = 0;
					string[] localFiles = Directory.GetFiles(patchDirectory, "*." + Constants.ykc);
					foreach(string filePath in localFiles) {
						string fileName = Path.GetFileName(filePath);
						if(history.Contains(fileName)) {
							skippedPatches++;
						}
						else {
							bool found = false;
							for(int i = 1; i <= 5; i++) {
								string archiveName = "data0" + i;
								string archivePath = Path.Combine(gameDirectory, archiveName + '.' + Constants.ykc);
								if(fileName.Contains(archiveName) && File.Exists(archivePath)) {
									if(flags.Has('v')) {
										Console.ForegroundColor = ConsoleColor.Yellow;
										Console.WriteLine("Applying patch " + fileName);
										Console.ResetColor();
									}
									found = true;
									Patch(archivePath, filePath);
									appliedPatches++;
									break;
								}
							}
							if(found) {
								history.Add(fileName);
							}
							else {
								Log("Could not determine target archive for patch '" + fileName + "'", ConsoleColor.Red);
							}
						}
					}
					if(skippedPatches + appliedPatches > 0) {
						Log("Applied " + appliedPatches + " patches, skipped " + skippedPatches, ConsoleColor.Green);
					}

					info.history = JArray.FromObject(history.ToArray());
					File.WriteAllText(targetBasePath, JsonConvert.SerializeObject(info, Formatting.Indented));
				}
			}

			if(flags.Has('w')) {
				Console.ReadLine();
			}
		}

19 Source : WaveForm.cs
with MIT License
from azist

public void Action_GetList(WebClient wc)
      {
        //using (var wc = CreateWebClient())
        {
          string str = wc.DownloadString(m_ServerURI + "GetList");

          if ("application/json" != wc.ResponseHeaders[HttpResponseHeader.ContentType]) throw new Exception();

          var obj = JSONReader.DeserializeDynamic(str);

          if (3 != obj.Data.Count) throw new Exception();
          if (1UL != obj.Data[0]) throw new Exception();
          if (2UL != obj.Data[1]) throw new Exception();
          if (3UL != obj.Data[2]) throw new Exception();
        }
      }

19 Source : WaveForm.cs
with MIT License
from azist

private void Action_Empty(WebClient wc)
      {
        //using (var wc = CreateWebClient())
        {
          var res = wc.DownloadString(m_ServerURI + "Empty");

          if (res.IsNotNullOrEmpty()) throw new Exception();
        }
      }

19 Source : WaveForm.cs
with MIT License
from azist

private void Action_Action0Name(WebClient wc)
      {
        //using (var wc = CreateWebClient())
        {
          try
          {
            wc.DownloadString(m_ServerURI + "ActionName0");
            throw new Exception(EXPECTED_404);
          }
          catch (WebException ex)
          {
            if (!Is404(ex)) throw new Exception();
          }
        }
      }

19 Source : WaveForm.cs
with MIT License
from azist

public void Action_GetWithNoPermission(WebClient wc)
      {
        //using (var wc = CreateWebClient())
        {
          string str = wc.DownloadString(m_ServerURI + "GetWithPermission");

          if ("text/html" != wc.ResponseHeaders[HttpResponseHeader.ContentType]) throw new Exception();
          if (!Regex.IsMatch(str, "Authorization to .+/TestPath/TestPermission.+ failed")) throw new Exception();
        }
      }

19 Source : WaveForm.cs
with MIT License
from azist

public void Action_RowGet_JSONDataMap(WebClient wc)
      {
        var start = DateTime.Now;

        System.Threading.Thread.Sleep(3000);

        //using (var wc = CreateWebClient())
        {
          string str = wc.DownloadString(m_ServerURI + "RowGet");

          if ("application/json" != wc.ResponseHeaders[HttpResponseHeader.ContentType]) throw new Exception();

          var obj = JSONReader.DeserializeDynamic(str);

          if (16 != obj.Data.Count) throw new Exception();
          if (777UL != obj.Data["ID"]) throw new Exception();
          if ("Test Name" != obj.Data["Name"]) throw new Exception();

          var date = DateTime.Parse(obj.Data["Date"]);
          if ((DateTime.Now - start).TotalSeconds < 2.0d) throw new Exception();
          if ("Ok" != obj.Data["Status"]) throw new Exception();

          var gotTs = TimeSpan.FromTicks((long)(ulong)(obj.Data["Span"]));
          if (TimeSpan.FromSeconds(1) != gotTs) throw new Exception();
        }
      }

19 Source : WaveForm.cs
with MIT License
from azist

public void Action_RowGet_TypeRow(WebClient wc)
      {
        var start = DateTime.Now;

        //using (var wc = CreateWebClient())
        {
          string str = wc.DownloadString(m_ServerURI + "RowGet");

          if ("application/json" != wc.ResponseHeaders[HttpResponseHeader.ContentType]) throw new Exception();
            
          var map = JSONReader.DeserializeDataObject(str) as JSONDataMap;
          var gotRow = JSONReader.ToRow<TestRow>(map);
        }
      }

19 Source : WaveForm.cs
with MIT License
from azist

public void Action_Login(WebClient wc)
      {
        var values = new NameValueCollection();
        values.Add("id", USER_ID);
        values.Add("pwd", USER_PWD);

        //using (var wc = CreateWebClient())
        {
          var bytes = wc.UploadValues(m_ServerURI + "LoginUser", values);
          var str = GetUTF8StringWOBOM(bytes);

          Console.WriteLine(str);

          if ("application/json" != wc.ResponseHeaders[HttpResponseHeader.ContentType]) throw new Exception();

          var obj = JSONReader.DeserializeDynamic(str);
          if (USER_STATUS != obj["Status"]) throw new Exception();
          if (USER_NAME != obj["Name"]) throw new Exception();

          str = wc.DownloadString(m_ServerURI + "GetWithPermission");

          if (Regex.IsMatch(str, "Authorization to .+/TestPath/TestPermission.+ failed")) throw new Exception();
        }
      }

19 Source : UpdateChecker.cs
with Apache License 2.0
from Azure99

public static void CheckUpdate()
        {
            try
            {
                using (WebClient client = new WebClient())
                {
                    string versionStr = client.DownloadString(VERSION_URL);
                    int version = int.Parse(versionStr);
                    if (NOW_VERSION < version)
                    {
                        if (MessageBox.Show("检测到版本更新, 是否前往发布页面?", "版本更新", MessageBoxButton.YesNo,
                            MessageBoxImage.Question) == MessageBoxResult.Yes)
                        {
                            Process.Start(RELEASE_PAGE_URL);
                            MessageBus.Exit();
                        }
                    }
                }
            }
            catch
            {
                // ignored
            }
        }

19 Source : GenshinAPI.cs
with Apache License 2.0
from Azure99

private static ServerResponse<T> Get<T>(string url)
        {
            return Request<T>(x => x.DownloadString(url), CreateDynamicSecret(url, ""));
        }

19 Source : HttpWebClient.cs
with MIT License
from Azure99

public string DownloadString(string address, int maxTry)
        {
            int tryCount = 0;
            Exception lastException = new Exception();

            while (tryCount++ < maxTry)
            {
                try
                {
                    return DownloadString(address);
                }
                catch (Exception ex)
                {
                    lastException = ex;
                }
            }

            throw lastException;
        }

19 Source : HttpWebClient.cs
with MIT License
from Azure99

public bool TryDownloadString(string address, out string result)
        {
            try
            {
                result = DownloadString(address);
                return true;
            }
            catch
            {
                result = null;
                return false;
            }
        }

19 Source : HttpWebClient.cs
with MIT License
from Azure99

public bool TryDownloadString(string address, out string result, int maxTray)
        {
            try
            {
                result = DownloadString(address);
                return true;
            }
            catch
            {
                result = null;
                return false;
            }
        }

19 Source : Client.cs
with GNU General Public License v3.0
from Azure99

public static string GET(string url, int tryCount = 2) 
        {
            Exception lastEx = new ApplicationException("Cannot get " + url);
            while (tryCount-- > 0)
            {
                try
                {
                    _wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36");
                    return _wc.DownloadString(url);
                }
                catch (Exception ex)
                {
                    lastEx = ex;
                }
            }
            throw lastEx;
        }

19 Source : Utility.cs
with BSD 3-Clause "New" or "Revised" License
from b4rtik

public static TaskMsg GetTaskHttp(CookiedWebClient wc, byte[] aeskey, byte[] aesiv, string rpaddress, string targetclreplaced, bool isCovered)
        {

            wc.UseDefaultCredentials = true;
            wc.Proxy = WebRequest.DefaultWebProxy;
            wc.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
            string resp = wc.DownloadString(rpaddress);

            if (!string.IsNullOrEmpty(resp))
            {
                if (isCovered)
                {
                    string baseurl = rpaddress.Substring(0, rpaddress.LastIndexOf('/'));
                    resp = Encoding.Default.GetString(ImageLoader.ImageLoader.Load(baseurl, rpaddress, resp, wc, targetclreplaced));
                }
                var line = Crypto.Aes.DecryptAesMessage(Convert.FromBase64String(resp), aeskey, aesiv);

                TaskMsg task = null;
                try
                {
                    task = new JavaScriptSerializer().Deserialize<TaskMsg>(line);
                    //task = JsonConvert.DeserializeObject<TaskMsg>(line);
                }
                catch (Exception)
                {
                }

                return task;
            }
            else
            {
                return null;
            }

        }

19 Source : utils.cs
with MIT License
from b9q

public static string[] get_usernames()
        {
            const string api_url = "https://versacehack.xyz/polymorphic/get_users.php";
            WebClient web = new WebClient();
            web.Headers.Add("user-agent", "VER$ACE-LOADER-BOT");
            var usernames = web.DownloadString(api_url).Split(' ');
            for (int i = 0; i < usernames.Length; i++)
            {
                usernames[i] = usernames[i].Trim();
            }

            return usernames;
        }

19 Source : TimeWeatherManager.cs
with MIT License
from Battlerax

private void WeatherTimeTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _elapsedMinutes += 1;

            //Update time first.
            Minutes += 2;
            if (Minutes >= 60)
            {
                Minutes = 0;
                Hours++;
                if (Hours >= 24)
                {
                    Hours = 0;
                }
            }
            NAPI.World.SetTime(Hours, Minutes, 0);

            //Update weather
            if (_elapsedMinutes >= 30)
            {
                _elapsedMinutes = 0;
                WebClient client = new WebClient();
                string reply = String.Empty;
                try
                {
                    reply =
                        client.DownloadString(
                            "https://api.apixu.com/v1/current.json?key=2e4a0092a177439cab8165133172805&q=Los%20Angeles");
                }
                catch (WebException ex)
                {
                    NAPI.Util.ConsoleOutput("Weather API Exception: " + ex.Status);
                }
                Match result = Regex.Match(reply, "\\{.*\\\"code\\\":([0-9]+)\\}");
                if (result.Success)
                {
                    int code = Convert.ToInt32(result.Groups[1].Value);
                    //Check and apply.
                    switch (code)
                    {
                        case 1000:
                            NAPI.World.SetWeather(0);
                            break;
                        case 1003:
                            NAPI.World.SetWeather((Weather)1);
                            break;
                        case 1006:
                            NAPI.World.SetWeather((Weather)2);
                            break;
                        case 1009:
                            NAPI.World.SetWeather((Weather)5);
                            break;
                        case 1030:
                        case 1135:
                        case 1147:
                            NAPI.World.SetWeather((Weather)4);
                            break;
                        case 1063:
                        case 1072:
                        case 1150:
                        case 1153:
                        case 1168:
                        case 1171:
                        case 1180:
                        case 1183:
                        case 1186:
                        case 1189:
                        case 1198:
                        case 1204:
                        case 1240:
                        case 1249:
                            NAPI.World.SetWeather((Weather)8);
                            break;
                        case 1066:
                        case 1069:
                        case 1210:
                        case 1216:
                        case 1255:
                        case 1261:
                            NAPI.World.SetWeather((Weather)10);
                            break;
                        case 1087:
                        case 1273:
                        case 1276:
                        case 1279:
                        case 1282:
                            NAPI.World.SetWeather((Weather)7);
                            break;
                        case 1114:
                            NAPI.World.SetWeather((Weather)11);
                            break;
                        case 1117:
                        case 1213:
                        case 1219:
                        case 1222:
                        case 1225:
                        case 1237:
                        case 1258:
                        case 1264:
                            NAPI.World.SetWeather((Weather)12);
                            break;
                        case 1192:
                        case 1195:
                        case 1201:
                        case 1207:
                        case 1243:
                        case 1246:
                        case 1252:
                            NAPI.World.SetWeather((Weather)6);
                            break;
                    }
                    NAPI.Util.ConsoleOutput("Set Weather To " + NAPI.World.GetWeather());
                }
            }
        }

19 Source : MappingManager.cs
with MIT License
from Battlerax

[RemoteEvent("requestCreateMapping")]
        public void RequestCreateMapping(Player player, params object[] arguments)
        {
            var propLink = Convert.ToInt32(arguments[0]);
            var dimension = Convert.ToInt32(arguments[1]);
            var pastebinLink = Convert.ToString(arguments[2]);
            var description = Convert.ToString(arguments[3]);

            if (dimension < 0)
            {
                NAPI.ClientEvent.TriggerClientEvent(player, "send_error", "The dimension entered is less than 0.");
                return;
            }

            if (propLink > 0)
            {
                if (PropertyManager.Properties.FindAll(p => p.Id == propLink).Count < 1)
                {
                    NAPI.ClientEvent.TriggerClientEvent(player, "send_error", "The property link ID you entered is invalid.");
                    return;
                }
            }

            var webClient = new WebClient();

            try
            {
                var pastebinData = webClient.DownloadString("http://pastebin.com/raw/" + pastebinLink);

                var newMapping = new Mapping(player.GetAccount().AdminName, pastebinLink, description, propLink, dimension);
                newMapping.Objects = ParseObjectsFromString(pastebinData);
                newMapping.DeleteObjects = ParseDeleteObjectsFromString(pastebinData);
                newMapping.Insert();
                newMapping.Load();
                Mapping.Add(newMapping);

                LogManager.Log(LogManager.LogTypes.MappingRequests, player.GetAccount().AccountName + " has created mapping request #" + newMapping.Id);
                NAPI.Chat.SendChatMessageToPlayer(player, core.Color.White, "You have successfully created and loaded mapping request #" + newMapping.Id);
                return;
            }
            catch (WebException e)
            {
                if (((HttpWebResponse)e.Response).StatusCode.ToString() == "NotFound")
                {
                    NAPI.ClientEvent.TriggerClientEvent(player, "send_error", "The pastebin link you entered does not exist.");
                    return;
                }
            }
        }

19 Source : VSCode.cs
with MIT License
from benotter

static void CheckForUpdate()
        {
            var fileContent = string.Empty;

            EditorUtility.DisplayProgressBar("VSCode", "Checking for updates ...", 0.5f);

            // Because were not a runtime framework, lets just use the simplest way of doing this
            try
            {
                using (var webClient = new System.Net.WebClient())
                {
                    fileContent = webClient.DownloadString("https://raw.githubusercontent.com/dotBunny/VSCode/master/Plugins/Editor/VSCode.cs");
                }
            }
            catch (Exception e)
            {
                if (Debug)
                {
                    UnityEngine.Debug.Log("[VSCode] " + e.Message);

                }

                // Don't go any further if there is an error
                return;
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }

            // Set the last update time
            LastUpdate = DateTime.Now;

            // Fix for oddity in downlo
            if (fileContent.Substring(0, 2) != "/*")
            {
                int startPosition = fileContent.IndexOf("/*", StringComparison.CurrentCultureIgnoreCase);

                // Jump over junk characters
                fileContent = fileContent.Substring(startPosition);
            }

            string[] fileExploded = fileContent.Split('\n');
            if (fileExploded.Length > 7)
            {
                float github = Version;
                if (float.TryParse(fileExploded[6].Replace("*", "").Trim(), out github))
                {
                    GitHubVersion = github;
                }


                if (github > Version)
                {
                    var GUIDs = replacedetDatabase.Findreplacedets("t:Script VSCode");
                    var path = Application.dataPath.Substring(0, Application.dataPath.Length - "/replacedets".Length) + System.IO.Path.DirectorySeparatorChar +
                               replacedetDatabase.GUIDToreplacedetPath(GUIDs[0]).Replace('/', System.IO.Path.DirectorySeparatorChar);

                    if (EditorUtility.DisplayDialog("VSCode Update", "A newer version of the VSCode plugin is available, would you like to update your version?", "Yes", "No"))
                    {
                        // Always make sure the file is writable
                        System.IO.FileInfo fileInfo = new System.IO.FileInfo(path);
                        fileInfo.IsReadOnly = false;

                        // Write update file
                        File.WriteAllText(path, fileContent);

                        // Force update on text file
                        replacedetDatabase.Importreplacedet(replacedetDatabase.GUIDToreplacedetPath(GUIDs[0]), ImportreplacedetOptions.ForceUpdate);
                    }

                }
            }
        }

19 Source : NetworkInfoAsync.cs
with GNU General Public License v3.0
from berichan

public static void SendDaemonAsync(string ipBase = "192.168.0.")
    {
        activeIP = new List<string>();
        upCount = 0;
        try
        {
            string ident = string.Empty;
            using (var webc = new WebClient())
                ident = webc.DownloadString(macIdentifiers);
            Console.WriteLine("Idenreplacedies downloaded");
            idents = new List<string>(ident.Split(new string[] { "\r", "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
            idents = idents.Where(x => !x.StartsWith("\t")).ToList();
            UnityEngine.Debug.Log("Idenreplacedies created");
        }
        catch { }

        countdown = new CountdownEvent(1);
        Stopwatch sw = new Stopwatch();
        sw.Start();
        for (int i = 1; i < 255; i++)
        {
            string ip = ipBase + i.ToString();
            string[] fourByteIp = ip.Split('.');
            if (fourByteIp.Length != 4)
                throw new Exception("IP address did not contain four values");
            byte[] ipBytes = new byte[4] { byte.Parse(fourByteIp[0]), byte.Parse(fourByteIp[1]), byte.Parse(fourByteIp[2]), byte.Parse(fourByteIp[3]) };
            System.Net.IPAddress addr = new System.Net.IPAddress(ipBytes);

            Ping p = new Ping();
            p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted);
            countdown.AddCount();
            p.SendPingAsync(addr, 500, null);
        }
        countdown.Signal();
        countdown.Wait();
        sw.Stop();
        TimeSpan span = new TimeSpan(sw.ElapsedTicks);
        UnityEngine.Debug.Log(string.Format("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount));
    }

19 Source : HardwareHelper.cs
with Apache License 2.0
from bezzad

public static IPAddress Ip()
        {
            var wc = new WebClient();
            var strInternetProtocol = wc.DownloadString("https://ipv4.wtfismyip.com/text");
            if (IPAddress.TryParse(strInternetProtocol.Trim(), out var ip))
                return ip;
            return null;
        }

19 Source : NameFetchingService.cs
with Mozilla Public License 2.0
from BibleBot

private async Task<Dictionary<string, string>> GetBibleGatewayVersions()
        {
            Dictionary<string, string> versions = new Dictionary<string, string>();

            string resp = _webClient.DownloadString("https://www.biblegateway.com/versions/");
            var doreplacedent = await BrowsingContext.New().OpenAsync(req => req.Content(resp));

            var translationElements = doreplacedent.All.Where(el => el.ClreplacedList.Contains("translation-name"));
            foreach (var el in translationElements)
            {
                var targets = el.GetElementsByTagName("a");

                if (targets.Length == 1)
                {
                    if (targets[0].HasAttribute("href"))
                    {
                        versions.Add(targets[0].TextContent, $"https://www.biblegateway.com{targets[0].GetAttribute("href")}");
                    }
                }
            }

            return versions;
        }

19 Source : NameFetchingService.cs
with Mozilla Public License 2.0
from BibleBot

private async Task<Dictionary<string, List<string>>> GetBibleGatewayNames(Dictionary<string, string> versions)
        {
            Dictionary<string, List<string>> names = new Dictionary<string, List<string>>();

            List<string> threeMaccVariants = new List<string> { "3macc", "3m" };
            List<string> fourMaccVariants = new List<string> { "4macc", "4m" };
            List<string> greekEstherVariants = new List<string> { "gkesth", "adest", "addesth", "gkes" };
            List<string> prayerAzariahVariants = new List<string> { "sgthree", "sgthr", "prazar" };

            foreach (KeyValuePair<string, string> version in versions)
            {
                string resp = _webClient.DownloadString(version.Value);
                var doreplacedent = await BrowsingContext.New().OpenAsync(req => req.Content(resp));

                var bookNames = doreplacedent.All.Where(el => el.ClreplacedList.Contains("book-name"));
                foreach (var el in bookNames)
                {
                    foreach (var span in el.GetElementsByTagName("span"))
                    {
                        span.Remove();
                    }

                    if (el.HasAttribute("data-target"))
                    {
                        string dataName = el.GetAttribute("data-target").Substring(1, el.GetAttribute("data-target").Length - 6);
                        string bookName = el.TextContent.Trim();

                        if (threeMaccVariants.Contains(dataName))
                        {
                            dataName = "3ma";
                        }
                        else if (fourMaccVariants.Contains(dataName))
                        {
                            dataName = "4ma";
                        }
                        else if (greekEstherVariants.Contains(dataName))
                        {
                            dataName = "gkest";
                        }
                        else if (prayerAzariahVariants.Contains(dataName))
                        {
                            dataName = "praz";
                        }
                        else if (dataName == "epjer")
                        {
                            continue;
                        }

                        if (!IsNuisance(bookName))
                        {
                            if (names.ContainsKey(dataName))
                            {
                                if (!names[dataName].Contains(bookName))
                                {
                                    names[dataName].Add(bookName);
                                }
                            }
                            else
                            {
                                names[dataName] = new List<string> { bookName };
                            }
                        }
                    }
                }
            }

            return names;
        }

See More Examples