Exemplo n.º 1
0
 /// <summary>
 /// 读取文件内容
 /// </summary>
 /// <param name="encoding">指定编码时(会跳过编码自动检测)</param>
 /// <returns></returns>
 public static string ReadAllText(string fileName, int cacheMinutes, Encoding encoding)
 {
     try
     {
         string key = "IOHelper_" + fileName.GetHashCode();
         if (cache.Contains(key))
         {
             return(cache.Get <string>(key));
         }
         if (!File.Exists(fileName))
         {
             return(string.Empty);
         }
         Byte[] buff = null;
         lock (GetLockObj(fileName.Length))
         {
             if (!File.Exists(fileName))//多线程情况处理
             {
                 return(string.Empty);
             }
             buff = File.ReadAllBytes(fileName);
             string result = BytesToText(buff, encoding);
             if (cacheMinutes > 0)
             {
                 cache.Set(key, result, cacheMinutes);
             }
             return(result);
         }
     }
     catch (Exception err)
     {
         Log.WriteLogToTxt(err);
     }
     return(string.Empty);
 }
Exemplo n.º 2
0
        //protected override string ChangedDbConn(string newDbName)
        //{
        //    string dbName = Path.GetFileNameWithoutExtension(DbFilePath);
        //    string newDbPath = DbFilePath.Replace(dbName, newDbName);
        //    if (File.Exists(newDbPath))
        //    {
        //        filePath = string.Empty;
        //        return base.conn.Replace(dbName, newDbName);
        //    }
        //    return conn;
        //}
        private Assembly GetAssembly()
        {
            object ass = _Cache.Get("SQLite_Assembly");

            if (ass == null)
            {
                try
                {
                    ass = Assembly.Load("System.Data.SQLite");
                    _Cache.Set("SQLite_Assembly", ass, 10080);
                }
                catch (Exception err)
                {
                    string errMsg = err.Message;
                    if (errMsg.Contains("v2.0"))
                    {
                        //混合模式程序集是针对“v2.0.50727”版的运行时生成的,在没有配置其他信息的情况下,无法在 4.0 运行时中加载该程序集。
                        //提示用户要增加配置文件
                        errMsg = "You need to add web.config or app.config : <startup useLegacyV2RuntimeActivationPolicy=\"true\"></startup> more info : " + AppConst.NewLine + errMsg;
                    }
                    else if (!System.IO.File.Exists(AppConst.AssemblyPath + "System.Data.SQLite.DLL"))
                    {
                        errMsg = "Can't find the System.Data.SQLite.dll more info : " + AppConst.NewLine + errMsg;
                    }
                    else
                    {
                        errMsg = "You need to choose the right version : x86 or x64. more info : " + AppConst.NewLine + errMsg;
                    }
                    Error.Throw(errMsg);
                }
            }
            return(ass as Assembly);
        }
Exemplo n.º 3
0
        //protected override string ChangedDbConn(string newDbName)
        //{
        //    string dbName = Path.GetFileNameWithoutExtension(DbFilePath);
        //    string newDbPath = DbFilePath.Replace(dbName, newDbName);
        //    if (File.Exists(newDbPath))
        //    {
        //        filePath = string.Empty;
        //        return base.conn.Replace(dbName, newDbName);
        //    }
        //    return conn;
        //}
        private Assembly GetAssembly()
        {
            object ass = _Cache.Get("SQLite_Assembly");

            if (ass == null)
            {
                try
                {
                    ass = Assembly.Load(providerName);
                    _Cache.Set("SQLite_Assembly", ass, 10080);
                }
                catch (Exception err)
                {
                    string errMsg = err.Message;
                    if (!System.IO.File.Exists(AppConst.RunFolderPath + "System.Data.SQLite.DLL"))
                    {
                        errMsg = "Can't find the System.Data.SQLite.dll more info : " + errMsg;
                    }
                    else
                    {
                        errMsg = "You need to choose the right version : x86 or x64. more info : \r\n" + errMsg;
                    }
                    Error.Throw(errMsg);
                }
            }
            return(ass as Assembly);
        }
