Beispiel #1
0
        /// <summary>
        /// 安全地记录一个异常对象到文本文件。
        /// </summary>
        /// <param name="ex"></param>
        public static void SafeLogException(Exception ex)
        {
            if (ex is MyMessageException)
            {
                return;
            }

            if (ex is HttpException)
            {
                HttpException ee = ex as HttpException;
                if (ee.GetHttpCode() == 404)
                {
                    return;
                }
            }


            try {
                string logfilePath = Path.Combine(HttpRuntime.AppDomainAppPath, @"App_Data\ErrorLog.txt");
                string message     = ex.ToString() + "\r\n\r\n\r\n";
                if (HttpContext.Current != null)
                {
                    message = "Url: " + HttpContext.Current.Request.RawUrl + "\r\n" + message;
                }

                RetryFile.AppendAllText(logfilePath, message, System.Text.Encoding.UTF8);
            }
            catch { }
        }
Beispiel #2
0
        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();
        }
Beispiel #3
0
        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);
        }
Beispiel #4
0
        public void Init2()
        {
            RetryFile.WriteAllText(s_testFilePath, "abc", Encoding.UTF8);

            // 设置 FileDependencyManager.RemovedCallback 的等待时间
            typeof(FileDependencyManager <string>).SetValue("s_WaitFileCloseTimeout", null, 100);
        }
Beispiel #5
0
        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));
        }
Beispiel #6
0
        public static void AppendAllText(string filePath, string text, Encoding encoding, long maxLength)
        {
            using (FileStream file = RetryFile.OpenAppend(filePath)) {
                // 如果文件已超过指定长度,就不再写入
                if (maxLength > 0 && file.Position >= maxLength)
                {
                    return;
                }


                if (file.Position == 0)
                {
                    // 写入 BOM
                    byte[] preamble = encoding.GetPreamble();
                    if (preamble.Length != 0)
                    {
                        file.Write(preamble, 0, preamble.Length);
                    }
                }

                byte[] bb = encoding.GetBytes(text);
                file.Write(bb, 0, bb.Length);

                file.Flush(true);
            }
        }
Beispiel #7
0
        /// <summary>
        /// 批量写入日志信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        public void Write <T>(List <T> list) where T : Model.BaseInfo
        {
            if (list == null || list.Count == 0)
            {
                return;
            }

            // 注意:取类型名称时,不采用 info.GetType().Name ,因为可能有继承情况
            string filePath = GetFilePath(typeof(T));

            StringBuilder sb = new StringBuilder();

            foreach (T info in list)
            {
                string json     = ClownFish.Base.JsonExtensions.ToJson(info);
                string contents = json + "\r\n\r\n" + s_separateLine + "\r\n\r\n";
                sb.Append(contents);
            }


            if (sb.Length > 0)
            {
                RetryFile.AppendAllText(filePath, sb.ToString(), Encoding.UTF8);
            }
        }
        /// <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);
                    }
                }
            }
        }
Beispiel #9
0
        private static string SafeReadFile(string filePath)
        {
            if (RetryFile.Exists(filePath))
            {
                return(RetryFile.ReadAllText(filePath, Encoding.UTF8));
            }

            return(null);
        }
Beispiel #10
0
        internal static void AssertWriteOK(string flagString)
        {
            FileWriter fileWriter = new FileWriter();
            string     filePath   = fileWriter.GetFilePath(typeof(ExceptionInfo));

            string logText = RetryFile.ReadAllText(filePath, Encoding.UTF8);

            Assert.IsTrue(logText.IndexOf(flagString) > 0);
        }
Beispiel #11
0
        internal static HttpFile CreateFromFileInfo(FileInfo file)
        {
            HttpFile result = new HttpFile();

            result.FileName      = file.FullName;
            result.ContentLength = (int)file.Length;
            result.FileBody      = RetryFile.ReadAllBytes(file.FullName);
            return(result);
        }
Beispiel #12
0
        public void Test_生成实体代理类型代码()
        {
            EntityGenerator g    = new EntityGenerator();
            string          code = g.GetCode <Product>();

            code = EntityGenerator.UsingCodeBlock + code;

            //RetryFile.WriteAllText("..\\AutoCode1.cs", code, Encoding.UTF8);
            RetryFile.WriteAllText("EntityGeneratorTest_code.cs", code, Encoding.UTF8);
        }
