private void ShowFile(string filenameBase64) { // 计算文件名的相对路径,从BASE64字符串中还原,具体可参考 GetUrl 方法 string filePath = filenameBase64.FromBase64(); filePath = Path.Combine(_logPath, filePath); if (RetryFile.Exists(filePath) == false) { WriteMessage("要查看的日志文件不存在:" + filePath); return; } // 安全检查,只允许查看日志下的文件 if (filePath.StartsWith(_logPath, StringComparison.OrdinalIgnoreCase) == false) { WriteMessage("无效的文件路径,已超出日志文件的根目录。"); return; } // 读文件,写响应流 string text = RetryFile.ReadAllText(filePath, Encoding.UTF8); // 由于是文本文件,所以就直接字符串输出 WriteMessage(text); }
IHttpHandler IHttpHandlerFactory.GetHandler(HttpContext context, string requestType, string virtualPath, string physicalPath) { // 说明:这里不使用virtualPath变量,因为不同的配置,这个变量的值会不一样。 // 例如:/mvc/*/*.aspx 和 /mvc/* // 为了映射HTTP处理器,下面直接使用context.Request.Path string requestPath = context.Request.Path; string vPath = context.GetRealVirtualPath(); // 尝试根据请求路径获取Action ControllerResolver controllerResolver = new ControllerResolver(context); InvokeInfo vkInfo = controllerResolver.GetActionInvokeInfo(vPath); // 如果没有找到合适的Action,并且请求的是一个ASPX页面,则按ASP.NET默认的方式来继续处理 if (vkInfo == null) { if (requestPath.EndsWithIgnoreCase(".aspx") && RetryFile.Exists(context.Request.PhysicalPath)) { // 调用ASP.NET默认的Page处理器工厂来处理 return(_msPageHandlerFactory.GetHandler(context, requestType, requestPath, physicalPath)); } else { ExceptionHelper.Throw404Exception(context); } } return(ActionHandlerFactory.CreateHandler(vkInfo)); }
public void Test_生成实体代理类程序集() { Type[] entityTypes = new Type[] { typeof(Product), typeof(Customer) }; string dllFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Test.EntityProxy.dll"); RetryFile.Delete(dllFilePath); var result = ProxyBuilder.Compile(entityTypes, dllFilePath); Assert.IsTrue(RetryFile.Exists(dllFilePath)); // 加载程序集并确认结果 Assembly asm = Assembly.LoadFrom(dllFilePath); Type[] types = asm.GetExportedTypes(); var t1 = (from x in types where x.Name.StartsWith("Customer_") && x.Name.EndsWith("_Loader") select x).First(); var t2 = (from x in types where x.Name.StartsWith("Customer_") && x.Name.EndsWith("_Proxy") select x).First(); var t3 = (from x in types where x.Name.StartsWith("Product_") && x.Name.EndsWith("_Loader") select x).First(); var t4 = (from x in types where x.Name.StartsWith("Product_") && x.Name.EndsWith("_Proxy") select x).First(); }
private static string SafeReadFile(string filePath) { if (RetryFile.Exists(filePath)) { return(RetryFile.ReadAllText(filePath, Encoding.UTF8)); } return(null); }
/// <summary> /// 给 ASP.NET RouteTable 注册路由规则 /// </summary> private static void InitRouting() { string filePath = WebRuntime.Instance.GetPhysicalPath("ClownFish.Web.RouteTable.config"); if (RetryFile.Exists(filePath) == false) { throw new FileNotFoundException("未能找到文件:" + filePath + " ,如果要启用 MvcRoutingModule,必须配置这个文件。"); } ClownFish.Web.Config.RouteTableConfig config = XmlHelper.XmlDeserializeFromFile <ClownFish.Web.Config.RouteTableConfig>(filePath); if (config.Routes != null) { foreach (var route in config.Routes) { if (string.IsNullOrEmpty(route.Url)) { throw new System.Configuration.ConfigurationErrorsException("路由规则配置,必须要指定URL属性。"); } RouteValueDictionary values = new RouteValueDictionary(); if (string.IsNullOrEmpty(route.Namespace) == false) { values.Add("namespace", route.Namespace); } if (string.IsNullOrEmpty(route.Controller) == false) { values.Add("controller", route.Controller); } if (string.IsNullOrEmpty(route.Action) == false) { values.Add("action", route.Action); } System.Web.Routing.Route routeRule = new System.Web.Routing.Route(route.Url, new MvcRouteHandler()); if (values.Count > 0) { routeRule.DataTokens = values; } if (string.IsNullOrEmpty(route.Name)) { RouteTable.Routes.Add(routeRule); } else { RouteTable.Routes.Add(route.Name, routeRule); } } } }
/// <summary> /// 加载默认的配置文件(ClownFish.Log.config) /// </summary> /// <returns></returns> public static LogConfig ReadConfigFile() { string configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ClownFish.Log.config"); if (RetryFile.Exists(configFile) == false) { throw new FileNotFoundException("配置文件不存在:" + configFile); } return(XmlHelper.XmlDeserializeFromFile <LogConfig>(configFile)); }
private static Dictionary <string, OutputCacheSetting> LoadConfigFile(string[] files) { string configFilePath = files[0]; if (RetryFile.Exists(configFilePath) == false) { throw new FileNotFoundException("未能找到文件:" + configFilePath + " ,如果要启用 SetOutputCacheModule,必须配置这个文件。"); } OutputCacheConfig config = XmlHelper.XmlDeserializeFromFile <OutputCacheConfig>(configFilePath); return(config.Settings.ToDictionary(x => x.FilePath, StringComparer.OrdinalIgnoreCase)); }
/// <summary> /// /// </summary> protected override void PostDeserialize() { try { string templatePath = UiHelper.AppRoot + this.Http404PagePath.Replace("/", "\\"); if (RetryFile.Exists(templatePath) == false) { throw new System.IO.FileNotFoundException(); } } catch { throw new ConfigurationErrorsException("pipeline.http404TemplatePagePath 配置值无效。"); } }
private void OutputCssFile(HttpContext context) { // 1. 先读出文件内容。注意这里使用UTF-8编码 // 2. 用正则表达式搜索所有的引用文件 // 3. 循环匹配结果, // 4. 对于匹配之外的内容,直接写入StringBuilder实例, // 5. 如果是文件,则计算版本号,再一起写入到StringBuilder实例 // 6. 最后,StringBuilder实例包含的内容就是处理后的结果。 string text = RetryFile.ReadAllText(context.Request.PhysicalPath, Encoding.UTF8); MatchCollection matches = s_CssBackgroundImageRegex.Matches(text); if (matches != null && matches.Count > 0) { int lastIndex = 0; StringBuilder sb = new StringBuilder(text.Length * 2); foreach (Match m in matches) { Group g = m.Groups["file"]; if (g.Success) { sb.Append(text.Substring(lastIndex, g.Index - lastIndex + g.Length)); lastIndex = g.Index + g.Length; //string fileFullPath = HttpRuntime.AppDomainAppPath.TrimEnd('\\') + g.Value.Replace("/", "\\"); string fileFullPath = WebRuntime.Instance.GetPhysicalPath(g.Value.Replace("/", "\\")); if (RetryFile.Exists(fileFullPath)) { string version = RetryFile.GetLastWriteTimeUtc(fileFullPath).Ticks.ToString(); sb.Append("?_v=").Append(version); } } } if (lastIndex > 0 && lastIndex < text.Length) { sb.Append(text.Substring(lastIndex)); } context.Response.Write(sb.ToString()); } else { context.Response.Write(text); } }
private static void LoadDbFromXml() { if (s_db != null) { return; } string xmlPath = Path.Combine(HttpRuntime.AppDomainAppPath, @"App_Data\MyNorthwindDataBase.xml"); if (RetryFile.Exists(xmlPath) == false) { throw new ArgumentException("指定的文件不存在:" + xmlPath); } s_db = XmlHelper.XmlDeserializeFromFile <MyNorthwind>(xmlPath); }
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { if (s_dllDirectory == null) { return(null); } string name = args.Name.Split(',')[0] + ".dll"; string filePath = Path.Combine(s_dllDirectory, name); if (RetryFile.Exists(filePath) == false) { return(null); } return(Assembly.LoadFrom(filePath)); }
/// <summary> /// 处理请求,输出文件内容以及设置缓存响应头 /// </summary> /// <param name="context"></param> public void ProcessRequest(HttpContext context) { Init(); string filePath = context.Request.PhysicalPath; bool isCssFile = filePath.EndsWith(".css", StringComparison.OrdinalIgnoreCase); if (RetryFile.Exists(filePath) == false) { new Http404Result().Ouput(context); return; } LazyFileInfo fileinfo = new LazyFileInfo(filePath); //string etagHeader = context.Request.Headers["If-None-Match"]; //if( string.IsNullOrEmpty(etagHeader) == false ) { // // 如果文件没有修改,就返回304响应 // if( fileinfo.LastWriteTime.Ticks.ToString() == etagHeader ) { // context.Response.StatusCode = 304; // context.Response.End(); // return; // } //} // 说明:Etag响应头在有些场景下会不起使用,例如VS自带的WEB服务器,或者Windows身份认证中。 // 因此现在采用SetLastModified + "If-Modified-Since" 的方式来识别304请求。 // 如果加了版本号,就表示需要长期缓存的文件,此时当文件没有修改时,用304来结束请求。 if (isCssFile == false && // CSS文件不能用304来响应,否则图片永远不能刷新 context.Request.QueryString.Count > 0) { string modifiedSince = context.Request.Headers["If-Modified-Since"]; if (string.IsNullOrEmpty(modifiedSince) == false) { DateTime dt; if (DateTime.TryParse(modifiedSince, out dt)) { // 因为要排除毫秒,所以判断是否小于1秒 if ((fileinfo.LastWriteTime - dt).TotalSeconds < 1.0) { context.Response.StatusCode = 304; context.Response.End(); return; } } } } // 设置输出缓存头 context.Response.Cache.SetCacheability(HttpCacheability.Public); // 如果请求的URL包含查询字符串,就认为是包含了版本参数,此时设置缓存时间为【一年】 if (isCssFile == false && // 注意:这里仍然要排除CSS文件 context.Request.QueryString.Count > 0) { context.Response.AppendHeader("X-StaticFileHandler", "1year"); context.Response.Cache.SetMaxAge(TimeSpan.FromSeconds(24 * 60 * 60 * 365)); context.Response.Cache.SetExpires(DateTime.Now.AddYears(1)); } else { int duration = GetDuration(fileinfo); context.Response.AppendHeader("X-StaticFileHandler", duration.ToString()); context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(duration)); //context.Response.Cache.SetMaxAge(TimeSpan.FromSeconds(duration)); // 上面的代码不起作用,只能用下面的方法来处理了。 context.Response.Cache.AppendCacheExtension("max-age=" + duration.ToString()); } // 设置HTTP缓存响应头 //context.Response.Cache.SetETag(fileinfo.LastWriteTime.Ticks.ToString()); context.Response.Cache.SetLastModified(fileinfo.LastWriteTime); // 设置响应内容标头 string contentType = (string)s_mineTable[fileinfo.Extension]; if (contentType == null) { contentType = GetMimeType(fileinfo); s_mineTable[fileinfo.Extension] = contentType; } context.Response.ContentType = contentType; // 输出文件内容 if (isCssFile) { OutputCssFile(context); } else { context.Response.TransmitFile(filePath); } }
static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("没有指定实体程序集文件名或者包含实体程序集的路径。"); return; } //Console.WriteLine("调试消息:请在附加进程后,按ENTER继续,"); //Console.ReadLine(); string[] commandArgs = (from x in System.Environment.GetCommandLineArgs() let a = "\"" + x + "\"" select a).ToArray(); Console.WriteLine("Execute: " + string.Join(" ", commandArgs)); // 读取命令行参数,并计算绝对路径 bool isFile = false; string path = Path.GetFullPath(Path.Combine(System.Environment.CurrentDirectory, args[0])); if (RetryFile.Exists(path)) { if (path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) == false) { Console.WriteLine("命令参数必须是一个程序集的DLL文件。"); return; } s_dllDirectory = Path.GetDirectoryName(path); isFile = true; } else if (Directory.Exists(path)) { s_dllDirectory = path; } else { Console.WriteLine($"指定的参数 {args[0]} 既不是文件也不是目录。"); return; } AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; // 生成代理类程序集 try { if (isFile) { Execute(path); } else { ExecuteBatch(path); } //Console.WriteLine("ClownFish.Data.ProxyGen.exe execute success."); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }