Esempio n. 1
0
        public LoginViewModel(INavigationService navigateService, GithubApiService ghservice, INotificationController notController, ICacheManager cache)
        {
            IsLogin = false;
            NavigationService = navigateService;
            GHService = ghservice;
            NotificationController = notController;
            _cache = cache;

            _loginCommand = new DelegateCommand(() =>
            {

                NotificationController.SplashScreen.IsVisible = true;
                cache.Add("username", User);
                cache.Add("password", Password);
                GHService.UseCredentials(User, Password);
                NavigationService.Navigate(AppPages.MainPage);
            });
        }
    public IList <TEntity> GetCachedItems <TEntity>(string name, object source) where TEntity : class
    {
        var data = cacheManager?.GetChache <TEntity>();

        if (data == null)
        {
            data = (dataRetrievalFuncs[new Tuple <Type, string>(typeof(TEntity), name)](source) as IEnumerable <TEntity>).ToList();
            cacheManager?.Add(data, "Maps", 20);
        }
        return(data);
    }
        void CacheManagerTest(ICacheManager mgr)
        {
            string key = "key1";
            string val = "value123";

            Assert.IsNull(mgr.GetData(key));

            mgr.Add(key, val);

            string result = (string)mgr.GetData(key);
            Assert.AreEqual(val, result, "result");
        }
        public void Thread_Update(ICacheManager<object> cache)
        {
            using (cache)
            {
                var key = Guid.NewGuid().ToString();
                var handleInfo = string.Join("\nh: ", cache.CacheHandles.Select(p => p.Configuration.Name + ":" + p.GetType().Name));

                cache.Remove(key);
                cache.Add(key, new RaceConditionTestElement() { Counter = 0 });
                int numThreads = 5;
                int iterations = 10;
                int numInnerIterations = 10;
                int countCasModifyCalls = 0;

                // act
                ThreadTestHelper.Run(
                    () =>
                    {
                        for (int i = 0; i < numInnerIterations; i++)
                        {
                            cache.Update(key, (value) =>
                            {
                                var val = (RaceConditionTestElement)value;
                                val.Counter++;
                                Interlocked.Increment(ref countCasModifyCalls);
                                return value;
                            });
                        }
                    },
                    numThreads,
                    iterations);

                // assert
                Thread.Sleep(10);
                for (var i = 0; i < cache.CacheHandles.Count(); i++)
                {
                    var handle = cache.CacheHandles.ElementAt(i);
                    var result = (RaceConditionTestElement)handle.Get(key);
                    if (i < cache.CacheHandles.Count() - 1)
                    {
                        // only the last one should have the item
                        result.Should().BeNull();
                    }
                    else
                    {
                        result.Should().NotBeNull(handleInfo + "\ncurrent: " + handle.Configuration.Name + ":" + handle.GetType().Name);
                        result.Counter.Should().Be(numThreads * numInnerIterations * iterations, handleInfo + "\ncounter should be exactly the expected value.");
                        countCasModifyCalls.Should().BeGreaterOrEqualTo((int)result.Counter, handleInfo + "\nexpecting no (if synced) or some version collisions.");
                    }
                }
            }
        }
