/// <summary>获取客户端</summary> /// <returns></returns> protected virtual HttpClient GetClient() { if (_Client != null) { return(_Client); } // 允许宽松头部 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 HttpClient(new HttpClientHandler { UseProxy = false }); var headers = client.DefaultRequestHeaders; headers.UserAgent.ParseAdd(agent); return(_Client = client); }
/// <summary>根据授权码获取访问令牌</summary> /// <param name="code"></param> /// <returns></returns> public String GetAccessToken(String code) { Code = code; var url = GetUrl(AccessUrl); var wc = new WebClientX(); var html = wc.DownloadString(url); if (html.IsNullOrEmpty()) { return(null); } var dic = html.SplitAsDictionary("=", "&"); if (dic.ContainsKey("access_token")) { AccessToken = dic["access_token"].Trim(); } if (dic.ContainsKey("expires_in")) { Expire = DateTime.Now.AddSeconds(dic["expires_in"].Trim().ToInt()); } if (dic.ContainsKey("refresh_token")) { RefreshToken = dic["refresh_token"].Trim(); } return(html); }
/// <summary>创建客户端</summary> /// <param name="url">路径</param> /// <returns></returns> protected virtual String Request(String url) { if (_Client == null) { _Client = new WebClientX(); } return(LastHtml = _Client.GetHtml(url)); }
/// <summary>创建客户端</summary> /// <param name="url">路径</param> /// <returns></returns> protected virtual async Task <String> Request(String url) { if (_Client == null) { _Client = new WebClientX(); } return(await _Client.DownloadStringAsync(url)); }
/// <summary>加载插件</summary> /// <param name="typeName"></param> /// <param name="disname"></param> /// <param name="dll"></param> /// <param name="linkName"></param> /// <param name="url"></param> /// <returns></returns> public static Type LoadPlugin(String typeName, String disname, String dll, String linkName, String url) { var type = typeName.GetTypeEx(true); if (type != null) { return(type); } if (dll.IsNullOrEmpty()) { return(null); } // 先检查当前目录,再检查插件目录 var file = dll.GetFullPath(); if (!File.Exists(file) && Runtime.IsWeb) { file = "Bin".GetFullPath().CombinePath(dll); } if (!File.Exists(file)) { file = Setting.Current.GetPluginPath().CombinePath(dll); } // 如果本地没有数据库,则从网络下载 if (!File.Exists(file)) { XTrace.WriteLine("{0}不存在或平台版本不正确,准备联网获取 {1}", disname ?? dll, url); var client = new WebClientX(true, true); client.Log = XTrace.Log; var dir = Path.GetDirectoryName(file); var file2 = client.DownloadLinkAndExtract(url, linkName, dir); } if (!File.Exists(file)) { XTrace.WriteLine("未找到 {0} {1}", disname, dll); return(null); } type = typeName.GetTypeEx(true); if (type != null) { return(type); } //var assembly = Assembly.LoadFrom(file); //if (assembly == null) return null; //type = assembly.GetType(typeName); //if (type == null) type = AssemblyX.Create(assembly).GetType(typeName); return(type); }
//private WebClientX _Client; /// <summary>创建客户端</summary> /// <param name="url">路径</param> /// <returns></returns> protected virtual async Task <String> Request(String url) { //if (_Client == null) //{ // _Client = new WebClientX(); // _Client.Log = Log; //} //return await _Client.DownloadStringAsync(url); return(LastHtml = await WebClientX.GetStringAsync(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> /// <returns></returns> protected virtual HttpClient GetClient() { if (_Client != null) { return(_Client); } // 允许宽松头部 WebClientX.SetAllowUnsafeHeaderParsing(true); var client = CreateClient(); return(_Client = client); }
/// <summary>加载插件</summary> /// <param name="typeName"></param> /// <param name="disname"></param> /// <param name="dll"></param> /// <param name="linkName"></param> /// <param name="url"></param> /// <returns></returns> public static Type LoadPlugin(String typeName, String disname, String dll, String linkName, String url) { var type = typeName.GetTypeEx(true); if (type != null) return type; if (dll.IsNullOrEmpty()) return null; // 先检查当前目录,再检查插件目录 var file = dll.GetFullPath(); if (!File.Exists(file) && Runtime.IsWeb) file = "Bin".GetFullPath().CombinePath(dll); if (!File.Exists(file)) file = Setting.Current.GetPluginPath().CombinePath(dll); // 如果本地没有数据库,则从网络下载 if (!File.Exists(file)) { XTrace.WriteLine("{0}不存在或平台版本不正确,准备联网获取 {1}", disname ?? dll, url); var client = new WebClientX(true, true); client.Log = XTrace.Log; var dir = Path.GetDirectoryName(file); var file2 = client.DownloadLinkAndExtract(url, linkName, dir); } if (!File.Exists(file)) { XTrace.WriteLine("未找到 {0} {1}", disname, dll); return null; } type = typeName.GetTypeEx(true); if (type != null) return type; //var assembly = Assembly.LoadFrom(file); //if (assembly == null) return null; //type = assembly.GetType(typeName); //if (type == null) type = AssemblyX.Create(assembly).GetType(typeName); return type; }
/// <summary>加载插件</summary> /// <param name="typeName"></param> /// <param name="disname"></param> /// <param name="dll"></param> /// <param name="linkName"></param> /// <param name="urls">提供下载地址的多个目标页面</param> /// <returns></returns> public static Type LoadPlugin(String typeName, String disname, String dll, String linkName, String urls = null) { var type = typeName.GetTypeEx(true); if (type != null) { return(type); } if (dll.IsNullOrEmpty()) { return(null); } lock (typeName) { var set = Setting.Current; var file = ""; if (!dll.IsNullOrEmpty()) { // 先检查当前目录,再检查插件目录 file = dll.GetFullPath(); if (!File.Exists(file) && Runtime.IsWeb) { file = "Bin".GetFullPath().CombinePath(dll); } if (!File.Exists(file)) { file = set.PluginPath.GetFullPath().CombinePath(dll); } if (!File.Exists(file)) { file = set.PluginPath.GetBasePath().CombinePath(dll); } } if (urls.IsNullOrEmpty()) { urls = set.PluginServer; } // 如果本地没有数据库,则从网络下载 if (!File.Exists(file)) { XTrace.WriteLine("{0}不存在或平台版本不正确,准备联网获取 {1}", disname ?? dll, urls); var client = new WebClientX() { Log = XTrace.Log }; var dir = Path.GetDirectoryName(file); var file2 = client.DownloadLinkAndExtract(urls, linkName, dir); client.TryDispose(); } if (!File.Exists(file)) { XTrace.WriteLine("未找到 {0} {1}", disname, dll); return(null); } //return Assembly.LoadFrom(file).GetType(typeName); return(typeName.GetTypeEx(true)); } }
void ProcessInternal() { // 取版本 // 对比版本 // 拿出更新源 // 下载更新包 // 执行更新 #region 取版本、对比版本 WebClientX client = new WebClientX(); // 同步下载,3秒超时 client.Timeout = 3000; String xml = client.DownloadString(VerSrc); if (String.IsNullOrEmpty(xml)) return; VerFile ver = new VerFile(xml); if (LocalVersion >= ver.GetVersion()) return; #endregion #region 下载 String upfile = String.Format("XCoder_{0}.zip", ver.Ver); upfile = Path.Combine("Update", upfile); String file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, upfile); String dir = Path.GetDirectoryName(file); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); if (!File.Exists(file)) { String url = ver.Src; if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { //Uri uri = new Uri(VerSrc); //uri = new Uri(uri, url); //url = uri.ToString(); url = VerSrc.Replace("XCoderVer.xml", url); } XTrace.WriteLine("准备从{0}下载相关文件到{1}!", url, file); client.DownloadFile(url, file); } #endregion #region 提示更新 { StringBuilder sb = new StringBuilder(); sb.AppendFormat("是否更新到最新版本:{0}", ver.Ver); sb.AppendLine(); if (!String.IsNullOrEmpty(ver.Description)) { sb.AppendLine("更新内容:"); sb.Append(ver.Description); } if (MessageBox.Show(sb.ToString(), "发现新版本", MessageBoxButtons.OKCancel) == DialogResult.Cancel) return; } #endregion #region 更新 if (File.Exists(file)) { // 解压缩,删除压缩文件 IOHelper.DecompressFile(file, null, false); File.Delete(file); StringBuilder sb = new StringBuilder(); // 复制 sb.AppendFormat("xcopy {0}\\*.* {1} /s /y /r", dir, AppDomain.CurrentDomain.BaseDirectory); sb.AppendLine(); sb.AppendLine("rd \"" + dir + "\" /s /q"); // 启动XCoder sb.AppendLine("start " + Application.ExecutablePath); // 删除dir目录 sb.AppendLine("rd \"" + dir + "\" /s /q"); // 删除模版目录 ////dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Engine.TemplatePath); //dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template"); //sb.AppendLine("rd \"" + dir + "\" /s /q"); String tmpfile = Path.GetTempFileName() + ".bat"; //String tmpfile = "Update_" + DateTime.Now.ToString("yyMMddHHmmss") + ".bat"; //tmpfile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, tmpfile); File.WriteAllText(tmpfile, sb.ToString(), Encoding.Default); String ph = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "NewLife.ProcessHelper.exe"); if (File.Exists(ph)) File.Delete(ph); FileSource.ReleaseFile("XCoder.NewLife.ProcessHelper.exe", ph); ProcessStartInfo si = new ProcessStartInfo(); si.FileName = ph; si.Arguments = Process.GetCurrentProcess().Id + " " + tmpfile; if (!XTrace.Debug) { si.CreateNoWindow = true; si.WindowStyle = ProcessWindowStyle.Hidden; } Process.Start(si); //Process.Start(ph, Process.GetCurrentProcess().Id + " " + tmpfile); Application.Exit(); } #endregion }
protected static void CheckAndDownload(String file, String targetPath = null) { if (!Path.IsPathRooted(file)) { if (!Runtime.IsWeb) file = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file); else file = Path.Combine(HttpRuntime.BinDirectory, file); } if (File.Exists(file) && new FileInfo(file).Length > 0) return; // 目标目录 String dir = !String.IsNullOrEmpty(targetPath) ? targetPath : Path.GetDirectoryName(file); // 从网上下载文件 var zipfile = Path.GetFileNameWithoutExtension(file); try { #region 检测64位平台 Module module = typeof(Object).Module; PortableExecutableKinds kind; ImageFileMachine machine; module.GetPEKind(out kind, out machine); if (machine != ImageFileMachine.I386) zipfile += "64"; #endregion zipfile += ".zip"; String url = String.Format(ServiceAddress, zipfile); // 目标Zip文件 zipfile = Path.Combine(dir, zipfile); // Zip文件不存在,准备下载 if (!File.Exists(zipfile) || new FileInfo(zipfile).Length <= 0) { DAL.WriteLog("准备从{0}下载文件到{1}!", url, zipfile); var client = new WebClientX(true, true); // 同步下载,3秒超时 client.Timeout = 3000; //var data = client.DownloadData(url); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); client.DownloadFile(url, zipfile); client.Dispose(); } DAL.WriteLog("下载完成,准备解压到{0}!", dir); //var ms = new MemoryStream(data); //if (file.EndsWith("64")) file = file.Substring(0, file.Length - 2); //IOHelper.DecompressFile(ms, dir, file, false); ZipFile.Extract(zipfile, dir, true); DAL.WriteLog("解压完成!"); } catch (ZipException ex) { if (File.Exists(zipfile)) File.Delete(zipfile); DAL.WriteLog("解压失败,删除压缩文件!{0}", ex.ToString()); } catch (Exception ex) { DAL.WriteLog(ex.ToString()); } }
public void Update() { // 取版本 // 对比版本 // 拿出更新源 // 下载更新包 // 执行更新 #region 准备工作 var curdir = AppDomain.CurrentDomain.BaseDirectory; String ProcessHelper = Path.Combine(curdir, "NewLife.ProcessHelper.exe"); if (File.Exists(ProcessHelper)) File.Delete(ProcessHelper); // 删除Update目录,避免重复使用错误的升级文件 var update = Path.Combine(curdir, "Update"); if (Directory.Exists(update)) { try { Directory.Delete(update, true); } catch { } } var updatebat = Path.Combine(curdir, "Update.bat"); if (File.Exists(updatebat)) { try { File.Delete(updatebat); } catch { } } // 开发环境下,自动生成版本文件 if (IsDevelop()) MakeVerFile(); #endregion #region 取版本、对比版本 var client = new WebClientX(); client.Encoding = Encoding.UTF8; // 同步下载,3秒超时 client.Timeout = 3000; XTrace.WriteLine("准备从{0}下载版本文件!", VerSrc); String xml = client.DownloadString(VerSrc); if (String.IsNullOrEmpty(xml)) { XTrace.WriteLine("无法从{0}获取版本信息!", VerSrc); return; } var ver = new VerFile(xml); var asm = Assembly.GetExecutingAssembly(); if (asm.GetName().Version >= ver.GetVersion()) return; #endregion #region 提示更新 { var sb = new StringBuilder(); sb.AppendFormat("是否更新到最新版本:{0}", ver.Ver); sb.AppendLine(); sb.AppendLine("XCoder会自动关闭以进行更新,更新完成后会启动新版本!"); if (!String.IsNullOrEmpty(ver.Description)) { sb.AppendLine("更新内容:"); sb.Append(ver.Description); } if (MessageBox.Show(sb.ToString(), "发现新版本", MessageBoxButtons.OKCancel) == DialogResult.Cancel) return; } #endregion #region 下载 String file = Path.Combine(update, "XCoder.zip"); CheckAndDownload(client, file, ver.Src); // 检查是否需要更新源码 String xfile = Path.Combine(@"C:\X\Src", "Src.zip"); String dfile = Path.Combine(@"C:\X\DLL", "DLL.zip"); CheckAndDownload(client, xfile, ver.XSrc); CheckAndDownload(client, dfile, ver.DLL); #endregion #region 更新 // 先更新源代码 Extract(xfile, null); Extract(dfile, null); var dir = Path.GetDirectoryName(file); if (Extract(file, dir)) { var cfgfile = Path.Combine(curdir, "XCoder.exe.config"); var xmlfile = Path.Combine(curdir, "XCoder.xml"); var sb = new StringBuilder(); // 备份配置文件 sb.AppendFormat("mov \"{0}\" \"{0}.bak\" /Y", cfgfile); sb.AppendFormat("mov \"{0}\" \"{0}.bak\" /Y", xmlfile); // 复制 sb.AppendFormat("copy \"{0}\\*.*\" \"{1}\" /y", dir, curdir); sb.AppendLine(); sb.AppendLine("rd \"" + dir + "\" /s /q"); // 还原配置文件 sb.AppendFormat("mov \"{0}.bak\" \"{0}\" /Y", cfgfile); sb.AppendFormat("mov \"{0}.bak\" \"{0}\" /Y", xmlfile); // 启动XCoder sb.AppendFormat("start {0}", Path.GetFileName(Application.ExecutablePath)); sb.AppendLine(); // 删除dir目录 //sb.AppendLine("rd \"" + dir + "\" /s /q"); sb.AppendFormat("del \"{0}\" /f/q", ProcessHelper); sb.AppendLine(); sb.AppendFormat("del \"{0}\" /f/q", updatebat); sb.AppendLine(); //String tmpfile = Path.GetTempFileName() + ".bat"; //String tmpfile = "Update.bat"; File.WriteAllText(updatebat, sb.ToString(), Encoding.Default); #region 老树修改 // FileSource.ReleaseFile("XCoder.NewLife.ProcessHelper.exe", ProcessHelper); //修改部分 string assemFullName = Assembly.GetExecutingAssembly().FullName; string assemNamespace = assemFullName.Substring(0, assemFullName.IndexOf(',')); //命名空间名称 FileSource.ReleaseFile(assemNamespace + ".NewLife.ProcessHelper.exe", ProcessHelper); #endregion ProcessStartInfo si = new ProcessStartInfo(); si.FileName = ProcessHelper; si.WorkingDirectory = Path.GetDirectoryName(si.FileName); si.Arguments = Process.GetCurrentProcess().Id + " " + updatebat; if (!XTrace.Debug) { si.CreateNoWindow = true; si.WindowStyle = ProcessWindowStyle.Hidden; } si.UseShellExecute = false; Process.Start(si); XTrace.WriteLine("已启动进程助手来升级,升级脚本:{0}", updatebat); Application.Exit(); } #endregion }
protected static void CheckAndDownload(String file, String targetPath = null) { if (!Path.IsPathRooted(file)) { if (!Runtime.IsWeb) file = file.GetFullPath(); else file = Path.Combine(HttpRuntime.BinDirectory, file); } if (File.Exists(file) && new FileInfo(file).Length > 0) return; // 目标目录 String dir = !String.IsNullOrEmpty(targetPath) ? targetPath : Path.GetDirectoryName(file); // 从网上下载文件 var zipfile = Path.GetFileNameWithoutExtension(file); try { #region 检测64位平台 var module = typeof(Object).Module; PortableExecutableKinds kind; ImageFileMachine machine; module.GetPEKind(out kind, out machine); if (machine != ImageFileMachine.I386) zipfile += "64"; #endregion zipfile += ".zip"; var url = String.Format(ServiceAddress, zipfile); var sw = new Stopwatch(); sw.Start(); // 检查缓存文件,一个月内有效 var x = Path.Combine(Path.GetPathRoot(Environment.SystemDirectory), @"X"); var xfile = Path.Combine(x, zipfile); var xf = new FileInfo(xfile); if (CacheZip && File.Exists(xfile) && xf.Length > 0 && xf.LastWriteTime.AddMonths(1) > DateTime.Now) zipfile = xfile; else { // 目标Zip文件 zipfile = Path.Combine(dir, zipfile); // Zip文件不存在,准备下载 if (!File.Exists(zipfile) || new FileInfo(zipfile).Length <= 0) { DAL.WriteLog("准备从{0}下载文件到{1}!", url, zipfile); var client = new WebClientX(true, true); // 同步下载,3秒超时 client.Timeout = 10000; //var data = client.DownloadData(url); if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); client.DownloadFile(url, zipfile); client.Dispose(); } if (CacheZip) File.Copy(zipfile, xfile, true); } sw.Stop(); var size = new FileInfo(zipfile).Length; DAL.WriteLog("下载{0}完成({3:n0}字节),耗时{2},准备解压到{1}!", zipfile, dir, sw.Elapsed, size); //var ms = new MemoryStream(data); //if (file.EndsWith("64")) file = file.Substring(0, file.Length - 2); //IOHelper.DecompressFile(ms, dir, file, false); ZipFile.Extract(zipfile, dir, true); DAL.WriteLog("解压完成!"); } catch (ZipException ex) { if (File.Exists(zipfile)) File.Delete(zipfile); DAL.WriteLog("解压失败,删除压缩文件!{0}", ex.ToString()); } catch (Exception ex) { DAL.WriteLog(ex.ToString()); } }
/// <summary>创建客户端</summary> /// <param name="url">路径</param> /// <returns></returns> protected virtual async Task <String> Request(String url) { return(LastHtml = await WebClientX.GetStringAsync(url)); }