public void Add(string key, object obj)
 {
     if (obj.IsNull())
     {
         Remove(key); return;
     }
     using (new WriterLockSlimDisposable(locker)) {
         _cache.Add(key, obj, DateTime.Now.GetTimeSpan(DateTime.Now.AddSeconds(Factor)), RegionName);
     }
 }
Exemple #2
0
        private bool Add <T>(string key, string region, T value, CachePolicy policy)
        {
            _cache.CreateRegion(region);

            if (policy == CachePolicy.ExpireAsPerConfig)
            {
                return(_cache.Add(key, value, region) != null);
            }

            return(_cache.Add(key, value, GetExpiryTime(policy), region) != null);
        }
Exemple #3
0
 public void Add(string key, object data, TimeSpan?timeout)
 {
     //Add item to Cache
     if (timeout.HasValue)
     {
         dataCache.Add(key, data, timeout.Value);
     }
     else
     {
         dataCache.Add(key, data);
     }
 }
Exemple #4
0
 public void Add(string cacheKey, DateTime expiry, object dataToAdd)
 {
     if (expiry > DateTime.Now && dataToAdd != null)
     {
         TimeSpan timeout = expiry - DateTime.Now;
         _cache.Add(cacheKey, dataToAdd, timeout);
         if (debugLog)
         {
             log.Debug(string.Format("Adding data to cache with cache key: {0}, expiry date {1}", cacheKey, expiry.ToString("yyyy/MM/dd hh:mm:ss")));
         }
     }
 }
        public void Add(string key, object value, TimeSpan timeout)
        {
            if (null == value)
            {
                return;
            }

            DataCacheItemVersion version = _Cache.Add(key, value, timeout, REGION_NAME);

            if (version == null)
            {
                throw new ApplicationException("DataCache.Add failed");
            }
        }
Exemple #6
0
        /// <summary>
        /// 获取接口签名Ticket
        /// lz 2016-10-25
        /// </summary>
        /// <returns></returns>
        public BaseResult GetTicketInfo(string key_y)
        {
            BaseResult res = new BaseResult()
            {
                Success = false
            };

            if (DataCache.Get(key_y + "_RegisterTicket") != null && !string.IsNullOrEmpty(((Tb_Ticket)DataCache.Get(key_y + "_RegisterTicket")).id))
            {
                res.Success = true;
                res.Data    = (Tb_Ticket)DataCache.Get(key_y + "_RegisterTicket");
                return(res);
            }
            else
            {
                Hashtable ht = new Hashtable();
                ht.Add("key_y", key_y);
                var ticketBr = BusinessFactory.Tb_Ticket.Get(ht);
                if (ticketBr.Success && ((Tb_Ticket)ticketBr.Data) != null && !string.IsNullOrEmpty(((Tb_Ticket)ticketBr.Data).id))
                {
                    res.Success = true;
                    res.Data    = ticketBr.Data;
                    DataCache.Add(key_y + "_RegisterTicket", (Tb_Ticket)ticketBr.Data, DateTime.Now.AddDays(1));
                    return(res);
                }
                else
                {
                    res.Success = false;
                    return(res);
                }
            }
        }
Exemple #7
0
        public IList <Ts_Param_Business> GetProcessList(long id_user_master)
        {
            IList <Ts_Param_Business> processList = DataCache.Get <IList <Ts_Param_Business> >(id_user_master + "_process");

            if (processList == null)
            {
                lock (lock1)
                {
                    processList = DataCache.Get <IList <Ts_Param_Business> >(id_user_master + "_process");
                    if (processList == null)
                    {
                        Hashtable param = new Hashtable();
                        param.Add("id_user_master", id_user_master);

                        IList <Ts_Param_Business> processlist = DAL.QueryList <Ts_Param_Business>(typeof(Ts_Param_Business), param);
                        if (processlist != null)
                        {
                            DataCache.Add(id_user_master + "_process", processList, CacheItemPriority.High);
                        }
                    }
                }
            }

            return(processList);
        }
 /// <summary>
 /// Adds an item to the cache
 /// </summary>
 /// <param name="key">Cache key</param>
 /// <param name="value">Value</param>
 public void Add(string key, object value)
 {
     _dc.Add(key, value);
     // if (_dc.Add(key, value) == null) throw (new Exception("error"));
     // _dc.Add(key, value, TimeSpan.FromMinutes(30));
     //catch (DataCacheException cacheError)
 }