Exemplo n.º 4
0
 private static string ReadAllText(string fileName, int cacheMinutes, Encoding encoding, int tryCount)
 {
     try
     {
         string key = "IOHelper_" + fileName.GetHashCode();
         if (cache.Contains(key))
         {
             return(cache.Get <string>(key));
         }
         if (!File.Exists(fileName))
         {
             return(string.Empty);
         }
         Byte[] buff = null;
         lock (GetLockObj(fileName.Length))
         {
             if (!File.Exists(fileName))//多线程情况处理
             {
                 return(string.Empty);
             }
             try
             {
                 buff = File.ReadAllBytes(fileName);
             }
             catch (Exception err)
             {
                 if (tryCount > 0)
                 {
                     tryCount--;
                     Thread.Sleep(500 + (3 - tryCount) * 500);
                     ReadAllText(fileName, cacheMinutes, encoding, tryCount);
                 }
                 else
                 {
                     Error.Throw(err.Message);
                 }
             }
             string result = BytesToText(buff, encoding);
             if (cacheMinutes > 0)
             {
                 cache.Set(key, result, cacheMinutes);
             }
             return(result);
         }
     }
     catch (Exception err)
     {
         Log.WriteLogToTxt(err);
     }
     return(string.Empty);
 }
Exemplo n.º 5
0
        private IAop GetFromConfig()
        {
            IAop   aop    = null;
            string aopApp = AppConfig.Aop;

            if (!string.IsNullOrEmpty(aopApp))
            {
                string key = "OuterAop_Instance";
                if (_Cache.Contains(key))
                {
                    aop = _Cache.Get(key) as IAop;
                }
                else
                {
                    #region AOP加载

                    string[] aopItem = aopApp.Split(',');
                    if (aopItem.Length == 2)//完整类名,程序集(dll)名称
                    {
                        if (!_IsLoadCompleted)
                        {
                            try
                            {
                                lock (lockObj)
                                {
                                    if (_IsLoadCompleted)
                                    {
                                        return(GetFromConfig());//重新去缓存里拿。
                                    }
                                    _IsLoadCompleted = true;
                                    System.Reflection.Assembly ass = System.Reflection.Assembly.Load(aopItem[1]);
                                    if (ass != null)
                                    {
                                        object instance = ass.CreateInstance(aopItem[0]);
                                        if (instance != null)
                                        {
                                            _Cache.Set(key, instance, 1440, AppConst.AssemblyPath + aopItem[1].Replace(".dll", "") + ".dll");
                                            aop = instance as IAop;
                                            aop.OnLoad();
                                        }
                                    }
                                }
                            }
                            catch (Exception err)
                            {
                                string errMsg = err.Message + "--Web.config need add a config item,for example:<add key=\"Aop\" value=\"Web.Aop.AopAction,Aop\" />(value format : ClassFullName,AssemblyName) ";
                                Error.Throw(errMsg);
                            }
                        }
                    }
                    #endregion
                }
            }
            if (aop != null)
            {
                IAop cloneAop = aop.Clone();
                return(cloneAop == null ? aop : cloneAop);
            }
            return(null);
        }
Exemplo n.º 6
0
        public static bool IsKeyInHtml(string objName)
        {
            CacheManage cache = CacheManage.LocalInstance;

            string path = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.UrlReferrer.LocalPath);
            string has  = path.GetHashCode().ToString();
            string html = string.Empty;

            if (cache.Contains(has))
            {
                html = cache.Get <string>(has);
            }
            else if (File.Exists(path))
            {
                html = File.ReadAllText(path);
                cache.Set(has, html, 0, path);
            }
            if (!string.IsNullOrEmpty(html))
            {
                //检测文件中是否有对应的关键字:
                if (html.Contains("\"" + objName + "\"") || html.Contains("'" + objName + "'"))
                {
                    return(true);
                }
            }
            return(false);
        }
Exemplo n.º 7
0
        protected override DbProviderFactory GetFactory()
        {
            //return DbProviderFactories.GetFactory(DllName);
            string key     = "DB2Client_Factory";
            object factory = _Cache.Get(key);

            if (factory == null)
            {
                Assembly ass = GetAssembly();
                Type     t   = ass.GetType(DllName + ".DB2Factory");
                if (t != null)
                {
                    FieldInfo fi = t.GetField("Instance", BindingFlags.Public | BindingFlags.Static);
                    if (fi != null)
                    {
                        factory = fi.GetValue(null);
                    }
                }
                //factory = ass.CreateInstance(DllName + ".DB2Factory.Instance");
                if (factory == null)
                {
                    throw new System.Exception("Can't Create DB2Factory in " + DllName + ".dll");
                }
                else
                {
                    _Cache.Set(key, factory, 10080);
                }
            }
            return(factory as DbProviderFactory);
        }
