Exemple #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);
 }
Exemple #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);
        }
Exemple #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);
        }
Exemple #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);
 }
 /// <summary>
 /// 将文档缓存到全局Cache中
 /// </summary>
 /// <param name="key">缓存的Key名称</param>
 /// <param name="isClone">是否克隆副本存档</param>
 /// <param name="cacheTimeMinutes">存档的分钟数</param>
 public void SaveToCache(string key, bool isClone, double cacheTimeMinutes)
 {
     if (_XmlDocument != null)
     {
         if (!isClone)
         {
             theCache.Set(key, _XmlDocument, cacheTimeMinutes, _FileName);//添加Cache缓存
         }
         else
         {
             theCache.Set(key, GetCloneFrom(_XmlDocument), cacheTimeMinutes, _FileName);//添加Cache缓存Clone
         }
     }
 }
Exemple #6
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);
        }
Exemple #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);
        }
Exemple #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);
        }
Exemple #9
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);
        }
Exemple #10
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);
        }
Exemple #11
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();
        }
Exemple #12
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);
 }
Exemple #13
0
 /// <summary>
 /// 设置全局一级缓存
 /// </summary>
 /// <param name="key">缓存键</param>
 /// <param name="value">缓存值</param>
 /// <param name="minute">缓存时间(单位分钟,可使用小数,默认30分钟)</param>
 /// <returns></returns>
 public static bool CacheSet(string key, object value, double minute = 30)
 {
     if (value == null)
     {
         return(false);
     }
     try
     {
         CacheManage cache = CacheManage.LocalInstance;
         cache.Set(key, value, minute);
         return(true);
     }
     catch (Exception ex)
     {
         Log.WriteLogToTxt(string.Format("更新缓存信息[CacheSet]:{0}", ex.Message));
         return(false);
     }
 }
Exemple #14
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);
        }
        /// <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;
            }
        }
Exemple #16
0
 /// <summary>
 /// 新增手机用户缓存数据 有个更新 没有就新增
 /// </summary>
 /// <param name="KeyNum">键</param>
 /// <param name="Info">值</param>
 /// <param name="CacheMinute">缓存时间</param>
 /// <returns></returns>
 public static bool SetAppCache(string KeyNum, object Info, double CacheMinute = 15)
 {
     if (Info == null || string.IsNullOrEmpty(KeyNum))
     {
         return(false);
     }
     try
     {
         var         _KeyNum = $"AppCache:{KeyNum}";
         CacheManage cache   = CacheManage.LocalInstance;
         cache.Set(_KeyNum, Info, CacheMinute);
         return(true);
     }
     catch (Exception ex)
     {
         Log.WriteLogToTxt(string.Format("新增手机用户缓存数据[SetAppCache]:{0}", ex.Message));
         return(false);
     }
 }
Exemple #17
0
 /// <summary>
 /// start to record sql
 /// <para>开始记录调试信息</para>
 /// <param name="isContainSysSql">是否包含框架内部Sql(默认否)</param>
 /// </summary>
 public static void Start(bool isContainSysSql)
 {
     _Cache.Set(_Key, string.Empty);
     _Cache.Set(_KeyTime, DateTime.Now);
     IsContainSysSql = isContainSysSql;
 }
Exemple #18
0
 /// <summary>
 /// 开始记录调试信息
 /// </summary>
 public static void Start()
 {
     _Cache.Set(_Key, string.Empty);
     _Cache.Set(_KeyTime, DateTime.Now);
 }