Exemple #9
0
 public static void TransactionAdd(DataCache snapshot, params TransactionState[] txs)
 {
     foreach (TransactionState tx in txs)
     {
         snapshot.Add(NativeContract.Ledger.CreateStorageKey(Prefix_Transaction, tx.Transaction.Hash), new StorageItem(tx, true));
     }
 }
Exemple #10
0
        //获取access_token
        protected string GetAccessToken(string appid, string appsecret)
        {
            if (string.IsNullOrEmpty(appid) || string.IsNullOrEmpty(appsecret))
            {
                return(null);
            }

            string key = string.Format("WeChat.Access_Token_{0}_{1}", appid, appsecret);

            string access_token = DataCache.Get <string>(key);

            if (string.IsNullOrEmpty(access_token))
            {
                var dict = WeChatHelper.GetAccessToken(appid, appsecret);

                if (dict != null && dict["access_token"] != null)
                {
                    access_token = dict["access_token"].ToString();
                    DataCache.Remove(key);
                    DataCache.Add(key, access_token, new TimeSpan(0, 0, int.Parse(dict["expires_in"].ToString()) - 200));
                }
            }

            return(access_token);
        }
        private void RecordTransferHistory(StoreView snapshot, UInt160 scriptHash, UInt160 from, UInt160 to, BigInteger amount, UInt256 txHash, ref ushort transferIndex)
        {
            if (!_shouldTrackHistory)
            {
                return;
            }

            Header header = snapshot.GetHeader(snapshot.CurrentBlockHash);

            if (_recordNullAddressHistory || from != UInt160.Zero)
            {
                _transfersSent.Add(new Nep5TransferKey(from, header.Timestamp, scriptHash, transferIndex),
                                   new Nep5Transfer
                {
                    Amount         = amount,
                    UserScriptHash = to,
                    BlockIndex     = snapshot.Height,
                    TxHash         = txHash
                });
            }

            if (_recordNullAddressHistory || to != UInt160.Zero)
            {
                _transfersReceived.Add(new Nep5TransferKey(to, header.Timestamp, scriptHash, transferIndex),
                                       new Nep5Transfer
                {
                    Amount         = amount,
                    UserScriptHash = from,
                    BlockIndex     = snapshot.Height,
                    TxHash         = txHash
                });
            }
            transferIndex++;
        }
        public string GetCaching()
        {
            DataCacheFactory cacheFactory = new DataCacheFactory();

            DataCache cache  = cacheFactory.GetDefaultCache();
            object    result = cache.Get("Item");

            string str = " ";

            if (result == null)
            {
                // "Item" not in cache. Obtain it from specified data source
                // and add it.
                var times = TimeSpan.FromMinutes(2);
                str = "no cache..." + times.ToString();
                cache.Add("item", str, times);
            }
            else
            {
                str = (string)result;
                // "Item" is in cache, cast result to correct type.
            }

            return(str);
        }
        public void Add(string key, string valueKey, object value)
        {
            // DataCache中不包含Contain方法,所有用Get方法来判断对应的key值是否在缓存中存在
            var val = (Dictionary <string, object>)_cache.Get(key);

            if (val == null)
            {
                val = new Dictionary <string, object> {
                    { valueKey, value }
                };
                _cache.Add(key, val);
            }
            else
            {
                if (!val.ContainsKey(valueKey))
                {
                    val.Add(valueKey, value);
                }
                else
                {
                    val[valueKey] = value;
                }

                _cache.Put(key, val);
            }
        }
