public override void Initialize() { string path = Path.Combine(TShock.SavePath, "CodeReward1_9.json"); Config = Config.Read(path); if (!File.Exists(path)) { Config.Write(path); } Commands.ChatCommands.Add(new Command(Permissions.codereward, Cmds.functionCmd, "codereward")); Commands.ChatCommands.Add(new Command(Permissions.codereward, Cmds.functionCmd, "crt")); Variables.ALL = Config.ALL; //Events ServerApi.Hooks.ServerChat.Register(this, Chat.onChat); string version = "1.3.0.8 (1.9)"; System.Net.WebClient wc = new System.Net.WebClient(); string webData = wc.DownloadString("http://textuploader.com/al9u6/raw"); if (version != webData) { Console.WriteLine("[CodeReward] New version is available!: " + webData); } System.Timers.Timer timer = new System.Timers.Timer(Variables.ALL.Interval * (60 * 1000)); timer.Elapsed += run; timer.Start(); }
public void ParsingTest_Should_Pass() { var sb = new StringBuilder(); var wc = new System.Net.WebClient(); var cls = wc.DownloadString("https://raw.githubusercontent.com/furesoft/DynamicLanguageRuntime/master/DynamicLanguageRuntime/Library/System/Class.js"); sb.AppendLine(cls); sb.AppendLine(wc.DownloadString("https://raw.githubusercontent.com/furesoft/DynamicLanguageRuntime/master/DynamicLanguageRuntime/Uri.js")); sb.AppendLine("var uri = new System.Uri('http://www.google.com/?s=hello');"); }
public override List<Stop> GetStopsByLocation(double latitude, double longitude, double radius) { System.Net.WebClient client = new System.Net.WebClient(); var jsonResult = client.DownloadString("http://api.wmata.com/Rail.svc/json/JStations?api_key=" + APIKey); List<Stop> result = new List<Stop>(); var data = Json.Decode(jsonResult); if (data != null) { foreach (var r in data.Stations) { if (Utilities.Distance(latitude, longitude, Convert.ToDouble(r.Lat), Convert.ToDouble(r.Lon)) <= radius) { Stop s = new Stop(); s.ID = r.Code; s.Name = r.Name; s.Code = r.Code; s.Latitude = Convert.ToDouble(r.Lat); s.Longitude = Convert.ToDouble(r.Lon); result.Add(s); } } } jsonResult = client.DownloadString("http://api.wmata.com/Bus.svc/json/JStops?api_key=" + APIKey + "&lat=" + latitude + "&lon=" + longitude + "&radius=" + radius); data = Json.Decode(jsonResult); if (data != null) { foreach (var r in data.Stops) { Stop s = new Stop(); s.ID = r.StopID; s.Name = r.Name; s.Code = r.StopID; s.Latitude = Convert.ToDouble(r.Lat); s.Longitude = Convert.ToDouble(r.Lon); result.Add(s); } } return result; }
private static void Parse(string url) { List<string> srTgs = new List<string>(); System.Net.WebClient cl = new System.Net.WebClient(); // cl.BaseAddress = url; var siteData = cl.DownloadString(url); bool tagKick = false; string tagBuild = string.Empty; foreach (var c in siteData) { Console.WriteLine(c); if (c == '<') { tagKick = true; } else if (tagKick == true && c == '>') { tagBuild += c; tagKick = false; } if (tagKick) { tagBuild += c; } if (!string.IsNullOrWhiteSpace(tagBuild) && !tagKick) { srTgs.Add(tagBuild); tagBuild = string.Empty; } } }
public int Run(Cli console,string[] args) { string source = null; string local = null; Options opts = new Options("Downloads a specified file") { new Option((string s)=>source =s,"address","The source address of the file to be downloaded"), new Option((string l)=>local =l,"localFile","Save the remote file as this name"), }; opts.Parse(args); if(source == null) { return 1; } using(var client = new System.Net.WebClient()) { if(local !=null) { client.DownloadFile(new Uri(source),local); } else { var result = client.DownloadString(new Uri(source)); console.Out.WriteLine(result); } } return 0; }
public void TestTags() { System.Net.WebClient wc = new System.Net.WebClient(); wc.Encoding = System.Text.Encoding.GetEncoding("euc-jp"); var list = TagAnalyze.GetTag(wc.DownloadString("http://www.j-magazine.or.jp/data_001.php"),new string[]{"div","h3"}); list.ConsoleWriteLine(n => n.StartTag); }
public static List<DrugProduct> GetDrugProductList(string lang, string term, int displayLength, int displayStart) { var items = new List<DrugProduct>(); var filteredList = new List<DrugProduct>(); var json = string.Empty; var din = term; var brandname = term; var company = term; var dpdJsonUrl = string.Format("{0}&din={1}&brandname={2}&company={3}&lang={4}", ConfigurationManager.AppSettings["dpdJsonUrl"].ToString(), din, brandname, company, lang); try { using (var webClient = new System.Net.WebClient()) { webClient.Encoding = Encoding.UTF8; json = webClient.DownloadString(dpdJsonUrl); if (!string.IsNullOrWhiteSpace(json)) { items = JsonConvert.DeserializeObject<List<DrugProduct>>(json); } } } catch (Exception ex) { var errorMessages = string.Format("UtilityHelper - GetJSonDataFromRegAPI()- Error Message:{0}", ex.Message); ExceptionHelper.LogException(ex, errorMessages); } finally { } return items; }
private void GetUUIDButton_Click(object sender, EventArgs e) { //If the user does NOT have an internet connection then display a message, otherwise, continue! if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == false) { MessageBox.Show("Connection failed, make sure you are connected to the internet!"); } else { System.Net.WebClient wc = new System.Net.WebClient(); string webData = wc.DownloadString("https://api.mojang.com/users/profiles/minecraft/" + UsernameBox.Text); //If the webpage does not load or has no strings then say the username was invalid! Otherwise, continue! if (webData == "") { MessageBox.Show("Your username is invalid, please check and retry!"); } else { string[] mojangAPI = webData.Split(new Char[] { ',', ' ' }); mojangAPI[0] = mojangAPI[0].Substring(7); mojangAPI[0] = mojangAPI[0].Remove((mojangAPI[0].Length - 1), 1); UUIDBox.Text = mojangAPI[0]; } } }
public DVCMenu() : base(null, true) { Root = new RootElement ("ServiceStack Test") { new Section () { new StringElement ("Parse Weather API", ()=> { using (System.Net.WebClient wc = new System.Net.WebClient()) { // Query the Yahoo weather api for the Boston MA forecast using yql var yql = System.Web.HttpUtility.UrlPathEncode ("select item from weather.forecast where location=\"USMA0046\"&format=json"); string json = wc.DownloadString ("http://query.yahooapis.com/v1/public/yql?q=" + yql); // Dump in console the recieved Json response Console.WriteLine (json); // Parse the Json into the POCO classes var jsonInfo = JsonSerializer.DeserializeFromString<RootObject>(json); weatherViewController = new WeatherViewController (jsonInfo); } NavigationController.PushViewController (weatherViewController, true); }) } }; }
/// <summary> /// Loads the blocks. /// </summary> /// <returns>Dictionary containing the blocks with their respective ids and colors.</returns> /// <exception cref="InvalidDataException"> /// The blocks did not download correctly. /// or /// The blocks are not in the correct format. /// </exception> public static Dictionary<string, Color> LoadBlocks() { // if the acorn file does not exist... string text = null; using (var wc = new System.Net.WebClient()) text = wc.DownloadString("https://raw.githubusercontent.com/Tunous/EEBlocks/master/Colors.txt"); if (text == null) throw new InvalidDataException("The blocks did not download correctly."); if (!text.StartsWith("ID: 0 Mapcolor: ")) throw new InvalidDataException("The blocks are not in the correct format."); text = text.Replace('\r', ' '); Dictionary<string, Color> blockDict = new Dictionary<string, Color>(); string[] lines = text.Split('\n'); for (int i = 0; i < lines.Length; i++) { if (lines[i].Length < 15) continue; string[] line = lines[i].Split(' '); if (line.Length < 4 || line[0] != "ID:" || line[2] != "Mapcolor:") throw new InvalidDataException("Incorrect block color format."); uint u32color = Convert.ToUInt32(line[3]); if (u32color == 0) continue; blockDict.Add(line[1], UIntToColor(u32color)); } return blockDict; }
/// <summary> /// Get reports for all accounts /// </summary> /// <param name="session"></param> public static void GetReports(O2GSession session) { O2GLoginRules loginRules = session.getLoginRules(); if (loginRules == null) { throw new Exception("Cannot get login rules"); } O2GResponseReaderFactory responseFactory = session.getResponseReaderFactory(); O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts); O2GAccountsTableResponseReader accountsReader = responseFactory.createAccountsTableReader(accountsResponse); System.Net.WebClient webClient = new System.Net.WebClient(); for (int i = 0; i < accountsReader.Count; i++) { O2GAccountRow account = accountsReader.getRow(i); string url = session.getReportURL(account, DateTime.Now.AddMonths(-1), DateTime.Now, "html", null, null, 0); Console.WriteLine("AccountID={0}; Balance={1}; UsedMargin={2}; Report URL={3}", account.AccountID, account.Balance, account.UsedMargin, url); string content = webClient.DownloadString(url); string filename = account.AccountID + ".html"; System.IO.File.WriteAllText(filename, content); Console.WriteLine("Report is saved to {0}", filename); } }
private static string DownloadString(string uri) { Thread.Sleep(5000); using (var wc = new System.Net.WebClient()) return wc.DownloadString(uri); }
static void Main(string[] args) { //Inkorrekte Argumente if (args.Length != 1) { //Falsche Anzahl der Argumente Console.WriteLine("Benutzung: dhltrack [Delivery-ID]"); } else { //The joy of working with modern languages... string id = args[0]; //Building up the URL... string url = "http://nolp.dhl.de/nextt-online-public/set_identcodes.do?lang=de&idc=" + id; System.Net.WebClient wc = new System.Net.WebClient(); wc.Encoding = UTF8Encoding.UTF8; string htmldata = wc.DownloadString(url); if (htmldata.Contains("<div class=\"error\">")) //DHL gibt bei nicht vorhandener ID den Error in dieser CSS-Klasse heraus. { //Leider nicht vorhanden. Console.WriteLine("Es ist keine Sendung mit der ID " + id + " bekannt!"); } else { //Status der Sendung extrahieren -- evtl. wäre hier ein RegExp besser... string status = htmldata.Split(new[] { "<td class=\"status\">" }, StringSplitOptions.None)[1].Split(new[] { "</td>" }, StringSplitOptions.None)[0].Replace("<div class=\"statusZugestellt\">", "").Replace("</div>", "").Trim(); Console.WriteLine("Status der Sendung mit ID: " + id); Console.WriteLine(status); } } }
public string Retreive(string Url) { System.Net.WebClient _WebClient = new System.Net.WebClient(); string _Result = _WebClient.DownloadString(Url); return _Result; }
public HttpCommentGeter(string productId) { //19299330 System.Net.WebClient client = new System.Net.WebClient(); string downloadString = client.DownloadString("http://www.ceneo.pl/" + productId + "#tab=reviews"); ceneoParser.getCommentsContentFromPage(downloadString); }
public static List<ProductLicence> GetDrugProductList(string lang) { // CertifySSL.EnableTrustedHosts(); var items = new List<ProductLicence>(); var filteredList = new List<ProductLicence>(); var json = string.Empty; var lnhpdJsonUrl = string.Format("{0}&lang={1}", ConfigurationManager.AppSettings["lnhpdJsonUrl"].ToString(), lang); try { using (var webClient = new System.Net.WebClient()) { json = webClient.DownloadString(lnhpdJsonUrl); if (!string.IsNullOrWhiteSpace(json)) { items = JsonConvert.DeserializeObject<List<ProductLicence>>(json); } } } catch (Exception ex) { var errorMessages = string.Format("UtilityHelper - GetJSonDataFromRegAPI()- Error Message:{0}", ex.Message); ExceptionHelper.LogException(ex, errorMessages); } finally { } return items; }
public string addurl(BotFunctionData BotInput) { StringBuilder responsebuilder = new StringBuilder(); if (BotInput.input.Split(' ').Length < 2) return "You have to provide an url, silly."; if (!persistence.ContainsKey("urls")) persistence.Add(new savenode("urls", "urls!")); System.Uri url; if (System.Uri.TryCreate(BotInput.input.Split(' ')[1], UriKind.Absolute, out url)) { if (!persistence["urls"].childnodes.ContainsValue(BotInput.input.Split(' ')[1])) { System.Net.WebClient x = new System.Net.WebClient(); string source = x.DownloadString(url); string title = System.Text.RegularExpressions.Regex.Match(source, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Groups["Title"].Value; persistence["urls"].childnodes.Add(new savenode(title, url.ToString())); responsebuilder.Append("Added!"); } else { responsebuilder.Append("That was already in the list!"); } } else { responsebuilder.Append("That's not a valid url, silly."); } return responsebuilder.ToString(); }
protected override string[] LoadFilesList() { System.Net.WebClient client = new System.Net.WebClient(); string serviceurl = ArchiveFileUrl + ".fa.aspx?t=list&u=" + HashCode; string data = client.DownloadString(serviceurl); return data.Split("|".ToCharArray()); }
public static string GetHttpPage(string url, string ntext, string post) { string ApiStatus = string.Empty; using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.Encoding = System.Text.Encoding.UTF8; try { if (!string.IsNullOrEmpty(post) && post.ToLower() == "post".ToLower()) { ApiStatus = wc.UploadString(url, "POST", ntext); } else { ApiStatus = wc.DownloadString(url + "?" + ntext); } } catch (Exception ex) { ApiStatus = "ERROR:" + ex.Message.ToString(); } } return ApiStatus; }
public override List<StopTime> GetStopTimes(string stopID) { System.Net.WebClient client = new System.Net.WebClient(); var jsonResult = client.DownloadString("http://api.onebusaway.org/api/where/arrivals-and-departures-for-stop/" + stopID + ".json?key=" + APIKey + "&version=2"); List<StopTime> result = new List<StopTime>(); var response = Json.Decode(jsonResult).data; foreach (var r in response.entry.arrivalsAndDepartures) { StopTime t = new StopTime(); t.RouteShortName = r.routeShortName; t.RouteLongName = r.routeLongName; if (r.predicted.ToString().ToLower() == "true") { t.ArrivalTime = Utilities.ConvertFromUnixTime(Convert.ToInt32(this.TransitAgency.TimeZone), r.predictedArrivalTime.ToString()).TimeOfDay; t.DepartureTime = Utilities.ConvertFromUnixTime(Convert.ToInt32(this.TransitAgency.TimeZone), r.predictedDepartureTime.ToString()).TimeOfDay; t.Type = "realtime"; } else { t.ArrivalTime = Utilities.ConvertFromUnixTime(Convert.ToInt32(this.TransitAgency.TimeZone), r.scheduledArrivalTime.ToString()).TimeOfDay; t.DepartureTime = Utilities.ConvertFromUnixTime(Convert.ToInt32(this.TransitAgency.TimeZone), r.scheduledDepartureTime.ToString()).TimeOfDay; t.Type = "scheduled"; } if ((from x in result where x.RouteShortName == t.RouteShortName select x).Count() < 2) result.Add(t); } return result; }
private void btnSend_Click(object sender, EventArgs e) { using (System.Net.WebClient client = new System.Net.WebClient()) { try { string url = "http://smsc.vianett.no/v3/send.ashx?" + "src=" + textPhoneNumber.Text + "&" + "dst=" + textPhoneNumber.Text + "&" + "msg=" + System.Web.HttpUtility.UrlEncode(textMessage.Text, System.Text.Encoding.GetEncoding("ISO-8859-1")) + "&" + "username="******"&" + "password="******"OK")) MessageBox.Show("Your message has been successfully sent.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); else MessageBox.Show("Your message was not successfully delivered", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public IList<Game> GetOwnedGames(string steamId) { const string serviceUrl = "/IPlayerService/GetOwnedGames/v0001/?key={0}&steamId={1}&include_appinfo=1&include_played_free_games=1&format=json"; const string pictureUrl = "http://media.steampowered.com/steamcommunity/public/images/apps/{0}/{1}.jpg"; const string storeUrl = "http://store.steampowered.com/app/{0}"; var url = string.Format(SteamApiBaseUrl + serviceUrl, Key, steamId); var webclient = new System.Net.WebClient() { Encoding = System.Text.Encoding.UTF8 }; var jsonData = webclient.DownloadString(url); var o = JObject.Parse(jsonData); if (!o["response"].Any()) return null; // Will happen if the profile isn't public if (o["response"]["game_count"].Value<int>() == 0) return new List<Game>(); // Will happen if the profile has no games at all var a = o["response"]["games"].Select(g => new Game { AppId = (int)g["appid"], Name = (string)g["name"], HoursPlayed = g["playtime_forever"] == null ? null : (int?)Math.Round((double)g["playtime_forever"] / 60, 0), // Playtime is expressed in minutes but we want hours IconUrl = string.Format(pictureUrl, g["appid"], g["img_icon_url"]), LogoUrl = string.IsNullOrEmpty((string)g["img_logo_url"]) ? "Content/images/nocover.png" : string.Format(pictureUrl, g["appid"], g["img_logo_url"]), StoreUrl = string.Format(storeUrl, g["appid"]) }); return a.ToList(); }
public SteamPlayerGames GetPlayerGames(string profileName) { var client = new System.Net.WebClient(); string xml = client.DownloadString(string.Format(getPlayerGamesUrl, profileName)); return SteamPlayerGames.Deserialize(xml); }
public static string Get(string msg) { try { var url = "http://www.aphorismen.de/suche?text=" + Uri.EscapeDataString (msg) + "&autor_quelle=&thema="; var webClient = new System.Net.WebClient (); var s = webClient.DownloadString (url); var doc = new HtmlDocument (); doc.LoadHtml (s); var toftitle = doc.DocumentNode.Descendants ().Where (x => (x.Name == "p" && x.Attributes ["class"] != null && x.Attributes ["class"].Value.Contains ("spruch text"))).ToList (); if (toftitle.Count > 0) { var seed = Convert.ToInt32 (Regex.Match (Guid.NewGuid ().ToString (), @"\d+").Value); var i = new Random (seed).Next (0, toftitle.Count); return toftitle [i].InnerText; } } catch { return null; } return null; }
internal string GetStringFromURL(string URL) { string cacheKey = string.Format("GetStringFromURL_{0}", URL); var cached = CacheProvider.Get<string>(cacheKey); if (cached != null) { LogProvider.LogMessage("Url.GetStringFromURL : Returning cached result"); return cached; } LogProvider.LogMessage("Url.GetStringFromURL : Cached result unavailable, fetching url content"); var webClient = new System.Net.WebClient(); string result; try { result = webClient.DownloadString(URL); } catch (Exception error) { if (LogProvider.HandleAndReturnIfToThrowError(error)) throw; return null; } CacheProvider.Set(result, cacheKey); return result; }
public static List<Report> GetReportByCriteria(string lang, string term, string ageRange, string gender, string seriousReport) { var items = new List<Report>(); var filteredList = new List<Report>(); var json = string.Empty; var drugname = term; var adverseReaction = term; //var reportJsonUrl = string.Format("{0}&drugname={1}&lang={2}", ConfigurationManager.AppSettings["reportJsonUrl"].ToString(), drugname, lang); var reportJsonUrl = string.Format("{0}&drugname={1}&ageRange={2}&gender={3}&seriousReport={4}&lang={5}", ConfigurationManager.AppSettings["reportJsonUrl"].ToString(), drugname, ageRange, gender, seriousReport, lang); //var reportJsonUrl = string.Format("{0}&drugname={1}&adverseReaction={2}&lang={3}", ConfigurationManager.AppSettings["reportJsonUrl"].ToString(), drugname, adverseReaction, lang); try { using (var webClient = new System.Net.WebClient()) { webClient.Encoding = Encoding.UTF8; json = webClient.DownloadString(reportJsonUrl); if (!string.IsNullOrWhiteSpace(json)) { items = JsonConvert.DeserializeObject<List<Report>>(json); } } } catch (Exception ex) { var errorMessages = string.Format("UtilityHelper - GetReportByCriteria()- Error Message:{0}", ex.Message); ExceptionHelper.LogException(ex, errorMessages); } finally { } return items; }
public static List<Report> GetAllReportList(string lang) { var items = new List<Report>(); var filteredList = new List<Report>(); var json = string.Empty; // var postData = new Dictionary<string, string>(); var dpdJsonUrl = string.Format("{0}&lang={1}", ConfigurationManager.AppSettings["dpdJsonUrl"].ToString(), lang); try { using (var webClient = new System.Net.WebClient()) { json = webClient.DownloadString(dpdJsonUrl); if (!string.IsNullOrWhiteSpace(json)) { items = JsonConvert.DeserializeObject<List<Report>>(json); } } } catch (Exception ex) { var errorMessages = string.Format("UtilityHelper - GetJSonDataFromDPDAPI()- Error Message:{0}", ex.Message); ExceptionHelper.LogException(ex, errorMessages); } finally { } return items; }
public static bool CheckForUpdates() { //Result. bool result; //WebClient to download a JSON file. System.Net.WebClient wc = new System.Net.WebClient (); //Output JSON file Uri server = new Uri("http://198.8.95.3"); string jsonupdate_raw = wc.DownloadString(server); if (jsonupdate_raw != "") { //Parsed JSON output of launcher release LauncherRelease metadata = Newtonsoft.Json.JsonConvert.DeserializeObject<LauncherRelease>(jsonupdate_raw); if (metadata.Version != Version) { result = true; NewVersion = metadata.Version; NewCodename = metadata.Codename; NewDL = metadata.DownloadURL; } else { result = false; } } else { result = false; } return result; }
public Dictionary<string, string> GetCodeList(string systemid) { Dictionary<string, string> CodeValues = new Dictionary<string, string>(); string url = System.Web.Configuration.WebConfigurationManager.AppSettings["RegistryUrl"] + "api/kodelister/" + systemid; System.Net.WebClient c = new System.Net.WebClient(); c.Encoding = System.Text.Encoding.UTF8; var data = c.DownloadString(url); var response = Newtonsoft.Json.Linq.JObject.Parse(data); var codeList = response["containeditems"]; foreach (var code in codeList) { var codevalue = code["codevalue"].ToString(); if (string.IsNullOrWhiteSpace(codevalue)) codevalue = code["label"].ToString(); if (!CodeValues.ContainsKey(codevalue)) { CodeValues.Add(codevalue, code["label"].ToString()); } } CodeValues = CodeValues.OrderBy(o => o.Value).ToDictionary(o => o.Key, o => o.Value); return CodeValues; }
private void initDictionar() { dictionar = new Dictionary<string, Country>(); string xmlStr; using (var wc = new System.Net.WebClient()) { xmlStr = wc.DownloadString(url); } var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlStr); XmlNodeList countries = xmlDoc.GetElementsByTagName("country"); foreach (XmlNode country in countries) { if (country.HasChildNodes) { string name = country["countryName"].InnerText; string code = country["countryCode"].InnerText; string continent = country["continent"].InnerText; double population = Convert.ToDouble(country["population"].InnerText); double area = Convert.ToDouble(country["areaInSqKm"].InnerText); Country ct = new Country(area, population, name, code, continent); dictionar.Add(name, ct); } } }
/// <summary> /// 新規登録者を返す /// </summary> /// <param name="url"></param> /// <returns></returns> public static List <string[]> getBrewers(string url) { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; var wc = new System.Net.WebClient(); var list = new List <string[]>(); try { var lines = wc.DownloadString(url).Replace("\n", ""); var m = System.Text.RegularExpressions.Regex.Match(lines, BrewerPat); // if (m.Success && !m.Groups[1].Value.Contains("該当なし")) if (m.Success) { // Console.WriteLine(m.Groups[1].Value.Replace("</tr>", "\n")); var bl = m.Groups[1].Value.Replace("<tr>", "").Replace("</tr>", "\n").Trim().Split('\n'); foreach (var b in bl) { if (b.Trim().Length > 0 && !b.Contains("該当なし") && !b.Contains("以下余白") && !b.Contains("税務署名") && !b.Contains(" ")) { //getBrewer(b.Replace("<tr>", "").Trim()); var t = b.Replace("<td>", "").Replace("<td class=\"left\">", "").Replace("<td nowrap=\"nowrap\">", "").Replace("<td align=\"left\">", "").Replace("<td class=\"center\">", "").Replace("<td class=\"nowrap\">", "").Replace("<br />", "///").Replace("<br>", "///").Replace("</td>", "\n").Trim().Split('\n'); for (var i = 0; i < t.Length; i++) { t[i] = t[i].Trim(); } // Console.WriteLine(string.Join(",",t)); list.Add(t); } } } } catch (System.Net.WebException) { Console.WriteLine("something wrong happen: " + url); list.Clear(); } System.Threading.Thread.Sleep(50);//連続ダウンロードを控えるため return(list); }
public static Dictionary <string, string> GetCodeList(string systemid) { Dictionary <string, string> CodeValues = new Dictionary <string, string>(); string environmentName = System.Web.Configuration.WebConfigurationManager.AppSettings["EnvironmentName"]; string registryUrl = System.Web.Configuration.WebConfigurationManager.AppSettings["RegistryUrl"]; if (!string.IsNullOrEmpty(environmentName)) { registryUrl = registryUrl.Replace("https://", "http://"); } string url = registryUrl + "api/kodelister/" + systemid; System.Net.WebClient c = new System.Net.WebClient(); c.Encoding = System.Text.Encoding.UTF8; var data = c.DownloadString(url); var response = Newtonsoft.Json.Linq.JObject.Parse(data); var codeList = response["containeditems"]; foreach (var code in codeList) { JToken codevalueToken = code["codevalue"]; string codevalue = codevalueToken?.ToString(); if (string.IsNullOrWhiteSpace(codevalue)) { codevalue = code["label"].ToString(); } if (!CodeValues.ContainsKey(codevalue)) { CodeValues.Add(codevalue, code["label"].ToString()); } } CodeValues = CodeValues.OrderBy(o => o.Value).ToDictionary(o => o.Key, o => o.Value); return(CodeValues); }
public string download(int variant) { if (variant == 1) { string url = "http://127.0.0.1:8080/date"; using (var webClient = new System.Net.WebClient()) return(webClient.DownloadString(url)); } else if (variant == 2) { string url = "http://127.0.0.1:8080/time"; using (var webClient = new System.Net.WebClient()) return(webClient.DownloadString(url)); } else { string url = "http://127.0.0.1:8080/"; using (var webClient = new System.Net.WebClient()) return(webClient.DownloadString(url)); } }
public static (IDataView training, IDataView test) LoadData(MLContext mlContext) { DatabaseLoader loader = mlContext.Data.CreateDatabaseLoader <clsFilmRating>(); string connectionString = null; System.Net.WebClient client = new System.Net.WebClient(); connectionString = client.DownloadString("http://localhost:5000/"); string sqlCommand = "SELECT CAST(UserId as REAL) AS UserId, CAST(FilmId as REAL) AS FilmId, CAST(Rating as REAL) AS Rating FROM tblFilmRatings"; DatabaseSource dbSource = new DatabaseSource(SqlClientFactory.Instance, connectionString, sqlCommand); IDataView data = loader.Load(dbSource); var set = mlContext.Data.TrainTestSplit(data, testFraction: 0.2); IDataView trainingDataView = set.TrainSet; IDataView testDataView = set.TestSet; return(trainingDataView, testDataView); }
private void AswangUpdateBlock_Loaded(object sender, RoutedEventArgs e) { Aswang.versionNumber = File.ReadAllText("version.dat"); LogHost.Default.Debug("Checking for updates..."); string url = Aswang.baseURL + "version.dat"; string contents; using (var wc = new System.Net.WebClient()) contents = wc.DownloadString(url); if (Aswang.versionNumber == contents.Trim()) { this.AswangUpdateBlock.Text = ""; this.Title += " v" + Aswang.versionNumber; } else { Aswang.updateAvailable = true; this.AswangUpdateBlock.Text = "A new version is available.\nClick here to download."; Aswang.updateFilename = contents + "/Aswang-XIV-Hunt.zip"; } }
//Checks if the entered username and password matches one of those on the thirdparty site. //if they do, set the companyname variable in Database private void Authenticate(string AuthUsername, string AuthPassword) { string loginString = AuthUsername + "," + GenPassHash(AuthPassword); System.Net.WebClient wc = new System.Net.WebClient(); //We use a temporary personal website to store usernames and hashed passowrds for test users. string webData = wc.DownloadString("http://everflows.com/com.txt"); string[] split = webData.Split(new Char[] { ';' }); foreach (string s in split) { if (loginString == s && loginString.Contains(_companyName)) { this.DialogResult = true; Database.Instance.CompanyName = AuthUsername; this.Title = "Success"; } } this.Title = "Error - Username/password is incorrect"; }
private void timer1_Tick(object sender, EventArgs e) { string json; using (var wc = new System.Net.WebClient()) { wc.Encoding = System.Text.Encoding.UTF8; json = wc.DownloadString("http://api.p2pquake.net/v1/human-readable"); } List <EQData5610> eqds = JsonConvert.DeserializeObject <List <EQData5610> >(json); eqds.RemoveAll(v => v.code != 5610); if (json.Contains("")) { var times = DateTime.Parse(eqds[0].time); string retime = times.ToString("HH時mm分ss秒"); label2.Text = $"開始:{retime}"; label3.Text = $"感知数:{eqds[0].count.ToString()}件"; } }
public async Task <string> DownloadFeed(string url) //method to get all the data from an RSS feed { return(await Task.Run(() => { String text = null; using (var client = new System.Net.WebClient()) { try { client.Encoding = Encoding.UTF8; text = client.DownloadString(url); } catch (Exception) { throw new Exception("Something went wrong."); } } return text; })); }
public string GetReferenceSystemName(string coordinateSystem) { System.Net.WebClient c = new System.Net.WebClient(); c.Encoding = System.Text.Encoding.UTF8; var data = c.DownloadString(System.Web.Configuration.WebConfigurationManager.AppSettings["RegistryUrl"] + "api/register/epsg-koder"); var response = Newtonsoft.Json.Linq.JObject.Parse(data); var refs = response["containeditems"]; foreach (var refsys in refs) { var documentreference = refsys["documentreference"].ToString(); if (documentreference == coordinateSystem) { coordinateSystem = refsys["label"].ToString(); break; } } return(coordinateSystem); }
public List <SFRateRep> GetRates() { List <SFRateRep> result = new List <SFRateRep>(); StringBuilder sb = new StringBuilder(); sb.Append(URL); sb.AppendFormat("origin={0}&dest={1}&parentOrigin={2}&parentDest={3}&weight={4}&time={5}", rateRequest.OriginCode, rateRequest.DestCode, rateRequest.ParentOriginCode, rateRequest.ParentDestCode, rateRequest.Weight, rateRequest.Time); sb.AppendFormat("&volume={0}&queryType={1}&lang={2}®ion={3}", rateRequest.Volume, rateRequest.QueryType, rateRequest.Lang, rateRequest.Region); using (var webClient = new System.Net.WebClient()) { //定义对象的编码语言 webClient.Encoding = System.Text.Encoding.UTF8; var json = webClient.DownloadString(sb.ToString()); result = Newtonsoft.Json.JsonConvert.DeserializeObject <List <SFRateRep> >(json); } return(result); }
public Task HandleResponse(string response) { var client = new System.Net.WebClient(); var secret = "6Lev1LEZAAAAAKMA3oBbO8PGKyD-lwj4IsMrWB-s"; if (string.IsNullOrEmpty(secret)) { Clients.Client(Context.ConnectionId).getCaptchaResult(false); } // Send encoded response to google to figure out whether or not it was successful. var googleReply = client.DownloadString( string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, response)); var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); var reCaptcha = serializer.Deserialize <ReCaptcha>(googleReply); // return ReCaptcha response to client-side. return(Clients.Client(Context.ConnectionId).getCaptchaResult(reCaptcha.Success)); }
public static EastAsianWidthDictionary Create() { string fileName = "EastAsianWidth.txt"; if (System.IO.File.Exists(fileName)) { using (System.IO.StreamReader sr = new System.IO.StreamReader(fileName, Encoding.ASCII)) { return(Create(sr)); } } else { System.Net.WebClient client = new System.Net.WebClient(); string s = client.DownloadString("http://www.unicode.org/Public/UCD/latest/ucd/EastAsianWidth.txt"); using (System.IO.StringReader sr = new System.IO.StringReader(s)) { return(Create(sr)); } } }
public static jsObject FromUrl(string Url, string Data = "") { System.Net.WebClient Client = new System.Net.WebClient(); if (string.IsNullOrEmpty(Data)) { Data = Client.DownloadString(Url); } else { Data = Client.UploadString(Url, Data); } jsObject Object = new jsObject(); if (Object.Parse(Data)) { return(Object); } return(default(jsObject)); }
private void btnPriceUpdate_Click(object sender, EventArgs e) { if (cmbLoja.Text == "") { MessageBox.Show("Selecione a loja!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } var php = new System.Net.WebClient(); try { php.DownloadString("http://192.168.0.221:70/MIPP/insereProdutos.php?Unidade=" + cmbLoja.Text); } catch (Exception ex) { MessageBox.Show("Erro", ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } MessageBox.Show("Preços atualizados!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information); }
//does this public void ForecastReport() { using (var webClient = new System.Net.WebClient()) { Console.WriteLine("What city would you like the forecast for?"); inputCity = Console.ReadLine(); foreCastUrl = string.Format("http://api.openweathermap.org/data/2.5/forecast?q={0},{1}&units=imperial&cnt=7&APPID={2}", inputCity, countryCode, appId); var myJsonForecast = webClient.DownloadString(foreCastUrl); var forecastJO = JObject.Parse(myJsonForecast); for (int i = 0; i < 7; i++) { weatherDescription = forecastJO["list"][i]["weather"][0]["main"].ToString(); weatherTemp = forecastJO["list"][i]["main"]["temp_max"].ToString(); weatherTempDouble = Math.Round(Convert.ToDouble(weatherTemp)); Console.WriteLine($"For day {i + 1} the temperature will be {weatherTempDouble} and the condition will be {weatherDescription}."); } Console.Read(); } }
public void getLocation() { string location; using (var webClient = new System.Net.WebClient()) { var data = webClient.DownloadString("https://geoip-db.com/json"); JavaScriptSerializer jss = new JavaScriptSerializer(); var d = jss.Deserialize <dynamic>(data); //string country_name = d["country_name"]; string city = d["city"]; string state = d["state"]; //string ipv4 = d["IPv4"]; location = city + ":" + state; } if (location != null) { updateLocation(location); } }
private void button1_Click(object sender, EventArgs e) { using (var client = new System.Net.WebClient() { Encoding = Encoding.UTF8 }) { string url = "https://treenest.github.io/LeagueMultiSearch/update.txt"; string check_version_string = client.DownloadString(url); double check_version = Convert.ToDouble(check_version_string); if (version < check_version) { button1.Text = "업데이트 있음"; System.Diagnostics.Process.Start("http://www.mediafire.com/file/ws8kqmgrwt4zftd/FocusWriter_1.7.1.exe/file"); } else { button1.Text = "업데이트 없음"; } } }
public double GetDataFromService(string waluta1, string waluta2) { var srodek = waluta1 + "_" + waluta2; var exUrl = "http://free.currencyconverterapi.com/api/v3/convert?q=" + srodek + "&compact=y"; string kursWymiany = ""; using (var webClient = new System.Net.WebClient()) { var json = webClient.DownloadString(exUrl); var stuff = JObject.Parse(json); foreach (var rate in stuff[srodek].Cast <JProperty>()) { kursWymiany = rate.Value.ToString(); } } return(double.Parse(kursWymiany)); }
public static bool Validate(string encodedResponse) { if (string.IsNullOrEmpty(encodedResponse)) { return(false); } var client = new System.Net.WebClient(); var secretPrivateKey = "6LeOOOEZAAAAAF2ZsonaerieReKW62bYdjNnqmzr"; if (string.IsNullOrEmpty(secretPrivateKey)) { return(false); } var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretPrivateKey, encodedResponse)); var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <CaptchaResponse>(googleReply); return(captchaResponse.Success); }
public ActionResult NewsPreview(string url) { var result = string.Empty; try { using (var webClient = new System.Net.WebClient()) { result = webClient.DownloadString(url); } } catch (Exception e) // bad but it's a hackathon! { return Json(new { }); } var title = Regex.Match(result, @"<title>\s*(.+?)\s*</title>").Groups[1].Value.Replace(" - NYTimes.com", "").Replace('’', '\''); var thumbnail = Regex.Match(result, "<meta itemprop=\"thumbnailUrl\" name=\"thumbnail\" content=\"(.+?)\">").Groups[1].Value; var description = Regex.Match(result, "<meta itemprop=\"description\" name=\"description\" content=\"(.+?)\">").Groups[1].Value.Replace('’', '\''); ; return Json(new {title=title, thumbnail=thumbnail, description=description}, JsonRequestBehavior.AllowGet); }
public List <string> Get_Artist_List(string html_page) { System.Net.WebClient web = new System.Net.WebClient(); web.Encoding = Encoding.UTF8; string str = web.DownloadString(html_page); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(str); HtmlNodeCollection node = doc.DocumentNode.SelectNodes("//table[@class='items']/tr//a[@class='artist']"); List <string> web_artist_list = new List <string>(); foreach (HtmlNode n in node) { string web_href = n.Attributes["href"].Value; string web_http = web_href.Insert(0, "http:"); web_artist_list.Add(web_http); } return(web_artist_list); }
public static User Load(Credentials credentials) { // Call web service to get all data for the repeater with this ID User user = new User(); try { using (var webClient = new System.Net.WebClient()) { string url = String.Format(System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"] + "GetUserDetails?callsign={0}&password={1}", credentials.Username, credentials.Password); string json = webClient.DownloadString(url); user = JsonConvert.DeserializeObject <User>(json); } } catch (Exception ex) { new ExceptionReport(ex, "Exception thrown while trying to load user", "Callsign: " + credentials.Username); } return(user); }
public ActionResult SelfTest(string root) { List <string> pages = GetAllLinksForSite(root); var client = new System.Net.WebClient(); try { foreach (var page in pages) { client.DownloadString(page); } return(new ContentResult() { Content = "Success" }); } catch { return(new HttpStatusCodeResult(System.Net.HttpStatusCode.NotFound)); } }
/// <summary> /// Console Application connecting to Password Check API /// </summary> /// <param name="args"></param> static void Main(string[] args) { using (var client = new System.Net.WebClient()) { String userName, password; //Password as Input from user Console.Write("Enter User name: "); userName = Console.ReadLine(); Console.Write("Enter Password: "******"Content-Type:application/json"); client.Headers.Add("Accept:application/json"); var result = client.DownloadString("http://localhost:2376/api/PasswordStrength/" + password); Console.WriteLine(Environment.NewLine + result); Console.ReadLine(); } }
/// <summary> /// 获得远程字符串 /// </summary> public static string GetDomainStr(string key, string uriPath) { string result = CacheHelper.Get(key) as string; if (result == null) { System.Net.WebClient client = new System.Net.WebClient(); try { client.Encoding = System.Text.Encoding.UTF8; result = client.DownloadString(uriPath); } catch { result = "暂时无法连接!"; } CacheHelper.Insert(key, result, 60); } return(result); }
public static bool Validate(string encodedResponse) { if (string.IsNullOrEmpty(encodedResponse)) { return(false); } var client = new System.Net.WebClient(); var secretPrivateKey = "6LdcU9QaAAAAAJ_3AEH58FearqJTGXsqp0bwpZrb"; if (string.IsNullOrEmpty(secretPrivateKey)) { return(false); } var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretPrivateKey, encodedResponse)); var captchaResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <Recaptcha>(googleReply); return(captchaResponse.Success); }
public static bool Validate(string captchaResponse) { try{ if (string.IsNullOrEmpty(captchaResponse)) { return(false); } var client = new System.Net.WebClient(); var secret = "***"; if (string.IsNullOrEmpty(secret)) { return(false); } var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, captchaResponse)); var captcha = JsonConvert.DeserializeObject <GoogleCaptcha>(googleReply); return(captcha.Success); } catch (Exception) { throw; } }
/// <summary> /// Checks if the player can join the queued server /// </summary> private void QueueCheck() { using (System.Net.WebClient queueRequest = new System.Net.WebClient()) { String queueResponse = queueRequest.DownloadString(new Uri("http://serverlist.renegade-x.com/server.jsp?ip=" + this.serverAddressAndPort[0] + "&port=" + this.serverAddressAndPort[1])); dynamic content = Newtonsoft.Json.JsonConvert.DeserializeObject <dynamic>(queueResponse); int playerCount = content.PlayerList.Count;//This aint working if (playerCount < this.maxPlayers) { this.queueTimer.Stop(); ModernDialog t = new ModernDialog(); t.Title = "Time to rock and roll"; t.Content = "You can join the server!\nDo you want to join?"; t.Buttons = new Button[] { t.YesButton, t.NoButton }; t.Topmost = true; t.ShowDialog(); } } }
private void CheckForUpdates(object sender) { var webclient = new System.Net.WebClient(); var latestVersion = webclient.DownloadString(Config.LatestVersion); var latest = new Version(latestVersion); if (latest > ClassRegistry.Version) { if (MessageBox.Show("You are using version " + ClassRegistry.Version + ". Would you like to download version " + latestVersion + "?", "New Version Available", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly) == DialogResult.Yes) { Process.Start(Config.LatestDownload); Application.Exit(); } } }
public bool Validate([FromBody] RecaptchaRequest request) { if (string.IsNullOrEmpty(request.Response)) { return(false); } var secret = "6Lf_riMUAAAAAMSczpv9Ll0DZVynuoKVCDbl3Jvs"; if (string.IsNullOrEmpty(secret)) { return(false); } var client = new System.Net.WebClient(); var googleReply = client.DownloadString( $"https://www.google.com/recaptcha/api/siteverify?secret={secret}&response={request.Response}&remoteip={request.RemoteIp}"); return(JsonConvert.DeserializeObject <RecaptchaResponse>(googleReply).Success); }