Beispiel #13
0
        /// <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));
        }
Beispiel #14
0
        /// <summary>
        /// 将一个对象按XML序列化的方式写入到一个文件
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="path">保存文件路径</param>
        /// <param name="encoding">编码方式</param>
        public static void XmlSerializeToFile(object o, string path, Encoding encoding)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            using (FileStream file = RetryFile.OpenCreate(path)) {
                XmlSerializeInternal(file, o, encoding);
            }
        }
        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));
        }
Beispiel #16
0
        /// <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 配置值无效。");
            }
        }
Beispiel #17
0
        internal static void SaveLastTempCode(string code, string tempOutPath)
        {
            if (string.IsNullOrEmpty(tempOutPath))
            {
                return;
            }

            try {
                string filePath = Path.Combine(tempOutPath, "__last_temp_code.cs");
                RetryFile.WriteAllText(filePath, code, Encoding.UTF8);
            }
            catch {  /* 输出最近一次运行时运行的代码,方便调试程序,忽略写文件出现的异常。 */
            }
        }
Beispiel #18
0
        /// <summary>
        /// 生成引入CSS文件的HTML代码
        /// </summary>
        /// <param name="path"></param>
        /// <param name="inline"></param>
        /// <returns></returns>
        public static string RefCssFileHtml(string path, bool inline)
        {
            string filePath = AppRoot + path.Replace("/", "\\");

            if (inline)
            {
                return(string.Format("<style type=\"text/css\">\r\n{0}\r\n</style>",
                                     RetryFile.ReadAllText(filePath, Encoding.UTF8)));
            }
            else
            {
                string version = RetryFile.GetLastWriteTimeUtc(filePath).Ticks.ToString();
                return(string.Format("<link type=\"text/css\" rel=\"Stylesheet\" href=\"{0}?_t={1}\" />", path, version));
            }
        }
Beispiel #19
0
        internal static void SaveLastComplieError(CompilerResults cr, string tempOutPath)
        {
            if (string.IsNullOrEmpty(tempOutPath))
            {
                return;
            }

            try {
                string errorText = GetCompileErrorMessage(cr);
                string filePath  = Path.Combine(tempOutPath, "__last_CompilerError.txt");
                RetryFile.WriteAllText(filePath, errorText, Encoding.UTF8);
            }
            catch {  /* 输出最近一次运行时运行的异常,方便调试程序,忽略写文件出现的异常。 */
            }
        }
Beispiel #20
0
        /// <summary>
        /// 生成引入JavaScript文件的HTML代码
        /// </summary>
        /// <param name="path"></param>
        /// <param name="inline"></param>
        /// <returns></returns>
        public static string RefJsFileHtml(string path, bool inline)
        {
            string filePath = AppRoot + path.Replace("/", "\\");

            if (inline)
            {
                return(string.Format("<script type=\"text/javascript\">\r\n{0}\r\n</script>",
                                     RetryFile.ReadAllText(filePath, Encoding.UTF8)));
            }
            else
            {
                string version = RetryFile.GetLastWriteTimeUtc(filePath).Ticks.ToString();
                return(string.Format("<script type=\"text/javascript\" src=\"{0}?_t={1}\"></script>", path, version));
            }
        }
Beispiel #21
0
        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);
            }
        }
Beispiel #22
0
        /// <summary>
        /// 读入一个文件,并按XML的方式反序列化对象。
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="path">文件路径</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserializeFromFile <T>(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

            try {
                using (FileStream fs = RetryFile.OpenRead(path)) {
                    return((T)XmlDeserialize(fs, typeof(T)));
                }
            }
            catch (Exception ex) {
                throw new InvalidDataException("XML反序列失败,当前文件:" + path, ex);
            }
        }
Beispiel #23
0
        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);
        }
Beispiel #24
0
        public void Test_正常的文件缓存依赖行为()
        {
            FileDependencyManager <string> cacheItem = new FileDependencyManager <string>(
                files => SafeReadFile(files[0]),
                s_testFilePath);

            Assert.AreEqual("abc", cacheItem.Result);

            // 修改文件
            RetryFile.WriteAllText(s_testFilePath, "Fish Li", Encoding.UTF8);

            // FileDependencyManager.RemovedCallback 有等待时间,所以这里要比那个时间再长一点
            System.Threading.Thread.Sleep(300);

            // 确认能拿到最新的结果
            Assert.AreEqual("Fish Li", cacheItem.Result);
        }