Exemple #14
0
        private BingSearchResultList FetchData(string query, int expirySeconds)
        {
            var key  = _cacheKeyPrefix + "-image-query-" + query;
            var data = _cache.Get <BingSearchResultList>(key);

            // If the query's not in the cache
            if (data == null)
            {
                // Request the data
                var client = new RestClient("https://api.datamarket.azure.com");
                client.Authenticator = new HttpBasicAuthenticator("", _config.Get <string>("BingApiKey"));

                var req = new RestRequest("Bing/Search/v1/Image");
                req.AddParameter("ImageFilters", "'Size:Large+Aspect:Tall'");
                req.AddParameter("Query", "'" + query.Trim() + "'");

                var response = client.Execute <BingSearchResultContainer>(req);

                data = response.Data.D;

                // And add it to the cache
                _cache.Add(key, data, expirySeconds);
            }

            return(data);
        }
Exemple #15
0
 public override void Add(BaseModel model)
 {
     if (model == null)
     {
         return;
     }
     cache.Add(model);
 }
Exemple #16
0
 protected TableAttribute GetTableAttr(Type type)
 {
     try
     {
         Dictionary <Type, TableAttribute> dic = DataCache.Get <Dictionary <Type, TableAttribute> >("TableAttributeCache");
         if (dic == null || !dic.ContainsKey(type) || dic[type] == null)
         {
             lock (lock_TableAttribute)
             {
                 dic = DataCache.Get <Dictionary <Type, TableAttribute> >("TableAttributeCache");
                 if (dic == null || !dic.ContainsKey(type) || dic[type] == null)
                 {
                     object[] attrs = type.GetCustomAttributes(tableAttributeType, true);
                     if (attrs.Length < 1)
                     {
                         throw new ArgumentException(String.Format("类 {0} 中未找到属性 {1}", type.FullName, tableAttributeType.FullName));
                     }
                     TableAttribute tableAttr = (TableAttribute)attrs[0];
                     if (tableAttr.Name == null || String.IsNullOrEmpty(tableAttr.Name.Trim()))
                     {
                         throw new ArgumentException(String.Format("类 {0} 中属性 {1} 的 Name 值有误", type.FullName, tableAttributeType.FullName));
                     }
                     if (tableAttr.MapName == null || String.IsNullOrEmpty(tableAttr.MapName.Trim()))
                     {
                         throw new ArgumentException(String.Format("类 {0} 中属性 {1} 的 MapName 值有误", type.FullName, tableAttributeType.FullName));
                     }
                     if (dic == null)
                     {
                         dic = new Dictionary <Type, TableAttribute>();
                     }
                     dic.Add(type, tableAttr);
                     DataCache.Add("TableAttributeCache", dic, CacheItemPriority.NotRemovable);
                 }
             }
         }
         return(dic[type]);
     }
     catch (TypeLoadException ex)
     {
         throw ex;
     }
     catch (ArgumentNullException ex)
     {
         throw ex;
     }
     catch (ArgumentException ex)
     {
         throw ex;
     }
     catch (InvalidOperationException ex)
     {
         throw ex;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        private Guid CreateSession()
        {
            Guid      sessionId = Guid.NewGuid();
            DataCache sessions  = CacheFactory.GetCache(CacheName);

            sessions.Add(sessionId.ToString(), new Dictionary <string, object>(), new TimeSpan(0, 0, SessionTimeout, 0));

            return(sessionId);
        }
 Tweets getTweets(string name)
 {
     DataCache cache = new DataCache();
     Tweets entries = cache.Get(name) as Tweets;
     if (entries == null)
     {
         entries = TwitterFeed.GetTweets(name);
         cache.Add(name, entries);
     }
     return entries;
 }
Exemple #19
0
        public void Subscribe(RabbitMQBus rabbitMQ, MessagePriorityEnum priority, Action <NotifyMessage> handler)
        {
            try
            {
                string topic = priority.ToString().ToUpper();
                rabbitMQ.Bus.Subscribe(QueueDic[topic], (body, props, info) => Task.Factory.StartNew(() =>
                {
                    MetricsKeys.RabbitMQ_Subscribe.MeterMark("Success");
                    if (DataCache.Add(props.MessageId, 1, DateTime.Now.AddMinutes(10)))
                    {
                        try
                        {
                            if (props.Type == "M")
                            {
#if DEBUG
                                System.Diagnostics.Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();
#endif
                                List <NotifyMessage> list = JsonConvert.DeserializeObject <List <NotifyMessage> >(Encoding.UTF8.GetString(body), serializerSettings);
                                for (int i = 0; i < list.Count; i++)
                                {
                                    handler(list[i]);
                                }
#if DEBUG
                                watch.Stop();
                                Process.Debug("订阅消息", "Consume", string.Format("数据模式:【{0}】,条数:【{1}】,耗时:【{2}】", props.Type, list.Count, watch.ElapsedMilliseconds), "");
#endif
                            }
                            else if (props.Type == "S")
                            {
                                handler(JsonConvert.DeserializeObject <NotifyMessage>(Encoding.UTF8.GetString(body), serializerSettings));
#if DEBUG
                                Process.Debug("订阅消息", "Consume", string.Format("数据模式:【{0}】,条数:【{1}】", props.Type, 1), "");
#endif
                            }
                        }
                        catch (Exception ex)
                        {
                            m_logger.Error("处理消息发生异常:" + ex.GetString());
                        }
                    }
                    else
                    {
                        RepeatMessageDic[props.MessageId] = RepeatMessageDic[props.MessageId] + 1;
                        ComsumeMessage(props.MessageId, RepeatMessageDic[props.MessageId]);
                    }
                }));
            }
            catch (Exception ex)
            {
                MetricsKeys.RabbitMQ_Subscribe.MeterMark("Error");
                m_logger.Error("订阅消息发生异常:" + ex.GetString());
                throw new RabbitMQException("订阅消息发生异常", ex);
            }
        }
        public List <string> GetProducts()
        {
            List <string> products = null;

            DataCache dataCache = null;

            if (this.enableCache)
            {
                try
                {
                    dataCache = cacheFactory.GetDefaultCache();
                    products  = dataCache.Get("products") as List <string>;
                    if (products != null)
                    {
                        products[0] = "(from cache)";
                        return(products);
                    }
                }
                catch (DataCacheException ex)
                {
                    if (ex.ErrorCode != DataCacheErrorCode.RetryLater)
                    {
                        throw;
                    }

                    // ignore temporary failures
                }
            }

            NorthwindEntities context = new NorthwindEntities();

            try
            {
                var query = from product in context.Products
                            select product.ProductName;
                products = query.ToList();
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }
            }

            products.Insert(0, "(from data source)");

            if (this.enableCache && dataCache != null)
            {
                dataCache.Add("products", products, TimeSpan.FromSeconds(30));
            }

            return(products);
        }
        /// <summary>
        /// Stores The value with key only if such key doesn't exist at the server yet.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="value">The value.</param>
        /// <param name="expiresAt">The expires at.</param>
        /// <returns></returns>
        private bool CacheAdd(string key, object value, DateTime expiresAt)
        {
            object entry;

            if (TryGetValue(key, out entry))
            {
                return(false);
            }
            DataCache.Add(key, value, expiresAt.Subtract(DateTime.Now));
            return(true);
        }
Exemple #22
0
        public bool Add <T>(string key, T value)
        {
            Guard.ArgumentNotNullOrEmpty(key, "key");
            Guard.ArgumentNotNull(value, "value");

            try
            {
                _cache.Add(key, value);
                return(true);
            }
            catch (DataCacheException ex)
            {
                if (ex.ErrorCode == DataCacheErrorCode.KeyAlreadyExists)
                {
                    return(false);
                }
                // if other error, just throw exception.
                throw;
            }
        }
 public void AddInfo(DataCache _cache, string key, string value)
 {
     try
     {
         _cache.Add(key, value);
     }
     catch (Exception)
     {
         throw new Exception("Ocorreu uma exceção inesperada");
     }
 }
        Tweets getTweets(string name)
        {
            DataCache cache   = new DataCache();
            Tweets    entries = cache.Get(name) as Tweets;

            if (entries == null)
            {
                entries = TwitterFeed.GetTweets(name);
                cache.Add(name, entries);
            }
            return(entries);
        }
Exemple #25
0
        public void PutNode(MPTNode np)
        {
            var n = Resolve(np.Hash);

            if (n is null)
            {
                np.Reference = 1;
                cache.Add(np.Hash, np.Clone());
                return;
            }
            cache.GetAndChange(np.Hash).Reference++;
        }
Exemple #26
0
        private BaseResult ValidClient()
        {
            BaseResult br         = new BaseResult();
            var        ip         = Request.UserHostAddress;
            var        key        = string.Format("$RegClientAccess_{0}", ip);
            var        initconfig = new Hashtable();

            initconfig.Add("date", DateTime.Now);
            initconfig.Add("count", 1);
            try
            {
                if (DataCache.ContainsKey(key))
                {
                    var list = DataCache.Get <Hashtable>(key);
                    if (list == null)
                    {
                        list = initconfig;
                    }
                    else
                    {
                        var date       = TypeConvert.ToDateTime(list["date"], DateTime.Now);
                        var count      = TypeConvert.ToInt(list["count"], 0) + 1;
                        var compssdate = date.AddDays(1);
                        if (compssdate >= DateTime.Now && count > 50)//一天内50次尝试注册
                        {
                            br.Success = false;
                            br.Data    = "count";
                            br.Message.Add("今天您的注册次数过多过频繁,不能再注册,请明天再试。");
                            br.Level = ErrorLevel.Warning;
                            return(br);
                        }
                        else if (compssdate < DateTime.Now)
                        {
                            date  = DateTime.Now;
                            count = 1;
                        }
                        list["date"]  = date;
                        list["count"] = count;
                    }
                    DataCache.Set(key, list);
                }
                else
                {
                    DataCache.Add(key, initconfig, DateTime.Now.AddHours(12));
                }
            }
            catch (Exception)
            {
                br.Success = true;
            }
            br.Success = true;
            return(br);
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (myCache == null)
            {
                UpdateStatus("First click Connect To Cache");
                return;
            }

            try
            {
                Guid key = Guid.NewGuid();
                myCache.Add(key.ToString(), txtObjectToCache.Text);
                lstboxGuidCache.Items.Add(key.ToString());
                txtMonitorCacheItem.Text = key.ToString();

                UpdateStatus("Added Item to Cache");
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }
 // Adds cache item having <key>,<value> to DataCache object.
 public void Add(string key, object value)
 {
     GetCache();
     if (Get(key) == null)
     {
         _cache.Add(key, value);
     }
 }
        Tweets getTweets(string name)
        {
            DataCache cache = new DataCache();

            Tweets entries = Tweets.FromObject(cache.Get(name));

            if (entries == null)
            {
                entries = TwitterFeed.GetTweets(name);
                cache.Add(name, entries.GetBytes());
            }

            return(entries);
        }
        Tweets getTweets(string name)
        {
            DataCache cache = new DataCache();

            Tweets entries = Tweets.FromObject(cache.Get(name));

            if (entries == null)
            {
                entries = TwitterFeed.GetTweets(name);
                cache.Add(name, entries.GetBytes());
            }

            return entries;
        }
Exemple #31
0
        /// <summary>
        /// 发送手机验证码
        /// </summary>
        // [HttpPost]
        public ActionResult GetPhoneVaildCode(string obj)
        {
            BaseResult br = new BaseResult();

            try
            {
                var         param = JSON.Deserialize <Hashtable>(obj);
                ParamVessel p     = new ParamVessel();
                p.Add("phone", String.Empty, HandleType.ReturnMsg);
                param = param.Trim(p);
                string vaildphone = param["phone"].ToString();

                br = ValidClient();
                if (!br.Success)
                {
                    return(Json(br));
                }

                param.Clear();
                param.Add("account", vaildphone);
                br = BusinessFactory.Account.Get(param);
                if (br.Data != null)
                {
                    br.Success = false;
                    br.Message.Add("该手机号已注册,请登录解除手机绑定后,再用该手机注册。");
                    br.Data  = "account";
                    br.Level = ErrorLevel.Warning;
                    return(Json(br));
                }

                PhoneVaild vaild = new PhoneVaild()
                {
                    phone = vaildphone, vaildcode = CySoft.Frame.Common.Rand.RandNum(4)
                };

                Utility.SMS.ISMSHelper sender = new Utility.SMS.EmayHelper();
                sender.Send(vaild.phone, String.Format("校验码:{0},用于开通订货易。", vaild.vaildcode));

                DataCache.Add(vaild.SeviceKey, vaild, new TimeSpan(0, 2, 0));
                br.Success = true;
            }
            catch (Exception)
            {
                br.Success = false;
                br.Level   = ErrorLevel.Error;
                br.Message.Add("验证码发送失败!");
            }
            return(Json(br));
        }
Exemple #32
0
        protected Table GetTable(Type type)
        {
            Dictionary <Type, Table> dicTableInfo = DataCache.Get <Dictionary <Type, Table> >("TableCache");
            TableAttribute           tableAttr    = GetTableAttr(type);

            if (dicTableInfo != null && dicTableInfo.ContainsKey(type))
            {
                return(dicTableInfo[type]);
            }
            lock (getTableLock)
            {
                dicTableInfo = DataCache.Get <Dictionary <Type, Table> >("TableCache");
                if (dicTableInfo == null)
                {
                    dicTableInfo = new Dictionary <Type, Table>();
                }
                if (dicTableInfo.ContainsKey(type))
                {
                    return(dicTableInfo[type]);
                }

                Hashtable param = new Hashtable();
                param.Add("name", tableAttr.Name);
                Table table = DAL.QueryForObject <Table>("DataTools.GetTable", param);

                PropertyInfo[] properties = type.GetProperties();
                param.Clear();
                param.Add("table_id", table.id);
                param.Add("columnList", properties.ToList(item => item.Name));
                IList <Column> columnList = DAL.QueryForList <Column>("DataTools.GetColumns", param);

                foreach (Column column in columnList)
                {
                    foreach (PropertyInfo propertie in properties)
                    {
                        if (column.name.ToLower() == propertie.Name.ToLower())
                        {
                            column.property = propertie;
                        }
                    }
                }

                table.columnList = columnList;
                dicTableInfo.Add(type, table);
                DataCache.Add("TableCache", dicTableInfo, CacheItemPriority.NotRemovable);

                return(table);
            }
        }
Exemple #33
0
        public static IncidentBoxRow Load(int IncidentBoxId)
        {
            IncidentBoxRow retVal;

            // OZ 2008-12-08 Improve Performance
            if (!DataCache.TryGetValue <IncidentBoxRow>(IncidentBoxCategoryName, DataCache.EmptyUser, IncidentBoxId.ToString(), out retVal))
            {
                retVal = new IncidentBoxRow(IncidentBoxId);

                // OZ 2008-12-08 Improve Performance
                DataCache.Add(IncidentBoxCategoryName, DataCache.EmptyUser, IncidentBoxId.ToString(), retVal);
            }

            return(retVal);
        }
        public ActionResult Index(string name)
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();

            DataCache cache = new DataCache();
            Tweets entries = cache.Get(name) as Tweets;
            if (entries == null)
            {
                entries = TwitterFeed.GetTweets(name);
                cache.Add(name, entries);
                mClient.Send(new BrokeredMessage(name));
            }

            timer.Stop();
            ViewBag.LoadTime = timer.Elapsed.TotalMilliseconds;

            return View(entries);
        }