Esempio n. 5
0
    public IList <TEntity> GetCachedItems <TEntity>(string name, object provider, int lifeTime = 20)
        where TEntity : class
    {
        var data = cacheManager?.Get <TEntity>(name);

        if (data == null)
        {
            data = (dataRetrievalFuncs[new Tuple <Type, string>(
                                           typeof(TEntity), name)](provider) as IEnumerable <TEntity>)
                   .ToList();
            cacheManager?.Add(data, name, lifeTime);
        }
        return(data);
    }
    public IList <TEntity> GetCachedItems <TEntity>(string name, object provider, int lifeTime = 20) where TEntity : class
    {
        var data = cacheManager?.Get <TEntity>(name);

        if (data == null)
        {
            if (dataRetrievalFuncs.TryGetValue(
                    new Key(name, typeof(TEntity), provider.GetType()), out var func))
            {
                data = (func(provider) as IEnumerable <TEntity>)?.ToList();
                cacheManager?.Add(data, name, lifeTime);
            }
            else
            {
                throw new InvalidOperationException("Specified cache is not registered.");
            }
        }
        return(data);
    }
        public List<Product> GetProductData(out string cacheStatus)
        {
            cacheProductData = EnterpriseLibraryContainer.Current.GetInstance<ICacheManager>();
            listProducts = (List<Product>)cacheProductData["ProductDataCache"];
            cacheStatus = "Employee Information is Retrived from Cache";
            LetsShopImplementation ls = new LetsShopImplementation();
            CacheFlag = true;
            if (listProducts == null)
            {
              //Database _db = EnterpriseLibraryContainer.Current.GetInstance<Database>("LetsShopConnection");
              //listProducts =

                LetsShopImplementation ls = new LetsShopImplementation();
                listProducts = ls.GetProducts();
                AbsoluteTime CacheExpirationTime = new AbsoluteTime(new TimeSpan(1, 0, 0));
                cacheProductData.Add("ProductDataCache", listProducts, CacheItemPriority.High, null, new ICacheItemExpiration[] { CacheExpirationTime });
                cacheStatus = "Product Info is Added in cache";
                CacheFlag = false;
            }
            return listProducts;
        }
        public static void LoadAttribute(List<string> BusinessDll, ICacheManager cache, string pluginName)
        {
            List<WebServicesAttributeInfo> webserviceList = new List<WebServicesAttributeInfo>();

            for (int k = 0; k < BusinessDll.Count; k++)
            {
                System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(BusinessDll[k]);
                Type[] types = assembly.GetTypes();
                for (int i = 0; i < types.Length; i++)
                {
                    WebServiceAttribute[] webS = ((WebServiceAttribute[])types[i].GetCustomAttributes(typeof(WebServiceAttribute), true));
                    if (webS.Length > 0)
                    {
                        WebServicesAttributeInfo wsa = new WebServicesAttributeInfo();
                        wsa.ServiceName = types[i].Name;
                        wsa.ServiceType = types[i];
                        webserviceList.Add(wsa);
                    }
                }
            }

            cache.Add(pluginName+"@"+GetCacheKey(), webserviceList);
        }
        public void Thread_RandomAccess(ICacheManager<object> cache)
        {
            if (cache == null)
            {
                throw new ArgumentNullException("cache");
            }

            foreach (var handle in cache.CacheHandles)
            {
                Trace.TraceInformation("Using handle {0}", handle.GetType());
            }

            var blob = new byte[1024];

            using (cache)
            {
                Action test = () =>
                {
                    var hits = 0;
                    var misses = 0;
                    var tId = Thread.CurrentThread.ManagedThreadId;

                    try
                    {
                        for (var r = 0; r < 5; r++)
                        {
                            for (int i = 0; i < 5; i++)
                            {
                                string key = "key" + i;
                                object value = blob.Clone();
                                string region = "region" + r;

                                CacheItem<object> item = null;
                                if (r % 2 == 0)
                                {
                                    item = new CacheItem<object>(key, value, ExpirationMode.Sliding, TimeSpan.FromMilliseconds(10));
                                }
                                else
                                {
                                    item = new CacheItem<object>(key, value, region, ExpirationMode.Absolute, TimeSpan.FromMilliseconds(10));
                                }

                                cache.Put(item);
                                if (!cache.Add(item))
                                {
                                    cache.Put(item);
                                }

                                var result = cache.Get(key);
                                if (result == null)
                                {
                                    misses++;
                                }
                                else
                                {
                                    hits++;
                                }

                                if (!cache.Remove(key))
                                {
                                    misses++;
                                }
                                else
                                {
                                    hits++;
                                }

                                Thread.Sleep(0);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("{1} Error: {0}", ex.Message, tId);
                        throw;
                    }

                    Trace.TraceInformation("Hits: {0}, Misses: {1}", hits, misses);
                };

                ThreadTestHelper.Run(test, 2, 1);
            }
        }
Esempio n. 10
0
        public static void CacheThreadTest(ICacheManager <string> cache, int seed)
        {
            cache.Clear();

            var threads          = 10;
            var numItems         = 1000;
            var eventAddCount    = 0;
            var eventRemoveCount = 0;
            var eventGetCount    = 0;

            cache.OnAdd    += (sender, args) => { Interlocked.Increment(ref eventAddCount); };
            cache.OnRemove += (sender, args) => { Interlocked.Increment(ref eventRemoveCount); };
            cache.OnGet    += (sender, args) => { Interlocked.Increment(ref eventGetCount); };

            Func <int, string> keyGet = (index) => "key" + ((index + 1) * seed);

            Action test = () =>
            {
                for (int i = 0; i < numItems; i++)
                {
                    cache.Add(keyGet(i), i.ToString());
                }

                for (int i = 0; i < numItems; i++)
                {
                    if (i % 10 == 0)
                    {
                        cache.Remove(keyGet(i));
                    }
                }

                for (int i = 0; i < numItems; i++)
                {
                    string val = cache.Get(keyGet(i));
                }
            };

            Parallel.Invoke(new ParallelOptions()
            {
                MaxDegreeOfParallelism = 8
            }, Enumerable.Repeat(test, threads).ToArray());

            foreach (var handle in cache.CacheHandles)
            {
                var stats = handle.Stats;
                Console.WriteLine(string.Format(
                                      "Items: {0}, Hits: {1}, Miss: {2}, Remove: {3}, ClearRegion: {4}, Clear: {5}, Adds: {6}, Puts: {7}, Gets: {8}",
                                      stats.GetStatistic(CacheStatsCounterType.Items),
                                      stats.GetStatistic(CacheStatsCounterType.Hits),
                                      stats.GetStatistic(CacheStatsCounterType.Misses),
                                      stats.GetStatistic(CacheStatsCounterType.RemoveCalls),
                                      stats.GetStatistic(CacheStatsCounterType.ClearRegionCalls),
                                      stats.GetStatistic(CacheStatsCounterType.ClearCalls),
                                      stats.GetStatistic(CacheStatsCounterType.AddCalls),
                                      stats.GetStatistic(CacheStatsCounterType.PutCalls),
                                      stats.GetStatistic(CacheStatsCounterType.GetCalls)));
            }

            Console.WriteLine(string.Format(
                                  "Event - Adds {0} Hits {1} Removes {2}",
                                  eventAddCount,
                                  eventGetCount,
                                  eventRemoveCount));
        }
Esempio n. 11
0
        public void Add(string key, object data, int cacheTime)
        {
            var cachItem = new CacheItem <object>(key, data, ExpirationMode.Absolute, TimeSpan.FromMinutes(cacheTime));

            Cache.Add(cachItem);
        }
Esempio n. 12
0
 public bool Add(string key, object value)
 {
     return(_cacheManager.Add(key, value));
 }
Esempio n. 13
0
 public static void Add(this ICacheManager cache, string key, object item)
 {
     cache.Add(key, item, 0);
 }
 /// <summary>
 /// 将对象添加到缓存中,对象将不会自动失效,除非你显示地从缓存中移除对象
 /// </summary>
 /// <param name="cacheClassification">缓存的类别</param>
 /// <param name="cacheKey">缓存键</param>
 /// <param name="cacheObject">缓存对象</param>
 public static void Add(string cacheClassification, string cacheKey, object cacheObject)
 {
     innerCacheManager.Add(getCacheKey(cacheClassification, cacheKey),
                           cacheObject);
 }
        public void Thread_RandomAccess(ICacheManager <object> cache)
        {
            NotNull(cache, nameof(cache));

            foreach (var handle in cache.CacheHandles)
            {
                Trace.TraceInformation("Using handle {0}", handle.GetType());
            }

            var blob = new byte[1024];

            using (cache)
            {
                Action test = () =>
                {
                    var hits   = 0;
                    var misses = 0;
                    var tId    = Thread.CurrentThread.ManagedThreadId;

                    try
                    {
                        for (var r = 0; r < 5; r++)
                        {
                            for (int i = 0; i < 5; i++)
                            {
                                string key    = "key" + i;
                                object value  = blob.Clone();
                                string region = "region" + r;

                                CacheItem <object> item = null;
                                if (r % 2 == 0)
                                {
                                    item = new CacheItem <object>(key, value, ExpirationMode.Sliding, TimeSpan.FromMilliseconds(10));
                                }
                                else
                                {
                                    item = new CacheItem <object>(key, region, value, ExpirationMode.Absolute, TimeSpan.FromMilliseconds(10));
                                }

                                cache.Put(item);
                                if (!cache.Add(item))
                                {
                                    cache.Put(item);
                                }

                                var result = cache.Get(key);
                                if (result == null)
                                {
                                    misses++;
                                }
                                else
                                {
                                    hits++;
                                }

                                if (!cache.Remove(key))
                                {
                                    misses++;
                                }
                                else
                                {
                                    hits++;
                                }

                                Thread.Sleep(0);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("{1} Error: {0}", ex.Message, tId);
                        throw;
                    }

                    Trace.TraceInformation("Hits: {0}, Misses: {1}", hits, misses);
                };

                ThreadTestHelper.Run(test, 2, 1);
            }
        }
Esempio n. 16
0
 public void Add <T>(T addObject, string key, int seconds)
 {
     _cacheManager.Add(key, addObject, CacheItemPriority.High, null, new AbsoluteTime(TimeSpan.FromSeconds(seconds)));
 }
Esempio n. 17
0
        private IEnumerable <ParametroSistema> GetParametros()
        {
            //Cache
            var parametros = _cacheManager.GetData(ConstantesCache.CACHE_PARAMETROS_SISTEMA) as IEnumerable <ParametroSistema>;

            if (parametros == null)
            {
                //1. Recuperar todos los parametros del sistema asociada.

                //AppSettings. La clave es formada por

                //CodigoSistema:TipoParametro:NombreParametro

                //TipoParametro: Numero = 1,  Cadena = 2, Booleano = 3, Listado = 4, Fecha = 5
                //<add key = "CodigoSistema:1:SizeGrid" value = "20" />
                //<add key = "CodigoSistema:2:NombreAplicacion" value = "NombreAplicacion" />
                //<add key = "CodigoSistema:3:VisualizarMenu" value = "true" />
                //<add key = "CodigoSistema:4:Opciones" value = "Valor1,Valor2,Valor3,Valor4" />
                //<add key = "CodigoSistema:5:FechaInicio" value = "20/01/2016" />



                string[] appSettingsSystem = ConfigurationManager.AppSettings.AllKeys
                                             .Where(key => key.StartsWith(string.Format("Sistema:")))
                                             .Select(key => key)
                                             .ToArray();

                char[] delimiterChars = { ':' };



                var listParam = new List <ParametroSistema>();
                var random    = new Random();
                foreach (var key in appSettingsSystem)
                {
                    var param = new ParametroSistema();

                    string[] parts = key.Split(delimiterChars);

                    var tipoParametro = TipoParametro.Cadena;

                    if (!(parts.Count() == 2 || parts.Count() == 3))
                    {
                        string error = string.Format("La calve [{0}], no tiene el formato correcto CodigoSistema:TipoParametro:NombreParametro", key);
                        throw new GenericException(error, error);
                    }

                    if (parts.Count() == 3)
                    {
                        int tipoParametroInt = int.Parse(parts[1]);
                        tipoParametro = (TipoParametro)tipoParametroInt;
                    }


                    param.Codigo = parts[parts.Length - 1];
                    param.Valor  = ConfigurationManager.AppSettings[key];

                    param.CreatorUserId        = 1;
                    param.CreationTime         = DateTime.Now;
                    param.LastModificationTime = DateTime.Now;
                    param.Descripcion          = string.Empty;
                    param.Categoria            = CategoriaParametro.General;
                    param.EsEditable           = false;
                    param.Id            = random.Next();
                    param.Nombre        = key;
                    param.TieneOpciones = false;
                    param.Tipo          = tipoParametro;

                    listParam.Add(param);
                }

                parametros = listParam.ToList();
                _cacheManager.Add(ConstantesCache.CACHE_PARAMETROS_SISTEMA, parametros);
            }
            return(parametros);
        }
Esempio n. 18
0
 /// <summary>
 /// 设置当前应用程序指定CacheKey的Cache值
 /// </summary>
 /// <param name="CacheKey">用于引用该对象的缓存键。</param>
 /// <param name="objObject">要插入缓存中的对象。</param>
 public static bool AddCache(string CacheKey, object objObject)
 {
     return(objCache.Add(CacheKey, objObject));
 }
Esempio n. 19
0
        protected void Page_Load(object sender, EventArgs e)
        {
            #region Oracle
            var db = DatabaseFactory.CreateDatabase();

            DataSet ds = db.ExecuteDataSet(CommandType.Text, "select * from users");

            IDataReader dr = db.ExecuteReader(CommandType.Text, "select *from users");

            while (dr.Read())
            {
                string userid = dr["userid"].ToString();
            }

            //Accessor进行RowMapper来直接为实体赋值

            DataAccessor <Users> studentAccessor = db.CreateSqlStringAccessor("select * from users",
                                                                              MapBuilder <Users> .MapAllProperties().Build());

            studentAccessor = db.CreateSqlStringAccessor("select * from users",
                                                         MapBuilder <Users> .MapAllProperties().
                                                         Map(p => p.USERID).ToColumn("USERID").
                                                         Map(p => p.USERNAME).ToColumn("USERNAME").
                                                         Map(p => p.TITLE).WithFunc(f => f["TITLE"].ToString().ToUpper()).//将学员名称转换为大写
                                                         Map(p => p.SEX).ToColumn("SEX").
                                                         Map(p => p.LASTUPDATE).ToColumn("LASTUPDATE").
                                                         Map(p => p.EMAIL).ToColumn("EMAIL").
                                                         Map(p => p.STATUS).ToColumn("STATUS").
                                                         Build()
                                                         );

            var list = studentAccessor.Execute().ToList();

            #endregion

            #region ODP.NET Oracle

            /*
             * var odpdb = DatabaseFactory.CreateDatabase("ODPConnStr");
             *
             * ds = db.ExecuteDataSet(CommandType.Text, "select * from users");
             *
             * dr = db.ExecuteReader(CommandType.Text, "select *from users");
             *
             * while (dr.Read())
             * {
             *  string userid = dr["userid"].ToString();
             * }
             */
            #endregion



            #region Sql Server

            var msdb = DatabaseFactory.CreateDatabase("MsSqlConnStr");

            ds = msdb.ExecuteDataSet(CommandType.Text, "select * from emp");

            dr = msdb.ExecuteReader(CommandType.Text, "select * from emp");

            while (dr.Read())
            {
                string empno = dr["empno"].ToString();
            }


            ds = msdb.ExecuteDataSet(CommandType.Text, "select * from Demo");

            #endregion



            #region Mysql

            var mysqldb = DatabaseFactory.CreateDatabase("MySqlConnStr");


            string deleteSql = @"delete from Demo";

            int result = mysqldb.ExecuteNonQuery(CommandType.Text, deleteSql);


            string insertSql = @"INSERT INTO `Demo`(`Name`, `Age`, `Money`, `Sex`, `AddTime`, `Contonts`) VALUES 
                ('mas',18,25.45,1,'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "','message')";

            result = mysqldb.ExecuteNonQuery(CommandType.Text, insertSql);

            ds = mysqldb.ExecuteDataSet(CommandType.Text, "select * from Demo");

            dr = mysqldb.ExecuteReader(CommandType.Text, "select * from Demo");

            while (dr.Read())
            {
                string Name = dr["Name"].ToString();
            }


            DataTable dt = ds.Tables[0];

            for (int i = 0; i < 10000; i++)
            {
                DataRow _dr = dt.NewRow();
                _dr[1] = "mas" + i;
                _dr[2] = 18;
                _dr[3] = 25.45;
                _dr[4] = 1;
                _dr[5] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                _dr[6] = "message";
                dt.Rows.Add(_dr);
            }

            DbCommand insertCommand = mysqldb.GetSqlStringCommand("INSERT INTO `Demo`(`Name`, `Age`, `Money`, `Sex`, `AddTime`, `Contonts`) VALUES (@Name,@Age,@Money,@Sex,@AddTime,@Contonts)");

            mysqldb.AddInParameter(insertCommand, "Name", DbType.String, "Name", DataRowVersion.Current);
            mysqldb.AddInParameter(insertCommand, "Age", DbType.Int32, "Age", DataRowVersion.Current);
            mysqldb.AddInParameter(insertCommand, "Money", DbType.Decimal, "Money", DataRowVersion.Current);
            mysqldb.AddInParameter(insertCommand, "Sex", DbType.UInt64, "Sex", DataRowVersion.Current);
            mysqldb.AddInParameter(insertCommand, "AddTime", DbType.DateTime, "AddTime", DataRowVersion.Current);
            mysqldb.AddInParameter(insertCommand, "Contonts", DbType.String, "Contonts", DataRowVersion.Current);


            int result_affect = mysqldb.UpdateDataSet(ds, "Table", insertCommand, null, null, UpdateBehavior.Transactional);


            ds = mysqldb.ExecuteDataSet(CommandType.Text, "select * from Demo");

            #endregion



            #region 通过构造函数直接创建企业库对象

            SqlDatabase sqldb = new SqlDatabase(@"Data Source=AX-EC-G01\SQL2008R2;Initial Catalog=UC7;Integrated Security=True;");

            sqldb.ExecuteDataSet(CommandType.Text, "select * from emp");

            #endregion



            #region 企业库的缓存模块

            ICacheManager goodsCache = CacheFactory.GetCacheManager();
            goodsCache.Add("name", "mas");
            goodsCache.Add("age", 18, CacheItemPriority.High, null, new SlidingTime(TimeSpan.FromSeconds(10)));


            string name = goodsCache.GetData("name").ToString();
            goodsCache.Remove("name");

            #endregion


            #region 日志模块

            LogEntry log = new LogEntry();
            log.EventId  = 100;
            log.Priority = 3;
            log.Message  = "information message";
            log.Categories.Add("C#学习");
            log.Categories.Add("Microsoft Enterprise Library学习");

            Logger.Write(log);

            #endregion
        }
Esempio n. 20
0
 public static void Add(string key, object value)
 {
     CacheManagerInstance.Add(key, value);
 }
Esempio n. 21
0
 public void SetCache(string key, string value)
 {
     _cache.Add(key, value);
 }
Esempio n. 22
0
 /// <summary>
 /// 添加特定的格式来过期缓存
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 /// <param name="extendedFormatString">过期时间</param>
 /// <param name="itemRefreshFactory">缓存过期委托</param>
 public void AddExtendedFormatTime(string key, object value, string extendedFormatString, ICacheItemRefreshAction itemRefreshFactory)
 {
     cacheMgr.Add(key, value, CacheItemPriority.Normal, itemRefreshFactory, new ExtendedFormatTime(extendedFormatString)
     {
     });
 }
Esempio n. 23
0
 public void AddCache(string key, object obj, ICacheExpiration expiration)
 {
     manager.Add(key, obj, CacheItemPriority.Normal, null,
                 expiration.GetExpirationStrategy <ICacheItemExpiration>());
 }
Esempio n. 24
0
        public static void TestEachMethod(ICacheManager<object> cache)
        {
            cache.Clear();

            cache.Add("key", "value", "region");
            cache.AddOrUpdate("key", "region", "value", _ => "update value", new UpdateItemConfig(2, VersionConflictHandling.EvictItemFromOtherCaches));

            cache.Expire("key", "region", TimeSpan.FromDays(1));
            var val = cache.Get("key", "region");
            var item = cache.GetCacheItem("key", "region");
            cache.Put("key", "region", "put value");
            cache.RemoveExpiration("key", "region");

            object update2;
            cache.TryUpdate("key", "region", _ => "update 2 value", out update2);

            object update3 = cache.Update("key", "region", _ => "update 3 value");

            cache.Remove("key", "region");

            cache.Clear();
            cache.ClearRegion("region");
        }
 public void Add(string key, T value, TimeSpan ttl, string region)
 {
     _cacheManager.Add(new CacheItem <object>(key, PaddingPrefix(region), value, ExpirationMode.Absolute, ttl));
 }
Esempio n. 26
0
        /// <summary>
        /// 把值放到缓存里
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        public static void SetCacheItem(string key, object value)
        {
            ICacheManager cache = CacheFactory.GetCacheManager("CacheManager");

            cache.Add(key, value);
        }
Esempio n. 27
0
 public object Set(string key, string value)
 {
     return(_cacheManager.Add(key, value));
 }
Esempio n. 28
0
        /// <summary>
        /// 把值放到缓存里
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="cacheItemPriority">缓存优先级</param>
        public static void SetCacheItem(string key, object value, CacheItemPriority cacheItemPriority)
        {
            ICacheManager cache = CacheFactory.GetCacheManager("CacheManager");

            cache.Add(key, value, cacheItemPriority, null, null);
        }
Esempio n. 29
0
        public static void CacheThreadTest(ICacheManager<string> cache, int seed)
        {
            var threads = 10;
            var numItems = 100;
            var eventAddCount = 0;
            var eventRemoveCount = 0;
            var eventGetCount = 0;

            cache.OnAdd += (sender, args) => { Interlocked.Increment(ref eventAddCount); };
            cache.OnRemove += (sender, args) => { Interlocked.Increment(ref eventRemoveCount); };
            cache.OnGet += (sender, args) => { Interlocked.Increment(ref eventGetCount); };

            Func<int, string> keyGet = (index) => "key" + ((index + 1) * seed);

            Action test = () =>
            {
                for (int i = 0; i < numItems; i++)
                {
                    cache.Add(keyGet(i), i.ToString());
                }

                for (int i = 0; i < numItems; i++)
                {
                    if (i % 10 == 0)
                    {
                        cache.Remove(keyGet(i));
                    }
                }

                for (int i = 0; i < numItems; i++)
                {
                    string val = cache.Get(keyGet(i));
                }
            };

            Parallel.Invoke(new ParallelOptions() { MaxDegreeOfParallelism = 8 }, Enumerable.Repeat(test, threads).ToArray());

            foreach (var handle in cache.CacheHandles)
            {
                var stats = handle.Stats;
                Console.WriteLine(string.Format(
                        "Items: {0}, Hits: {1}, Miss: {2}, Remove: {3}, ClearRegion: {4}, Clear: {5}, Adds: {6}, Puts: {7}, Gets: {8}",
                            stats.GetStatistic(CacheStatsCounterType.Items),
                            stats.GetStatistic(CacheStatsCounterType.Hits),
                            stats.GetStatistic(CacheStatsCounterType.Misses),
                            stats.GetStatistic(CacheStatsCounterType.RemoveCalls),
                            stats.GetStatistic(CacheStatsCounterType.ClearRegionCalls),
                            stats.GetStatistic(CacheStatsCounterType.ClearCalls),
                            stats.GetStatistic(CacheStatsCounterType.AddCalls),
                            stats.GetStatistic(CacheStatsCounterType.PutCalls),
                            stats.GetStatistic(CacheStatsCounterType.GetCalls)));
            }

            Console.WriteLine(string.Format("Event - Adds {0} Hits {1} Removes {2}",
                eventAddCount,
                eventGetCount,
                eventRemoveCount));

            cache.Clear();
            cache.Dispose();
        }
Esempio n. 30
0
 public void Add(string key, T value, TimeSpan ttl, string region)
 {
     _cacheManager.Add(new CacheItem <T>(key, region, value, ExpirationMode.Absolute, ttl));
 }
Esempio n. 31
0
 public bool Set(string key, Nca.Library.Models.CacheItem <T> value)
 {
     return(_cacheManager.Add(ConvertCacheItem(key, value)));
 }
Esempio n. 32
0
        /// <summary>
        /// 加载自定义标签
        /// </summary>
        /// <param name="BusinessDll">Dll路径</param>
        /// <param name="cache">存入缓存</param>
        public static void LoadAttribute(List<string> BusinessDll, ICacheManager cache,string pluginName)
        {
            string cacheKey = pluginName+"@"+GetCacheKey();

            List<EntityAttributeInfo> entityAttributeList = new List<EntityAttributeInfo>();

            for (int k = 0; k < BusinessDll.Count; k++)
            {

                System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom(BusinessDll[k]);
                Type[] types = assembly.GetTypes();
                for (int i = 0; i < types.Length; i++)
                {
                    TableAttribute[] tableAttrs = ((TableAttribute[])types[i].GetCustomAttributes(typeof(TableAttribute), true));

                    if (tableAttrs.Length > 0)
                    {
                        EntityAttributeInfo eattr = new EntityAttributeInfo();
                        eattr.ObjType = types[i];
                        eattr.TableAttributeInfoList = new List<TableAttributeInfo>();
                        foreach (TableAttribute val in tableAttrs)
                        {
                            TableAttributeInfo tableattr = new TableAttributeInfo();
                            tableattr.Alias = val.Alias;
                            tableattr.EType = val.EntityType;
                            tableattr.TableName = val.TableName;
                            tableattr.IsGB = val.IsGB;
                            tableattr.ColumnAttributeInfoList = new List<ColumnAttributeInfo>();

                            PropertyInfo[] property = eattr.ObjType.GetProperties();
                            for (int n = 0; n < property.Length; n++)
                            {
                                ColumnAttribute[] columnAttributes = (ColumnAttribute[])property[n].GetCustomAttributes(typeof(ColumnAttribute), true);
                                if (columnAttributes.Length > 0)
                                {
                                    ColumnAttributeInfo colattr = new ColumnAttributeInfo();
                                    ColumnAttribute colval = columnAttributes.ToList().Find(x => x.Alias == tableattr.Alias);
                                    if (colval == null) throw new Exception("输入的Alias别名不正确");
                                    colattr.Alias = colval.Alias;
                                    colattr.DataKey = colval.DataKey;
                                    colattr.FieldName = colval.FieldName;
                                    colattr.IsInsert = colval.IsInsert;
                                    //colattr.IsSingleQuote=colval.is
                                    colattr.Match = colval.Match;
                                    colattr.PropertyName = property[n].Name;

                                    if (colattr.DataKey)
                                    {
                                        tableattr.DataKeyFieldName = colattr.FieldName;//设置TableAttributeInfo的主键字段名
                                        tableattr.DataKeyPropertyName = colattr.PropertyName;
                                    }
                                    tableattr.ColumnAttributeInfoList.Add(colattr);
                                }
                            }

                            eattr.TableAttributeInfoList.Add(tableattr);
                        }


                        entityAttributeList.Add(eattr);
                    }
                }
            }

            cache.Add(cacheKey, entityAttributeList);
        }
Esempio n. 33
0
        public override void OnInvoke(MethodInterceptionArgs args)
        {
            var keyGenerator     = new StringBuilder();
            var referenceTypeKey = new StringBuilder();
            var valueTypeKey     = new StringBuilder();

            var methodName = IsNullOrEmpty(_customKey)
                ? $"{args.Method.ReflectedType?.Name}.{args.Method.Name}"
                : _customKey.WhiteSpaceRemove();

            keyGenerator.Append(methodName);

            var arguments = args.Arguments.ToList();

            foreach (var dataArgument in arguments)
            {
                if (dataArgument != null)
                {
                    var getTypeInfo = dataArgument.GetType().GetTypeInfo().ToString();
                    var getBaseType = dataArgument.GetType().BaseType?.ToString();

                    if (getTypeInfo != "System.String" && getBaseType != "System.ValueType")
                    {
                        var getObjectName = dataArgument.GetType().Name;

                        referenceTypeKey.AppendFormat($"{getObjectName}RT/");

                        var getPropertiesValue =
                            dataArgument.GetType().GetProperties().Select(x => x.GetValue(dataArgument));

                        foreach (var value in getPropertiesValue)
                        {
                            referenceTypeKey.AppendFormat(value == null ? "<Null>/" : $"{value}/");
                        }
                    }

                    if (getTypeInfo == "System.String" || getBaseType == "System.ValueType")
                    {
                        valueTypeKey.AppendFormat($"{dataArgument}-");
                    }
                }

                else
                {
                    valueTypeKey.AppendFormat("<Null>-");
                }
            }

            if (!IsNullOrEmpty(referenceTypeKey.ToString()))
            {
                referenceTypeKey.Remove(referenceTypeKey.Length - 1, 1);
                keyGenerator.Append("&" + referenceTypeKey);
            }

            if (!IsNullOrEmpty(valueTypeKey.ToString()))
            {
                valueTypeKey = valueTypeKey.Remove(valueTypeKey.Length - 1, 1);
                keyGenerator.Append("&VT" + valueTypeKey);
            }

            var clearKeyData = keyGenerator.ToString().WhiteSpaceRemove();

            if (_cacheManager.IsAdd(clearKeyData))
            {
                var cacheValue = _cacheManager.Get <object>(clearKeyData);

                switch (_cacheType.Name)
                {
                case nameof(MemoryCacheManager):

                    args.ReturnValue = cacheValue;
                    return;

                case nameof(RedisCacheManager):

                    var methodInfo = args.Method as MethodInfo;
                    if (methodInfo == null)
                    {
                        return;
                    }
                    var methodReturnType = methodInfo.ReturnType;

                    args.ReturnValue = JsonConvert.DeserializeObject(cacheValue.ToString(), methodReturnType);
                    return;

                default:
                    return;
                }
            }

            base.OnInvoke(args);

            if (_cacheByMinute > 0)
            {
                _cacheManager.Add(clearKeyData, args.ReturnValue, _cacheByMinute);
            }
            else
            {
                _cacheManager.Add(clearKeyData, args.ReturnValue);
            }
        }
Esempio n. 34
0
        /// <summary>
        /// This will return the Content HTML Event Definition, which is a combination of ContentData properties and MetaDataProperties.
        /// </summary>
        /// <returns></returns>
        private EventDefinition GetContentHTMLEventDef()
        {
            Log.WriteMessage(string.Format("-Begin {0}.GetContentHTMLEventDef.", CLASS_NAME), LogLevel.Verbose);
            EventDefinition HTMLDefinition = null;
            try
            {

                CachManger = ObjectFactory.GetCacheManager();
                HTMLDefinition = CachManger.Get(CacheKey) as EventDefinition;

                if (HTMLDefinition == null)
                {

                    List<EventDefinition> EktronEventDefs = null;

                    if (!string.IsNullOrEmpty(AdapterName))
                    {
                        EktronEventDefs = this.ContextBusClient.GetEventDefinitionList(AdapterName);
                    }
                    if (EktronEventDefs != null)
                    {
                        HTMLDefinition = EktronEventDefs.FirstOrDefault(x => x.DisplayName.ToLower().Contains("html"));
                        CachManger.Add(CacheKey, HTMLDefinition, new TimeSpan(0, 10, 0));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteError(string.Format("{0}.GetContentHTMLEventDef failed: {1}.", CLASS_NAME, ex.Message));
            }

            Log.WriteMessage(string.Format("+Finish {0}.GetContentHTMLEventDef.", CLASS_NAME), LogLevel.Verbose);
            return HTMLDefinition;
        }
 private static void setCache(string expressionKeyHash, string sql)
 {
     _keysCacheManager.Add(
         new CacheItem <string>(expressionKeyHash, sql, ExpirationMode.Sliding, _slidingExpirationTimeSpan));
 }
 private static void setCache(string expressionKeyHash, EFCacheKey value)
 {
     _keysCacheManager.Add(
         new CacheItem <EFCacheKey>(expressionKeyHash, value, ExpirationMode.Sliding, _slidingExpirationTimeSpan));
 }
Esempio n. 37
0
 public void Add(String key, Object obj)
 {
     _cacheManager.Add(key, obj);
 }
        public static TApi GetStaticApi(string key, string accessToken)
        {
            TApi apiClass = null;

            switch (key)
            {
            case "TeamApi":
                if (_cacheManager.Get <TApi>(key) != null)
                {
                    return(_cacheManager.Get <TApi>(key));
                }
                else
                {
                    apiClass = new TeamApi(accessToken);
                }
                break;

            case "BucketApi":
                if (_cacheManager.Get <TApi>(key) != null)
                {
                    return(_cacheManager.Get <TApi>(key));
                }
                else
                {
                    apiClass = new BucketApi(accessToken);
                }
                break;

            case "ChannelApi":
                if (_cacheManager.Get <TApi>(key) != null)
                {
                    return(_cacheManager.Get <TApi>(key));
                }
                else
                {
                    apiClass = new ChannelApi(accessToken);
                }
                break;

            case "PlannerApi":
                if (_cacheManager.Get <TApi>(key) != null)
                {
                    return(_cacheManager.Get <TApi>(key));
                }
                else
                {
                    apiClass = new PlannerApi(accessToken);
                }
                break;

            case "TaskApi":
                if (_cacheManager.Get <TApi>(key) != null)
                {
                    return(_cacheManager.Get <TApi>(key));
                }
                else
                {
                    apiClass = new TaskApi(accessToken);
                }
                break;

            default:
                break;
            }
            _cacheManager.Add(key, apiClass);
            return(apiClass);
        }
Esempio n. 39
0
        public static void TestEachMethod(ICacheManager<object> cache)
        {
            cache.Clear();

            cache.Add("key", "value", "region");
            cache.AddOrUpdate("key", "region", "value", _ => "update value", 22);

            cache.Expire("key", "region", TimeSpan.FromDays(1));
            var val = cache.Get("key", "region");
            var item = cache.GetCacheItem("key", "region");
            cache.Put("key", "put value");
            cache.RemoveExpiration("key");

            object update2;
            cache.TryUpdate("key", "region", _ => "update 2 value", out update2);

            object update3 = cache.Update("key", "region", _ => "update 3 value");

            cache.Remove("key", "region");

            cache.Clear();
            cache.ClearRegion("region");
        }
Esempio n. 40
0
        public ActionResult Login(string name, string password, string validateCode = null)
        {
            //是否是安全IP地址
            var  currentIp = HttpContext.Connection.RemoteIpAddress.ToString();
            bool isSafeIp  = _projectSetting.Value.SafeIPAddress.Split(",").Any(c => c == currentIp);

            if (!isSafeIp)
            {
                if (string.IsNullOrEmpty(validateCode))
                {
                    return(ErrorJsonResult("请输入验证码"));
                }
                string code = HttpContext.Session.GetString("validateCode");
                if (code != validateCode.ToLower())
                {
                    return(ErrorJsonResult("验证码错误"));
                }
                //更新验证码
                HttpContext.Session.SetString("validateCode", ValidateCodeHelper.GetValidateCode().ValidateNum.ToLower());
            }
            var sr = _accountService.Login(name, password);

            if (!sr.IsSucceed)
            {
                return(ErrorJsonResult(sr.Message));
            }
            string cookieKey = _projectSetting.Value.CookieKey;
            //每一个登录用户生成不同的cookie
            string cookieValue = BitConverter.ToInt64(Guid.NewGuid().ToByteArray()).ToString();

            //写入cookie
            HttpContext.Response.Cookies.Append(cookieKey, cookieValue, new CookieOptions
            {
                Expires  = DateTime.Now.AddMinutes(_projectSetting.Value.SessionTimeOut),
                HttpOnly = true
            });
            //当前登录用户
            var currentSysUser = new CurrentSysUser()
            {
                UserID    = sr.Data.UserID,
                LoginName = sr.Data.LoginName,
                UserName  = sr.Data.UserName
            };
            var menuList = _accountService.GetMenuList(currentSysUser.UserID).Data;

            currentSysUser.MenuList = menuList.Select(s => new CurrentSysUserMenu()
            {
                ID       = s.MenuID,
                Name     = s.MenuName,
                URL      = s.URL,
                ParentID = s.ParentID,
                Icon     = s.Icon,
                Sort     = s.Sort
            }).ToList();
            //将用户权限以cookieValue为键写入cache
            string userCacheKey = GetCacheKey(cookieValue);

            //滑动方式添加缓存
            _cacheManager.Add(userCacheKey, currentSysUser, new TimeSpan(0, _projectSetting.Value.SessionTimeOut, 0), true);

            return(SuccessJsonResult());
        }
            public StateHash Run(DeployContext context, StateHash hash, ICacheManager cacheManager, bool first = true, bool last = true)
            {
                if (mLogPre != null)
                    context.ApplicationContext.Log.Log(mLogPre);

                if (mTransform != null)
                {
                    var stopWatch = new Stopwatch();
                    stopWatch.Start();
                    hash = mTransform.RunTransform(hash, context.DryRun, context.ApplicationContext.Log);
                    stopWatch.Stop();

                    if (!context.DryRun)
                    {
                        var rhf = GetResumeHashFile(context);
                        File.WriteAllText(rhf.FullName, hash.ToHexString());
                    }

                    if (!first && !last && stopWatch.Elapsed >= context.ApplicationContext.UserConfig.Cache.MinDeployTime)
                    {
                        foreach (var db in context.ApplicationContext.ProjectConfig.Databases)
                        {
                            cacheManager.Add(context.ApplicationContext.UserConfig.Databases.Connection, db, hash);
                        }
                    }
                }
                else if (mChildren.Count > 0)
                {
                    using (context.ApplicationContext.Log.IndentScope())
                    {
                        for (var i = 0; i < mChildren.Count; i++)
                        {
                            var child = mChildren[i];
                            hash = child.Run(context, hash, cacheManager, first, last && i == mChildren.Count - 1);
                            first = false;
                        }
                    }
                }

                if (mLogPost != null)
                    context.ApplicationContext.Log.Log(mLogPost);

                return hash;
            }
Esempio n. 42
0
 public JsonResult Getfinyr(string finyr)
 {
     Session["FINYEAR"] = finyr.Trim();
     _ICacheManager.Add("FINYEAR", finyr.Trim());
     return(Json(finyr, JsonRequestBehavior.AllowGet));
 }