Beispiel #25
0
        /// <summary>
        /// 写入单条日志信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="info"></param>
        public void Write <T>(T info) where T : Model.BaseInfo
        {
            if (info == null)
            {
                return;
            }

            // 注意:取类型名称时,不采用 info.GetType().Name ,因为可能有继承情况
            string filePath = GetFilePath(typeof(T));


            string xml = XmlHelper.XmlSerialize(info, Encoding.UTF8);

            string contents = xml + "\r\n\r\n" + s_separateLine + "\r\n\r\n";

            RetryFile.AppendAllText(filePath, contents, Encoding.UTF8);
        }
Beispiel #26
0
        /// <summary>
        /// 写入单条日志信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="info"></param>
        public void Write <T>(T info) where T : Model.BaseInfo
        {
            if (info == null)
            {
                return;
            }

            // 注意:取类型名称时,不采用 info.GetType().Name ,因为可能有继承情况
            string filePath = GetFilePath(typeof(T));


            string json = ClownFish.Base.JsonExtensions.ToJson(info);

            string contents = json + "\r\n\r\n" + s_separateLine + "\r\n\r\n";

            RetryFile.AppendAllText(filePath, contents, Encoding.UTF8);
        }
Beispiel #27
0
        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));
        }
Beispiel #28
0
        /// <summary>
        /// 写入一条消息到日志文件。
        /// 说明:为了防止程序突然崩溃,写入消息时,不做任何缓冲处理,且每次写入时打开文件
        /// </summary>
        /// <param name="category">消息类别,默认:INFO</param>
        /// <param name="message">消息文本</param>
        public virtual string Write(string message, string category = null)
        {
            // 扩展点:如果希望在写文件时,同时将消息输出到控制台,可以重写这个方法。

            string line = GetLine(message, category);

            if (line == null)
            {
                return(null);
            }

            if (_lock != null)
            {
                lock ( _lock ) {
                    RetryFile.AppendAllText(_filePath, line, Encoding.UTF8);
                }
            }
            else
            {
                RetryFile.AppendAllText(_filePath, line, Encoding.UTF8);
            }
            return(line);
        }
        public void Test_FormDataCollection_AddObject_File()
        {
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Test_FormDataCollection_AddObject_bytes.txt");

            RetryFile.WriteAllText(filePath, "不能直接重载 -= 运算符", Encoding.UTF8);

            FormDataCollection form = new FormDataCollection();

            form.AddObject("a", new byte[] { 1, 2, 3, 4, 5 });
            form.AddString("b", "xyz中文汉字");
            form.AddObject("c", new FileInfo(filePath));

            form.AddObject("d", new HttpFile {
                FileName = "c:\\test1.dat",
                FileBody = Encoding.UTF8.GetBytes("XML 的输出文件,由编译的源代码文件中的注释填充")
            });



            string md5 = null;

            using (MemoryStream ms = new MemoryStream()) {
                form.WriteToStream(ms, Encoding.UTF8);
                ms.Position = 0;
                byte[] buffer = ms.ToArray();

                string s = Encoding.UTF8.GetString(buffer);
                Console.WriteLine(s);

                // byte 数组太难写断言,所以就计算 MD5 来比较
                byte[] bb = (new MD5CryptoServiceProvider()).ComputeHash(buffer);
                md5 = bb.ToHexString().ToLower();
            }

            Assert.IsTrue(form.HasFile);
            Assert.AreEqual("fbf3628c4d1415ace6e56084d3edcc18", md5);
        }
Beispiel #30
0
        private static void Execute(string dllFile, Assembly asm = null)
        {
            string currentPath = Path.GetDirectoryName(dllFile);

            string newName = Path.GetFileNameWithoutExtension(dllFile) + ".EntityProxy.dll";
            string outFile = Path.Combine(currentPath, newName);

            RetryFile.Delete(outFile);

            if (asm == null)
            {
                asm = Assembly.LoadFrom(dllFile);
            }

            Type[] entityTypes = ProxyBuilder.GetAssemblyEntityTypes(asm);
            if (entityTypes == null || entityTypes.Length == 0)
            {
                return;
            }

            ProxyBuilder.Compile(entityTypes, outFile);

            Console.WriteLine("成功生成实体代理程序集:" + outFile);
        }