private void SendScore(String type, Int32 count) { var ds = _DS; var cfg = Setting.Current; var nvs = new Dictionary <String, Object>(); nvs[nameof(type)] = type; nvs["score"] = ds.Score; //nvs["name"] = "{0}/{1}".F(Environment.UserName, Environment.MachineName); nvs["name"] = cfg.Name; nvs["OS"] = Runtime.OSName; using (var reg = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0")) { nvs["Processor"] = (reg.GetValue("ProcessorNameString") + "").Trim(); nvs["Frequency"] = reg.GetValue("~MHz").ToInt() + ""; } nvs["Memory"] = Runtime.PhysicalMemory; nvs["Config"] = new { count, ds.Threads, ds.BatchSize, ds.UseSql }.ToJson(); XTrace.WriteLine(nvs.ToJson(true)); var url = Setting.Current.Address.EnsureEnd("/add"); var client = new WebClientX(true, true); client.Log = XTrace.Log; client.UploadJsonAsync(url, nvs); }
/// <summary> /// /// </summary> /// <param name="stockCode"></param> /// <param name="start"></param> /// <param name="end"></param> /// <param name="type">cn为股票,zs为指数</param> public static void GetHistoryFromWeb(string stockCode, DateTime start, DateTime end, string type = "cn") { string url = @"http://q.stock.sohu.com/hisHq?code={3}_{0}&start={1}&end={2}".F(stockCode, start.ToString("yyyyMMdd"), end.ToString("yyyyMMdd"), type); WebClientX client = new WebClientX(); client.Timeout = 1000 * 120; var text = client.GetHtml(url); var doc = new HtmlDocument(); doc.LoadHtml(text); var value = doc.DocumentNode.InnerText; var et = new StockHisText() { Code = stockCode, Start = start, End = end, HisText = value }; try { if (type == "zs") { et.Code = "{0}_{1}".F("Index", et.Code); //加前缀区分 } et.Insert(); } catch (Exception err) { XTrace.WriteException(err); } }
static Ip() { var dir = Runtime.IsWeb ? "..\\Data" : "."; var ip = dir.CombinePath("ip.gz").GetFullPath(); if (File.Exists(ip)) { DbFile = ip; } // 如果本地没有IP数据库,则从网络下载 if (DbFile.IsNullOrWhiteSpace()) { Task.Factory.StartNew(() => { var url = Setting.Current.PluginServer; XTrace.WriteLine("没有找到IP数据库{0},准备联网获取 {1}", ip, url); var client = new WebClientX { Log = XTrace.Log }; var file = client.DownloadLink(url, "ip.gz", dir.GetFullPath()); if (File.Exists(file)) { DbFile = file.GetFullPath(); zip = null; // 让它重新初始化 _inited = null; } }, TaskCreationOptions.LongRunning).LogException(); } }
/// <summary>异步获取字符串</summary> /// <param name="url"></param> /// <returns></returns> public virtual async Task <String> GetStringAsync(String url) { if (AppKey.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(AppKey)); } if (_Client == null) { _Client = new WebClientX { Log = Log } } ; if (url.Contains("?")) { url += "&"; } else { url += "?"; } url += KeyName + "=" + AppKey; return(await _Client.DownloadStringAsync(url)); }
static void Test1() { Console.WriteLine(Runtime.OSName); var os = Environment.OSVersion; Console.WriteLine(os); var wc = new WebClientX(true, true); var html = wc.DownloadString("http://www.newlifex.com/showtopic-1433.aspx"); if (!html.IsNullOrEmpty()) { var txt = html.Substring("<div id=\"firstpost\">", "</div>"); txt = txt.Substring("<b>", "<pre>"); txt = txt.Replace("<br/>", Environment.NewLine) .Replace("<font color=\"Red\">", null) .Replace("<font color=\"Green\">", null) .Replace("<font color=\"Blue\">", null) .Replace("</font>", null) .Replace("<b>", null) .Replace("</b>", null); Console.WriteLine(txt); txt.SpeakAsync(); } }
/// <summary> /// 手动销毁当前项 /// </summary> public void Destroyed() { try { if (timDownSpeedTask != null) { //主时钟,倒计时,移除下载事件 timDownSpeedTask.Stop(); timDownSpeedTask.Enabled = false; timDownSpeedTask.Tick -= timDownSpeedTask_Tick; timDownSpeedTask = null; } if (webcDownloading != null) { //移除下载进度改变事件 webcDownloading.DownloadProgressChanged -= DownloadProgressChanged; webcDownloading.DownloadFileCompleted -= DownloadFileCompleted; } if (webcDownloading != null) { webcDownloading.Dispose(); webcDownloading = null; } bolItemDestroyed = true; } catch (Exception ex) { } }
static void Test4() { var str = "~/Sso/Login"; var uri2 = new Uri("Sso/Login", UriKind.Absolute); //var uri = str.AsUri("http://xxx.yyy.zzz/ss/dd/ff".AsUri()); var uri = str.AsUri(); //var cfg = CacheConfig.Current; //Console.WriteLine(cfg.GetOrAdd("Bill01")); //var set = cfg.GetOrAdd("aa_test", "redis"); //Console.WriteLine(set); WebClientX.SetAllowUnsafeHeaderParsing(true); var url = "https://api.github.com/user?access_token=ccb5c1363318ee2fa1d9374e87961bdf01a4c682"; var client = new WebClientX(true, true); //var buf = client.DownloadDataAsync(url).Result; //var ms = new MemoryStream(buf); //var ms2 = ms.DecompressGZip(); //buf = ms2.ReadBytes(); var html = client.GetHtml(url); Console.WriteLine(html); var ip = "223.5.5.5"; ip = ip.IPToAddress(); Console.WriteLine(ip); }
static Ip() { var dir = Runtime.IsWeb ? "..\\Data" : "Data"; var ip = dir.CombinePath("ip.gz").GetFullPath(); if (File.Exists(ip)) { DbFile = ip; } // 如果本地没有IP数据库,则从网络下载 if (DbFile.IsNullOrWhiteSpace()) { ThreadPoolX.QueueUserWorkItem(() => { var url = Setting.Current.PluginServer; XTrace.WriteLine("没有找到IP数据库{0},准备联网获取 {1}", ip, url); var client = new WebClientX { Log = XTrace.Log }; var file = client.DownloadLink(url, "ip.gz", dir.GetFullPath()); if (File.Exists(file)) { DbFile = file.GetFullPath(); zip = null; // 让它重新初始化 _inited = null; } }); } }
static void CheckContent() { // 释放ico图标 var ico = "favicon.ico"; var wwwroot = Setting.Current.WebRootPath; var ico2 = wwwroot.CombinePath(ico).GetFullPath(); if (!File.Exists(ico2)) { var asm = Assembly.GetExecutingAssembly(); var ns = asm.GetManifestResourceNames(); var f = ns.FirstOrDefault(e => e.EndsWithIgnoreCase(ico)); if (!f.IsNullOrEmpty()) { XTrace.WriteLine("释放图标{0}到{1}", f, ico2); var ms = asm.GetManifestResourceStream(f); File.WriteAllBytes(ico2.EnsureDirectory(true), ms.ReadBytes()); } } // 检查魔方样式 var content = Setting.Current.WebRootPath.CombinePath("Content"); var js = content.CombinePath("Cube.js").GetFullPath(); var css = content.CombinePath("Cube.css").GetFullPath(); if (File.Exists(js) && File.Exists(css)) { // 判断脚本时间 var dt = DateTime.MinValue; var ss = File.ReadAllLines(js); for (var i = 0; i < 5; i++) { if (DateTime.TryParse(ss[i].TrimStart("//").Trim(), out dt)) { break; } } // 要求脚本最小更新时间 if (dt >= "2020-02-04 00:00:00".ToDateTime()) { return; } } var url = Setting.Current.PluginServer; if (url.IsNullOrEmpty()) { return; } var wc = new WebClientX() { Log = XTrace.Log }; wc.DownloadLinkAndExtract(url, "Cube_Content", content, true); }
static void CheckContent() { // 释放ico图标 var ico = "favicon.ico"; var ico2 = ico.GetFullPath(); if (!File.Exists(ico2)) { // 延迟时间释放,给子系统覆盖的机会 TimerX.Delay(s => { if (!File.Exists(ico2)) { Assembly.GetExecutingAssembly().ReleaseFile(ico, ico2); } }, 15000); } // 检查魔方样式 var js = "~/Content/Cube.js".GetFullPath(); var css = "~/Content/Cube.css".GetFullPath(); if (File.Exists(js) && File.Exists(css)) { // 判断脚本时间 var dt = DateTime.MinValue; var ss = File.ReadAllLines(js); for (var i = 0; i < 5; i++) { if (DateTime.TryParse(ss[i].TrimStart("//").Trim(), out dt)) { break; } } // 要求脚本最小更新时间 if (dt >= "2017-12-07 00:00:00".ToDateTime()) { return; } } var url = Setting.Current.PluginServer; if (url.IsNullOrEmpty()) { return; } var wc = new WebClientX(true, true) { Log = XTrace.Log }; wc.DownloadLinkAndExtract(url, "Cube_Content", "~/Content".GetFullPath(), true); }
public static HtmlDocument GetHtmlByUrl(this string url) { WebClientX client = new WebClientX(); client.Timeout = 1000 * 120; var text = client.GetHtml(url); var doc = new HtmlDocument(); doc.LoadHtml(text); return(doc); }
private WebClientX CreateClient() { if (_Client != null) { return(_Client); } var web = new WebClientX(); return(_Client = web); }
/// <summary>创建客户端</summary> /// <param name="url">路径</param> /// <returns></returns> protected override String Request(String url) { if (_Client == null) { // 允许宽松头部 WebClientX.SetAllowUnsafeHeaderParsing(true); // 必须指定中文编码 _Client = new WebClientX(true, true); } return(LastHtml = _Client.GetHtml(url)); }
private WebClientX CreateClient() { if (_Client != null) { return(_Client); } var web = new WebClientX(true, true); web.UserAgent = "NewLife.Upgrade"; return(_Client = web); }
private WebClientX CreateClient() { if (_Client != null) { return(_Client); } var web = new WebClientX(true, true) { UserAgent = "Ding.Upgrade" }; return(_Client = web); }
public Boolean Init(Object config) { var url = config as String; if (url.IsNullOrEmpty()) { return(false); } Client = new WebClientX(); Remote = url; return(true); }
/// <summary>抓取远程头像</summary> /// <param name="user"></param> /// <returns></returns> public virtual Boolean FetchAvatar(IManageUser user) { var av = user.GetValue("Avatar") as String; if (av.IsNullOrEmpty()) { throw new Exception("用户头像不存在 " + user); } var url = av; if (!url.StartsWithIgnoreCase("http")) { return(false); } // 不要扩展名 var set = Setting.Current; av = set.AvatarPath.CombinePath(user.ID + "").GetFullPath(); // 头像是否已存在 if (File.Exists(av)) { return(false); } av.EnsureDirectory(true); try { var wc = new WebClientX(true, true); Task.Factory.StartNew(() => wc.DownloadFileAsync(url, av)).Wait(5000); //// 更新头像 //user.SetValue("Avatar", "/Sso/Avatar/" + user.ID); return(true); } catch (Exception ex) { XTrace.WriteException(ex); } return(false); }
static Ip() { var dir = Runtime.IsWeb ? "..\\Data" : "."; var ip = dir.CombinePath("ip.gz"); if (File.Exists(ip)) { DbFile = ip; } // 删除旧版本 ip = "App_Data\\ip.gz".GetFullPath(); if (File.Exists(ip)) { File.Delete(ip); var di = "App_Data".AsDirectory(); if (di.GetFiles().Length == 0) { di.Delete(true); } } // 如果本地没有IP数据库,则从网络下载 if (DbFile.IsNullOrWhiteSpace()) { Task.Factory.StartNew(() => { var url = Setting.Current.PluginServer; XTrace.WriteLine("没有找到IP数据库,准备联网获取 {0}", url); var client = new WebClientX(); client.Log = XTrace.Log; var file = client.DownloadLink(url, "ip.gz", dir.GetFullPath()); if (File.Exists(file)) { DbFile = file.GetFullPath(); zip = null; // 让它重新初始化 _inited = null; } }, TaskCreationOptions.LongRunning).LogException(); } }
static void Main(string[] args) { string uriString = "http://www.remotesite.com/login.cfm"; // Create a new WebClient instance. WebClientX myWebClient = new WebClientX(); // Create a new NameValueCollection instance to hold some custom parameters to be posted to the URL. NameValueCollection myNameValueCollection = new NameValueCollection(); // Add necessary parameter/value pairs to the name/value container. myNameValueCollection.Add("userid", "myname"); myNameValueCollection.Add("mypassword", "mypassword"); Console.WriteLine("\nUploading to {0} ...", uriString); // 'The Upload(String,NameValueCollection)' implicitly method sets HTTP POST as the request method. byte[] responseArray = myWebClient.UploadValues(uriString, myNameValueCollection); // Decode and display the response. Console.WriteLine("\nResponse received was :\n{0}", Encoding.ASCII.GetString(responseArray)); Console.WriteLine("\n\n\n pausing..."); Console.ReadKey(); // Go to 2nd page on the site to get additional data Stream myStream = myWebClient.OpenRead("https://www.remotesite.com/status_results.cfm?t=8&prog=d"); Console.WriteLine("\nDisplaying Data :\n"); StreamReader sr = new StreamReader(myStream); StringBuilder sb = new StringBuilder(); using (StreamReader reader = new StreamReader(myStream, System.Text.Encoding.UTF8)) { string line; while ((line = reader.ReadLine()) != null) { sb.Append(line + "\r\n"); } } using (StreamWriter outfile = new StreamWriter(@"Logfile1.txt")) { outfile.Write(sb.ToString()); } Console.WriteLine(sb.ToString()); Console.WriteLine("\n\n\n pausing..."); Console.ReadKey(); }
static void Test1() { //new AgentService().Main(); var wc = new WebClientX { Log = XTrace.Log }; var url = wc.DownloadLink("http://x.newlifex.com/", "Oracle.ManagedDataAccess.st", "."); XTrace.WriteLine(url); url = wc.DownloadLink("http://x.newlifex.com/", "MySql.Data.st", "."); XTrace.WriteLine(url); url = wc.DownloadLink("http://x.newlifex.com/", "MySql.Data64Fx40,MySql.Data", "."); XTrace.WriteLine(url); url = wc.DownloadLink("http://x.newlifex.com/", "System.Data.SqlClient.st", "."); XTrace.WriteLine(url); }
///// <summary>自动扫描控制器,并添加到菜单</summary> ///// <remarks>默认操作当前注册区域的下一级Controllers命名空间</remarks> //protected override void ScanController() //{ // base.ScanController(); // var menu = ManageProvider.Menu.Root.FindByPath(AreaName); // if (menu != null && menu.DisplayName.IsNullOrEmpty()) // { // menu.DisplayName = "管理平台"; // menu.Save(); // } //} void CheckContent() { var cube = "~/Content/Cube.js".GetFullPath(); if (File.Exists(cube)) { return; } var url = Setting.Current.PluginServer; if (url.IsNullOrEmpty()) { return; } var wc = new WebClientX(true, true); wc.Log = XTrace.Log; wc.DownloadLinkAndExtract(url, "Cube_Content", "~/Content".GetFullPath()); }
/// <summary>创建客户端</summary> /// <param name="url">路径</param> /// <returns></returns> protected override String Request(String url) { if (_Client == null) { // 允许宽松头部 WebClientX.SetAllowUnsafeHeaderParsing(true); var asm = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly(); var agent = ""; if (asm != null) { agent = $"{asm.GetName().Name} v{asm.GetName().Version}"; } var client = new System.Net.Http.HttpClient(); client.DefaultRequestHeaders.UserAgent.ParseAdd(agent); _Client = client; } return(LastHtml = _Client.GetStringAsync(url).Result); }
/// <summary>异步获取字符串</summary> /// <param name="url"></param> /// <returns></returns> public virtual async Task <String> GetStringAsync(String url) { var key = AcquireKey(); if (key.IsNullOrEmpty()) { throw new ArgumentNullException(nameof(AppKey), "没有可用密钥"); } if (_Client == null) { _Client = new WebClientX { Log = Log } } ; if (url.Contains("?")) { url += "&"; } else { url += "?"; } url += KeyName + "=" + key; LastUrl = url; LastString = null; LastKey = key; var rs = await _Client.DownloadStringAsync(url).ConfigureAwait(false); //// 删除无效密钥 //if (IsValidKey(rs)) RemoveKey(key); return(LastString = rs); }
static void CheckContent() { var js = "~/Content/Cube.js".GetFullPath(); var css = "~/Content/Cube.css".GetFullPath(); if (File.Exists(js) && File.Exists(css)) { // 判断脚本时间 var dt = DateTime.MinValue; var ss = File.ReadAllLines(js); for (var i = 0; i < 5; i++) { if (DateTime.TryParse(ss[i].TrimStart("//").Trim(), out dt)) { break; } } // 要求脚本最小更新时间 if (dt >= "2017-11-27 00:00:00".ToDateTime()) { return; } } var url = Setting.Current.PluginServer; if (url.IsNullOrEmpty()) { return; } var wc = new WebClientX(true, true) { Log = XTrace.Log }; wc.DownloadLinkAndExtract(url, "Cube_Content", "~/Content".GetFullPath(), true); }
public static void ParseStockGroup(GroupKind model, string url) { WebClientX client = new WebClientX(); client.Timeout = 1000 * 120; var text = client.GetHtml(url); var doc = new HtmlDocument(); doc.LoadHtml(text); var value = doc.DocumentNode.InnerText; string node = @"/html[1]/body[1]/div[4]/div[1]/div[3]/table[1]/tbody[1]"; var res = doc.DocumentNode.SelectSingleNode(node).SelectNodes(@"tr"); if (res == null) { return; } if (res.Count > 1) { for (int i = 1; i < res.Count; i++) { var code = res[i].SelectSingleNode(@"td[1]").InnerText.Trim(); var name = res[i].SelectSingleNode(@"td[2]").InnerText.Trim(); StockGroup et = new StockGroup() { Code = code, StockName = name, GroupID = model.ID, Kind = model.Kind, CreateDate = DateTime.Now }; et.ID = "{0}_{1}".F(et.GroupID, et.Code); et.Save(); } #endregion } }
static Ip() { var ns = new String[] { "qqwry.dat", "qqwry.gz", "ip.gz", "ip.gz.config", "ipdata.config" }; foreach (var item in ns) { var fs = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, item, SearchOption.AllDirectories); if (fs != null && fs.Length > 0) { DbFile = Path.GetFullPath(fs[0]); break; } } // 如果本地没有IP数据库,则从网络下载 if (DbFile.IsNullOrWhiteSpace()) { Task.Factory.StartNew(() => { var url = Setting.Current.PluginServer; XTrace.WriteLine("没有找到IP数据库,准备联网获取 {0}", url); var client = new WebClientX(); client.Log = XTrace.Log; var dir = Runtime.IsWeb ? "App_Data" : "Data"; var file = client.DownloadLink(url, "ip.gz", dir.GetFullPath()); if (File.Exists(file)) { DbFile = file.GetFullPath(); zip = null; // 让它重新初始化 _inited = null; } }, TaskCreationOptions.LongRunning).LogException(); } }
static Ip() { var ns = new String[] { "qqwry.dat", "qqwry.gz", "ip.gz", "ip.gz.config", "ipdata.config" }; foreach (var item in ns) { var fi = ".".AsDirectory().GetAllFiles(item, true).FirstOrDefault(); if (fi != null) { DbFile = fi.FullName; break; } } // 如果本地没有IP数据库,则从网络下载 if (DbFile.IsNullOrWhiteSpace()) { Task.Factory.StartNew(() => { var url = Setting.Current.PluginServer; XTrace.WriteLine("没有找到IP数据库,准备联网获取 {0}", url); var client = new WebClientX(); client.Log = XTrace.Log; var dir = Runtime.IsWeb ? "App_Data" : "Data"; var file = client.DownloadLink(url, "ip.gz", dir.GetFullPath()); if (File.Exists(file)) { DbFile = file.GetFullPath(); zip = null; // 让它重新初始化 _inited = null; } }, TaskCreationOptions.LongRunning).LogException(); } }
static void CheckContent() { var js = "~/Content/Cube.js".GetFullPath(); var css = "~/Content/Cube.css".GetFullPath(); if (File.Exists(js) && File.Exists(css)) { return; } var url = Setting.Current.PluginServer; if (url.IsNullOrEmpty()) { return; } var wc = new WebClientX(true, true) { Log = XTrace.Log }; wc.DownloadLinkAndExtract(url, "Cube_Content", "~/Content".GetFullPath(), false); }
/// <summary>检查是否安装了语音库</summary> void CheckVoice() { if (_type == null) { return; } try { var synth = _type.CreateInstance(new Object[0]); var vs = synth.Invoke("GetInstalledVoices") as IList; if (vs != null && vs.Count > 0) { var flag = false; foreach (var item in vs) { if (XTrace.Debug) { XTrace.WriteLine("语音库:{0}", item.GetValue("VoiceInfo").GetValue("Description")); } if ((Boolean)item.GetValue("Enabled")) { flag = true; } } if (flag) { return; } } } catch { } var url = Setting.Current.PluginServer; XTrace.WriteLine("没有找到语音运行时,准备联网获取 {0}", url); var dir = ".".GetFullPath(); if (Runtime.IsWeb) { dir = dir.CombinePath("Bin"); } dir.EnsureDirectory(); var client = new WebClientX(true, true); client.Log = XTrace.Log; var file2 = client.DownloadLinkAndExtract(url, "SpeechRuntime", dir); if (!file2.IsNullOrEmpty()) { // 安装语音库 var msi = "SpeechPlatformRuntime_x{0}.msi".F(Runtime.Is64BitOperatingSystem ? 64 : 86); msi = dir.CombinePath(msi); if (File.Exists(msi)) { XTrace.WriteLine("正在安装语音平台运行时 {0}", msi); "msiexec".Run("/i \"" + msi + "\" /passive /norestart", 5000); } msi = "MSSpeech_TTS_zh-CN_HuiHui.msi"; msi = dir.CombinePath(msi); if (File.Exists(msi)) { XTrace.WriteLine("正在安装微软TTS中文语音库 {0}", msi); "msiexec".Run("/i \"" + msi + "\" /passive /norestart", 5000); } } }
public GCCArmLocation() { #region 从注册表获取目录和版本 if (String.IsNullOrEmpty(ToolPath)) { var reg = Registry.LocalMachine.OpenSubKey(@"Software\ARM\GNU Tools for ARM Embedded Processors"); if (reg == null) { reg = Registry.LocalMachine.OpenSubKey(@"Software\Wow6432Node\ARM\GNU Tools for ARM Embedded Processors"); } if (reg != null) { ToolPath = reg.GetValue("InstallFolder") + ""; if (ToolPath.Contains(".")) { Version = ToolPath.AsDirectory().Name; } WriteLog("注册表 {0} {1}", ToolPath, Version); } } #endregion #region 扫描所有根目录,获取MDK安装目录 if (String.IsNullOrEmpty(ToolPath)) { foreach (var item in DriveInfo.GetDrives()) { if (!item.IsReady) { continue; } var p = Path.Combine(item.RootDirectory.FullName, @"GCCArm\arm-none-eabi"); if (!Directory.Exists(p)) { p = Path.Combine(item.RootDirectory.FullName, @"GCC\arm-none-eabi"); } if (Directory.Exists(p)) { p = p.CombinePath(@"..\").GetFullPath(); var ver = GetVer(p); if (ver.CompareTo(Version) > 0) { ToolPath = p; Version = ver; WriteLog("本地 {0} {1}", p, ver); } } } } #endregion #region 版本更新 if (String.IsNullOrEmpty(ToolPath)) { XTrace.WriteLine("准备下载安装 GCCArm", Version); var url = "http://x.newlifex.com/"; var client = new WebClientX(true, true) { Log = XTrace.Log }; var p = Environment.SystemDirectory.CombinePath("..\\..\\GCCArm").GetFullPath(); var file = client.DownloadLinkAndExtract(url, "GCCArm", p); if (Directory.Exists(p)) { var ver = GetVer(p); if (ver.CompareTo(Version) > 0) { ToolPath = p; Version = ver; } } } #endregion if (String.IsNullOrEmpty(ToolPath)) { throw new Exception("无法获取GCC Arm安装目录!"); } }