Exemplo n.º 8
0
        private static bool IsObjInHtml(string objName, string path)
        {
            if (string.IsNullOrEmpty(objName))
            {
                return(false);
            }
            objName = objName.Trim('_', ' ');
            CacheManage cache = CacheManage.LocalInstance;
            string      has   = path.GetHashCode().ToString();
            string      html  = string.Empty;

            if (cache.Contains(has))
            {
                html = cache.Get <string>(has);
            }
            else if (File.Exists(path))
            {
                html = File.ReadAllText(path);
                cache.Set(has, html, 0, path);
            }
            if (!string.IsNullOrEmpty(html))
            {
                //检测文件中是否有对应的关键字:
                if (html.Contains(objName + "\"") || html.Contains(objName + "'"))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 9
0
        private IAop GetFromConfig()
        {
            IAop aop = null;

            string aopApp = AppConfig.Aop;

            if (!string.IsNullOrEmpty(aopApp))
            {
                if (_Cache.Contains("Aop_Instance"))
                {
                    aop = _Cache.Get("Aop_Instance") as IAop;
                }
                else
                {
                    #region AOP加载

                    string[] aopItem = aopApp.Split(',');
                    if (aopItem.Length == 2)//完整类名,程序集(dll)名称
                    {
                        try
                        {
                            System.Reflection.Assembly ass = System.Reflection.Assembly.Load(aopItem[1]);
                            if (ass != null)
                            {
                                object instance = ass.CreateInstance(aopItem[0]);
                                if (instance != null)
                                {
                                    _Cache.Add("Aop_Instance", instance, AppConst.RunFolderPath + aopItem[1].Replace(".dll", "") + ".dll", 1440);
                                    aop = instance as IAop;
                                    if (!_CallOnLoad)
                                    {
                                        lock (lockObj)
                                        {
                                            if (!_CallOnLoad)
                                            {
                                                _CallOnLoad = true;
                                                aop.OnLoad();
                                            }
                                        }
                                    }
                                    return(aop);
                                }
                            }
                        }
                        catch (Exception err)
                        {
                            string errMsg = err.Message + "--Web.config need add a config item,for example:<add key=\"Aop\" value=\"Web.Aop.AopAction,Aop\" />(value format:namespace.Classname,Assembly name) ";
                            Error.Throw(errMsg);
                        }
                    }
                    #endregion
                }
            }
            if (aop != null)
            {
                return(aop.Clone());
            }
            return(null);
        }
Exemplo n.º 10
0
 /// <summary>
 /// 从缓存中加载html
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public bool LoadFromCache(string key)
 {
     if (theCache.Contains(key))//缓存中存在对应值是key的对象
     {
         if (_IsNoClone)
         {
             _XmlDocument = theCache.Get(key) as XmlDocument;
         }
         else
         {
             _XmlDocument = GetCloneFrom(theCache.Get(key) as XmlDocument);
         }
         _IsLoadFromCache = true;
         return(true);
     }
     else
     {
         return(false);
     }
 }
Exemplo n.º 11
0
        MDataRow GetUser()
        {
            string key = "WF_User_" + UserID;

            if (cache.Contains(key))
            {
                return(cache.Get <MDataRow>(key));
            }
            else
            {
                using (MAction action = new MAction(U_AriesEnum.Sys_User))
                {
                    if (action.Fill(UserID))
                    {
                        cache.Set(key, action.Data, 1);
                        return(action.Data);
                    }
                }
            }
            return(null);
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            //说明:如果你确定缓存一定是在本机,使用:CacheManage cache= CacheManage.LocalInstance
            //如果只是缓存一般数据,将来有可能启用分布式时,用:CacheManage cache = CacheManage.Instance;

            //比如框架对一些表架构的元数据的缓存,用的是本机(速度快):CacheManage.LocalInstance
            //而框架对于自动缓存(表的数据),用的是:CacheManage.Instance (将来随便分布式启用分散到各缓存服务器)

            AppConfig.Cache.MemCacheServers = "127.0.0.1:11211";//配置启用MemCache,127.0.0.1:11212
            CacheManage cache = CacheManage.Instance;

            if (!cache.Contains("a1"))
            {
                cache.Set("a1", "a1", 0.1);
            }
            cache.Set("a2", "a2", 0.5);//存在则更新,不存在则添加。
            cache.Set("a3", "a3", 2.2);
            cache.Set("a0", "a0");
            cache.Set("table", cache.CacheInfo);

            Console.WriteLine(cache.Get <string>("a0"));
            Console.WriteLine(cache.Get <string>("a1"));
            Console.WriteLine(cache.Get <string>("a2"));
            Console.WriteLine(cache.Get <string>("a3"));
            MDataTable table = cache.Get <MDataTable>("table");

            if (table != null)
            {
                Console.WriteLine(table.Rows.Count);
            }

            if (cache.CacheType == CacheType.LocalCache)//只能拿到本机的信息
            {
                Console.WriteLine("缓存数:" + table.Rows.Count);
                Console.WriteLine("总内存(M):" + GC.GetTotalMemory(false) / 1024); // 感觉拿到的值不太靠谱。
            }
            cache.Remove("a0");                                                 //单个移除
            cache.Clear();                                                      //清除所有缓存
            Console.Read();
        }
Exemplo n.º 13
0
 /// <summary>
 /// 获取全局缓存数据
 /// </summary>
 /// <param name="key">键</param>
 /// <returns></returns>
 public static object CacheGet(string key)
 {
     try
     {
         CacheManage cache = CacheManage.LocalInstance;
         var         value = cache.Get(key);
         return(value);
     }
     catch (Exception ex)
     {
         Log.WriteLogToTxt(string.Format("更新用户缓存信息[CacheGet]:{0}", ex.Message));
         return(false);
     }
 }
Exemplo n.º 14
0
 /// <summary>
 /// 获取用户缓存数据
 /// </summary>
 /// <param name="KeyNum">键</param>
 /// <returns></returns>
 public static object GetCache(string KeyNum)
 {
     try
     {
         var         _KeyNum = string.Concat(KeyNum, GetIdentityKey);
         CacheManage cache   = CacheManage.LocalInstance;
         var         value   = cache.Get(_KeyNum);
         return(value);
     }
     catch (Exception ex)
     {
         Log.WriteLogToTxt(string.Format("更新用户缓存信息[UpdateUserInfoCache]:{0}", ex.Message));
         return(false);
     }
 }
Exemplo n.º 15
0
 /// <summary>
 /// 获取手机用户缓存数据
 /// </summary>
 /// <param name="KeyNum">键</param>
 /// <returns></returns>
 public static object GetAppCache(string KeyNum)
 {
     try
     {
         var         _KeyNum = $"AppCache:{KeyNum}";
         CacheManage cache   = CacheManage.LocalInstance;
         var         value   = cache.Get(_KeyNum);
         return(value);
     }
     catch (Exception ex)
     {
         Log.WriteLogToTxt(string.Format("获取手机用户缓存数据[GetAppCache]:{0}", ex.Message));
         return(false);
     }
 }
Exemplo n.º 16
0
        protected override DbProviderFactory GetFactory()
        {
            object factory = _Cache.Get("MySqlClient_Factory");

            if (factory == null)
            {
                Assembly ass = GetAssembly();
                factory = ass.CreateInstance("MySql.Data.MySqlClient.MySqlClientFactory");
                if (factory == null)
                {
                    throw new System.Exception("Can't Create  MySqlClientFactory in MySql.Data.dll");
                }
                else
                {
                    _Cache.Set("MySqlClient_Factory", factory, 10080);
                }
            }
            return(factory as DbProviderFactory);
        }
Exemplo n.º 17
0
        protected override DbProviderFactory GetFactory(string providerName)
        {
            object factory = _Cache.Get("MySqlClient_Factory");

            if (factory == null)
            {
                Assembly ass = GetAssembly();
                factory = ass.CreateInstance("MySql.Data.MySqlClient.MySqlClientFactory");
                if (factory == null)
                {
                    throw new System.Exception("Can't Create  MySqlClientFactory in MySql.Data.dll");
                }
                else
                {
                    _Cache.Add("MySqlClient_Factory", factory, null, 10080, System.Web.Caching.CacheItemPriority.High);
                }
            }
            return(factory as DbProviderFactory);
        }
Exemplo n.º 18
0
        /// <summary>
        /// 检测用户
        /// </summary>
        /// <param name="token"></param>
        public void IsCheckUser(string token)
        {
            this.userModel = null;
            string userGuid = CommonHelp.EncryptOrDecrypt.Decrypt(token);

            if (string.IsNullOrEmpty(userGuid))
            {
                UrlToLogin();
                return;
            }
            if (userModel == null)
            {
                var cacheUserList = cache.Get <List <UserModel> >("cacheUser_Manager");
                #region 重新获取缓存数据
                if (cacheUserList == null || cacheUserList.Count <= 0)
                {
                    //重新获取缓存数据
                    using (MAction m = new MAction("C_UserManager"))
                    {
                        cacheUserList = m.Select().ToList <UserModel>();
                        cache.Set("cacheUser_Manager", cacheUserList, 120);
                    }
                }
                #endregion

                var userInfo = cacheUserList.FirstOrDefault(a => a.UserGuid == userGuid);
                if (userInfo != null)
                {
                    userModel = userInfo;
                    CommonHelp.ComHelper.SavaCookie(token, "admin_UserToken");
                }
                else
                {
                    UrlToLogin();
                    return;
                }
            }
            else
            {
                UrlToLogin();
                return;
            }
        }
Exemplo n.º 19
0
 /// <summary>
 /// 根据操作标识和用户标识检测是否没超过限制次数
 /// 默认1440分钟,1次,使用URL和GetIdentityKey作为Key
 /// 如:CommonContext.VisitCheck(1, 1440, "HitIndustry" + id, userId);
 /// </summary>
 /// <param name="minute">限制分钟数,默认1440分钟(24小时)</param>
 /// <param name="limit">限制次数,默认1</param>
 /// <param name="mark">操作标识,默认URL,可指定为:需求名+Id、产品名+Id、设计师名+Id等</param>
 /// <param name="userKey">用户标识,默认GetIdentityKey,可指定为:用户名或用户ID等</param>
 /// <returns></returns>
 public static bool VisitCheck(double minute = 1440, int limit = 1, object mark = null, object userKey = null)
 {
     if (limit > 0 && minute > 0)
     {
         mark    = mark ?? HttpContext.Current.Request.Url;
         userKey = userKey ?? GetIdentityKey;
         string      key   = "VisitCheck:" + MD5Encrupt($"{userKey}{mark}");
         CacheManage cache = CacheManage.LocalInstance;
         var         value = cache.Get(key);
         if (value != null)//已经访问过
         {
             try
             {
                 int times = (int)value;
                 if (times < limit) //未超过限制次数
                 {
                     cache.Set(key, times + 1, minute);
                     return(true);
                 }
                 else //超过次数
                 {
                     return(false);
                 }
             }
             catch (Exception)
             {
                 return(true);
             }
         }
         else //未访问过
         {
             cache.Set(key, 1, minute);
         }
     }
     return(true);
 }
Exemplo n.º 20
0
        internal static void Add(string sql)
        {
            object sqlObj = _Cache.Get(_Key);

            _Cache.Set(_Key, sqlObj + sql);
        }
Exemplo n.º 21
0
 internal static bool Save(string fileName, string text, bool isAppend, bool writeLogOnError, Encoding encode, int tryCount)
 {
     try
     {
         //System.Text.Encoding.UTF8
         string folder = Path.GetDirectoryName(fileName);
         if (!Directory.Exists(folder))
         {
             Directory.CreateDirectory(folder);
         }
         string key = "IOHelper_Save_" + fileName.GetHashCode();
         if (cache.Contains(key))
         {
             encode = cache.Get <Encoding>(key);
         }
         else if (File.Exists(fileName))
         {
             TextEncodingDetect detect       = new TextEncodingDetect();
             Encoding           detectEncode = detect.GetEncoding(File.ReadAllBytes(fileName), encode);
             if (detectEncode != Encoding.ASCII)
             {
                 encode = detectEncode;
             }
             cache.Set(key, encode, 60);
         }
         lock (GetLockObj(fileName.Length))
         {
             try
             {
                 using (StreamWriter writer = new StreamWriter(fileName, isAppend, encode))
                 {
                     if (!isAppend && fileName.EndsWith(".txt"))
                     {
                         //写入bom头
                     }
                     writer.Write(text);
                 }
             }
             catch (Exception err)
             {
                 if (tryCount > 0)
                 {
                     tryCount--;
                     Thread.Sleep(500 + (3 - tryCount) * 500);
                     Save(fileName, text, isAppend, writeLogOnError, encode, tryCount);
                 }
                 else
                 {
                     Error.Throw(err.Message);
                 }
             }
         }
         return(true);
     }
     catch (Exception err)
     {
         if (tryCount == 3) // 避免死循环。
         {
             if (writeLogOnError)
             {
                 Log.Write(err, LogType.Error);
             }
             else
             {
                 Error.Throw("IOHelper.Save() : " + err.Message);
             }
         }
     }
     return(false);
 }