public void TestCacheHitMiss() { CacheModel cache = GetCacheModel(); CacheKey key = new CacheKey(); key.Update("testKey"); string value = "testValue"; cache[key] = value; object returnedObject = cache[key]; Assert.AreEqual(value, returnedObject); Assert.AreEqual(HashCodeProvider.GetIdentityHashCode(value), HashCodeProvider.GetIdentityHashCode(returnedObject)); CacheKey wrongKey = new CacheKey(); wrongKey.Update("wrongKey"); returnedObject = cache[wrongKey]; Assert.IsTrue(!value.Equals(returnedObject)); Assert.IsNull(returnedObject); //Assert.AreEqual(0.5, cache.HitRatio); }
/// <summary> /// Gets the cache key. /// </summary> /// <param name="request">The request.</param> /// <returns>the cache key</returns> private CacheKey GetCacheKey(RequestScope request) { CacheKey cacheKey = new CacheKey(); int count = request.DbCommand.Parameters.Count; for (int i = 0; i < count; i++) { IDataParameter dataParameter = (IDataParameter)request.DbCommand.Parameters[i]; if (dataParameter.Value != null) { cacheKey.Update(dataParameter.Value); } } cacheKey.Update(_mappedStatement.Id); cacheKey.Update(_mappedStatement.SqlMap.DataSource.ConnectionString); cacheKey.Update(request.DbCommand.CommandText); CacheModel cacheModel = _mappedStatement.Statement.CacheModel; if (!cacheModel.IsReadOnly && !cacheModel.IsSerializable) { // read/write, nonserializable cache models need to use per-session caching cacheKey.Update(request.Session); } return(cacheKey); }
private void btnShowDeletedFiles_Click(object sender, EventArgs e) { var selectedNode = tvFileSystem.SelectedNode; if (selectedNode == null) { return; } if (selectedNode is DirectoryTreeNode) { var info = selectedNode.Tag as DirectoryInfo; forDisplayFile = new CacheModel() { CreationTime = info.CreationTime, Extension = "folder", LastAccessTime = info.LastAccessTime, LastModificationTime = info.LastWriteTime, Name = info.FullName.Replace('\\', '/'), NumberOfFiles = (selectedNode as DirectoryTreeNode).NumberOfFiles, Size = (selectedNode as DirectoryTreeNode).Size }; FilterForm.RecievedFolder = forDisplayFile; FilterForm.Show(); } }
/// <summary> /// Returns copy of cached object /// </summary> public void TestReturnCopyOfCachedOject() { CacheModel cacheModel = new CacheModel("test", typeof(LruCache).FullName, 60, 1, true); Order order = new Order(); order.CardNumber = "CardNumber"; order.Date = DateTime.Now; order.LineItemsCollection = new LineItemCollection(); LineItem item = new LineItem(); item.Code = "Code1"; order.LineItemsCollection.Add(item); item = new LineItem(); item.Code = "Code2"; order.LineItemsCollection.Add(item); CacheKey key = new CacheKey(); key.Update(order); int firstId = HashCodeProvider.GetIdentityHashCode(order); cacheModel[key] = order; Order order2 = cacheModel[key] as Order; int secondId = HashCodeProvider.GetIdentityHashCode(order2); Assert.AreNotEqual(firstId, secondId, "hasCode equal"); }
public void UpdateCacheData(string path, CacheModel cacheModel) { cacheModel.LatestCheckDateTime = DateTime.Now.Ticks; var bytes = ObjectSerializer.SerializeObject(cacheModel); File.WriteAllBytes(path, bytes); }
public GraphicForm(string drive, CacheModel file) { InitializeComponent(); database = new DatabaseHelper(); selectedFile = file; selectedDrive = drive; }
public static CacheModel Deserialize(XmlNode node, ConfigurationScope configScope) { CacheModel model = new CacheModel(); NameValueCollection attributes = NodeUtils.ParseAttributes(node, configScope.Properties); model.Id = NodeUtils.GetStringAttribute(attributes, "id"); model.Implementation = NodeUtils.GetStringAttribute(attributes, "implementation"); model.Implementation = configScope.SqlMapper.TypeHandlerFactory.GetTypeAlias(model.Implementation).Class.AssemblyQualifiedName; model.IsReadOnly = NodeUtils.GetBooleanAttribute(attributes, "readOnly", true); model.IsSerializable = NodeUtils.GetBooleanAttribute(attributes, "serialize", false); int count = node.ChildNodes.Count; for (int i = 0; i < count; i++) { if (node.ChildNodes[i].LocalName == "flushInterval") { FlushInterval interval = new FlushInterval(); NameValueCollection values2 = NodeUtils.ParseAttributes(node.ChildNodes[i], configScope.Properties); interval.Hours = NodeUtils.GetIntAttribute(values2, "hours", 0); interval.Milliseconds = NodeUtils.GetIntAttribute(values2, "milliseconds", 0); interval.Minutes = NodeUtils.GetIntAttribute(values2, "minutes", 0); interval.Seconds = NodeUtils.GetIntAttribute(values2, "seconds", 0); model.FlushInterval = interval; } } return(model); }
public override void OnAuthorization(AuthorizationContext filterContext) { string token = HttpContext.Current.Request["token"]; bool isOk = false; string info = "登录超时"; object data = null; object datas = null; string type = "info"; JsonResult jsonResult = new JsonResult() { Data = new { isOk, info, data, datas, type }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; if (string.IsNullOrWhiteSpace(token)) { filterContext.Result = jsonResult; return; } CacheModel cache = CacheModel.FirstOrDefault("where cache_key = @0", token); if (cache == null) { filterContext.Result = jsonResult; } }
/// <summary> /// Initializes a new instance of the <see cref="Statement"/> class. /// </summary> /// <param name="id">The id.</param> /// <param name="parameterClass">The parameter class.</param> /// <param name="parameterMap">The parameter map.</param> /// <param name="resultClass">The result class.</param> /// <param name="resultMaps">The result maps.</param> /// <param name="listClass">The list class.</param> /// <param name="listClassFactory">The list class factory.</param> /// <param name="cacheModel">The cache model.</param> /// <param name="remapResults">if set to <c>true</c> [remap results].</param> /// <param name="extends">The extends.</param> /// <param name="sqlSource">The SQL source.</param> /// <param name="preserveWhitespace">Preserve whitespace.</param> public Statement( string id, Type parameterClass, ParameterMap parameterMap, Type resultClass, ResultMapCollection resultMaps, Type listClass, IFactory listClassFactory, CacheModel cacheModel, bool remapResults, string extends, ISqlSource sqlSource, bool preserveWhitespace) { Contract.Require.That(id, Is.Not.Null & Is.Not.Empty).When("retrieving argument id"); this.id = id; this.parameterClass = parameterClass; this.parameterMap = parameterMap; this.resultClass = resultClass; this.resultMaps = resultMaps; this.listClass = listClass; this.listClassFactory = listClassFactory; this.cacheModel = cacheModel; allowRemapping = remapResults; this.extends = extends; this.sqlSource = sqlSource; this.preserveWhitespace = preserveWhitespace; }
/// <summary> /// Returns reference to same instance of cached object /// </summary> public void TestReturnInstanceOfCachedOject() { CacheModel cacheModel = new CacheModel("test", typeof(LruCache).FullName, 60, 1, false); //cacheModel.FlushInterval = interval; //cacheModel.IsReadOnly = true; //cacheModel.IsSerializable = false; Order order = new Order(); order.CardNumber = "CardNumber"; order.Date = DateTime.Now; order.LineItemsCollection = new LineItemCollection(); LineItem item = new LineItem(); item.Code = "Code1"; order.LineItemsCollection.Add(item); item = new LineItem(); item.Code = "Code2"; order.LineItemsCollection.Add(item); CacheKey key = new CacheKey(); key.Update(order); int firstId = HashCodeProvider.GetIdentityHashCode(order); cacheModel[key] = order; Order order2 = cacheModel[key] as Order; int secondId = HashCodeProvider.GetIdentityHashCode(order2); Assert.AreEqual(firstId, secondId, "hasCode different"); }
/// <summary> /// Builds the cache model. /// </summary> /// <param name="store">The store.</param> private void BuildCacheModels(IConfigurationStore store) { for (int i = 0; i < store.CacheModels.Length; i++) { IConfiguration cacheModelConfig = store.CacheModels[i]; CacheModel cacheModel = CacheModelDeSerializer.Deserialize(cacheModelConfig, modelStore.DataExchangeFactory); string nameSpace = ConfigurationUtils.GetMandatoryStringAttribute(cacheModelConfig, ConfigConstants.ATTRIBUTE_NAMESPACE); // Gets all the flush on excecute statement id ConfigurationCollection flushConfigs = cacheModelConfig.Children.Find(ConfigConstants.ELEMENT_FLUSHONEXECUTE); for (int j = 0; j < flushConfigs.Count; j++) { string statementId = flushConfigs[j].Attributes[ConfigConstants.ATTRIBUTE_STATEMENT]; if (useStatementNamespaces) { statementId = ApplyNamespace(nameSpace, statementId); } cacheModel.StatementFlushNames.Add(statementId); } modelStore.AddCacheModel(cacheModel); } }
/// <summary> /// 获取系统的所有storages /// </summary> /// <returns></returns> private static List <StorageDAO> GetStorages() { var cacheFilter = new CacheFilter(_storageCacheKey); var cacheClient = new RedisClientCache(); List <StorageDAO> storages = cacheClient.Query <List <StorageDAO> >(cacheFilter); if (storages == null || storages.Count == 0) { string sql = "select * from t_sys_storage where misdelete=0 order by mitemid"; string connectionString = ConfigurationManager.AppSetting("ConnectionString"); IORM _orm = new SugarORM(connectionString); var client = _orm.GetSqlClient <SqlSugarClient>(); storages = client.SqlQueryable <StorageDAO>(sql).ToList(); CacheModel storageCache = new CacheModel() { Key = _storageCacheKey, Data = storages }; if (cacheClient.IsExistCacheKey(cacheFilter)) { cacheClient.Delete(cacheFilter); } cacheClient.Add(storageCache); } return(storages); }
public override object GetData(ITabContext context) { var cacheModel = new CacheModel(); cacheModel.Configuration.EffectivePercentagePhysicalMemoryLimit = HttpRuntime.Cache.EffectivePercentagePhysicalMemoryLimit; cacheModel.Configuration.EffectivePrivateBytesLimit = HttpRuntime.Cache.EffectivePrivateBytesLimit; var list = HttpRuntime.Cache.Cast <DictionaryEntry>().ToList(); foreach (var item in list) { try { var cacheEntry = MethodInfoCacheGet.Invoke(HttpRuntime.Cache, new object[] { item.Key, 1 }); var cacheItemModel = new CacheItemModel(); cacheItemModel.Key = item.Key.ToString(); cacheItemModel.Value = Serialization.GetValueSafe(item.Value); cacheItemModel.CreatedOn = GetCacheProperty(ProcessInfoUtcCreated, cacheEntry) as DateTime?; cacheItemModel.ExpiresOn = GetCacheProperty(ProcessInfoUtcExpires, cacheEntry) as DateTime?; cacheItemModel.SlidingExpiration = GetCacheProperty(ProcessInfoSlidingExpiration, cacheEntry) as TimeSpan?; cacheModel.CacheItems.Add(cacheItemModel); } catch (Exception) { return(false); } } return(cacheModel); }
private void GraphicForm_Load(object sender, EventArgs e) { perviousFileData = database.GetFileColumnHistory(selectedDrive, selectedFile.Name); selectedFile = perviousFileData.Count == 0 ? selectedFile : perviousFileData.Last(); ShowDirectoryFileDetails(); cbxGraphicOptions.SelectedIndex = 0; }
/// <summary> /// Default constructor. /// </summary> public EditModel() { Cache = new CacheModel(); Comments = new CommentModel(); Site = new SiteModel(); Params = new List <object>(); }
public ActionResult Index(Page <CacheModel> model) { if (model.CurrentPage <= 0) { model.CurrentPage = 1; } StringBuilder where = new StringBuilder("select c.*,u.ChName as Ssssname from Cache c left join XUser u on c.CacheValue = u.Id where c.DelFlag=0 "); if (model.Item != null) { if (!string.IsNullOrEmpty(model.Item.CacheKey)) { where.AppendFormat(" and CacheKey like '%{0}%' ", model.Item.CacheKey.Trim()); } if (!string.IsNullOrEmpty(model.Item.Ssssname)) { where.AppendFormat(" and u.ChName like '%{0}%' ", model.Item.Ssssname.Trim()); } } where.AppendFormat(" order by c.createtime desc "); var page = CacheModel.Page(model.CurrentPage, MTConfig.ItemsPerPage, where.ToString(), model.Item); page.Item = model.Item; LogDAL.AppendSQLLog(MTConfig.CurrentUserID, typeof(CacheModel)); return(View(page)); }
public void MakeIndexTriggerModel <T>(T model) where T : BaseEventTriggerModel <T> { CacheModel cacheModel = null; if (model is GameEventTriggerModel) { cacheModel = _gameCacheData; } else if (model is EventTriggerModel) { cacheModel = _commonCacheData; } if (model.TriggerIndex == 0) { model.TriggerIndex = IncreaseIndex(cacheModel); } else if (model.TriggerIndex > cacheModel.MaxIndex) { cacheModel.MaxIndex = model.TriggerIndex; } foreach (var child in model.SubEventTriggers) { MakeIndexTriggerModel(child); } }
private CacheModel ReadAnagramIDs(IList <string> receivedList) { var resultLists = new CacheModel { IDList = new List <int>(), WordList = new List <string>() }; var list = receivedList.Distinct(); //var resultList = new List<int>(); using (var connection = new SqlConnection(_connectionString)) { connection.Open(); var cmd = new SqlCommand("SELECT ID FROM Words WHERE Word=@word", connection); cmd.Parameters.Add(new SqlParameter("@word", SqlDbType.NVarChar)); foreach (string s in list) { cmd.Parameters["@word"].Value = s; var dr = cmd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { resultLists.IDList.Add(dr.GetInt32(0)); resultLists.WordList.Add(s); } } dr.Close(); } } return(resultLists); }
public ActionResult Edit(string id) { CacheModel model = CacheModel.SingleOrDefault(id); ViewBag.EditFlag = true; return(View(model)); }
/// <summary> /// 用户登录 /// </summary> /// <param name="email"></param> /// <param name="password"></param> /// <returns></returns> public OperationResult Login(string email, string password) { OperationResult result = new OperationResult(); var userModel = GetUser(email, password); if (userModel == null) { return(result); } TokenDTO tokenModel = new TokenDTO() { UserId = userModel.Id, UserName = userModel.Name, Token = GuidUtility.GetGuid(), ExpireDateTime = DateTime.Now.AddHours(1) }; CacheModel tokenCache = new CacheModel() { CacheType = CacheType.KeyValue, Key = tokenModel.Token, Data = tokenModel, }; result.Success = _cache.Add(tokenCache); result.Data = result.Success ? tokenModel : null; return(result); }
/// <summary> /// Adds a (named) cache model. /// </summary> /// <param name="cacheModel">The cache model.</param> public void AddCacheModel(CacheModel cacheModel) { if (cacheModels.ContainsKey(cacheModel.Id)) { throw new DataMapperException("The DataMapper already contains a CacheModel named " + cacheModel.Id); } cacheModels.Add(cacheModel.Id, cacheModel); }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); if (CacheData == null) { CacheData = CacheModel.CacheDataCreation(); } }
private CacheModel GetCacheModel() { CacheModel cache = new CacheModel("test", typeof(PerpetualCache).FullName, long.MinValue, 0, false); //cache.FlushInterval = new FlushInterval(0, 5, 0, 0); return(cache); }
public void AddCache(CacheModel cache) { if (this._cacheMaps.Contains(cache.Id)) { throw new DataMapperException("This SQL map already contains an Cache named " + cache.Id); } this._cacheMaps.Add(cache.Id, cache); }
public CacheDataManager() { _indexTriggerModels = new Dictionary <ulong, EventTriggerModel>(); _cacheData = new CacheModel(0); NotifyHelper.EventTriggerInserted += NotifyHelper_EventTriggerInserted; NotifyHelper.EventTriggerRemoved += NotifyHelper_EventTriggerRemoved; }
public ulong IncreaseIndex(CacheModel cacheModel) { if (Interlocked.Exchange(ref _atomic, 1) == 0) { cacheModel.MaxIndex++; Interlocked.Exchange(ref _atomic, 0); } return(cacheModel.MaxIndex); }
public void SetCache_SingleModel_Test() { RedisCache_HashSrategy<CacheModel> _hashStrategy = new RedisCache_HashSrategy<CacheModel>(_client); CacheModel model = new CacheModel { Age = 19 }; _hashStrategy.Set("key", new CacheModel { Age = 19, NickName = "kissnana" }); var model2 = _hashStrategy.Get("key"); Assert.AreEqual(model.Age, model2.Age); Assert.AreEqual(model.NickName, model2.NickName); Assert.AreNotEqual(model, model2); }
public GoogleProfileManagerTests() { CacheModel testCacheModel = new CacheModel { UserProfile = null }; _memoryCacheMock = MockMemoryCacheService.GetMemoryCache(_validTestSessionId, testCacheModel); _testingProfileManager = new GoogleProfileManager(_memoryCacheMock); }
private static CacheModel GetCacheModelObject(string cacheKey, object data, int cacheTime) { var expiration = TimeSpan.FromMinutes(cacheTime); var cache = new CacheModel(); cache.Expiration = expiration; cache.Key = cacheKey; cache.Value = data; return(cache); }
private CacheModel GetCacheModel() { CacheModel cache = new CacheModel(); cache.FlushInterval = new FlushInterval(); cache.FlushInterval.Minutes = 5; cache.Implementation = "Mybatis.Mapper.Configuration.Cache.Lru.LruCacheController, Mybatis.Mapper"; cache.Initialize(); return(cache); }
public JsonResult editBir([FromBody] editBirModel value) { try { var token = value.token; var cache = CacheUntity.GetCache <UserCacheModel>(token); //var birdModelStr = value.model; //var birdModel = value.model; //JsonConvert.DeserializeObject<Birdhouse>(birdModelStr); Birdhouse birdhouse = _birdhouse.GetByID(value.id); birdhouse.update_time = Util.ToUnixStamp(DateTime.Now).ToString(); //{"token":"08ea69102b204b09bd66cdbcf661dfef","min_temperature":"12","max_temperature":"23","min_humidity":"11" //,"max_humidity":"22","warning_ammonia_concentration":0,"warning_negative_pressure":0,"id":238} birdhouse.min_humidity = value.min_humidity.ToString("F1"); birdhouse.min_temperature = value.min_temperature.ToString("F1"); birdhouse.max_humidity = value.max_humidity.ToString("F1"); birdhouse.max_temperature = value.max_temperature.ToString("F1"); birdhouse.warning_ammonia_concentration = value.warning_ammonia_concentration.ToString(); birdhouse.warning_negative_pressure = value.warning_negative_pressure.ToString(); _birdhouse.Update(birdhouse); var model1 = _cache.FillCacheWithToken(token, cache.member); CacheUntity.SetCache(token, model1.Result); var model = new CacheModel(); model.serial = birdhouse.equipment_id; var equip = _equipment.GetCacheModelByserial(model.serial); model.bind_status = equip.bind_status; model.birdhouse_name = equip.birdhouse_name; model.phone = 5; model.sms = 5; model.smsEnableFlag = true; model.call_num = 0; model.max_humidity = equip.max_humidity; model.min_humidity = equip.min_humidity; model.max_temperature = equip.max_temperature; model.min_temperature = equip.min_temperature; model.warning_ammonia_concentration = equip.warning_ammonia_concentration; model.warning_negative_pressure = equip.warning_negative_pressure; model.name = equip.name; model.status = equip.status; model.username = equip.username; model.warning_mobile = equip.warning_mobile; model.currentTemp = "0"; model.currentHumidity = "0"; model.currentPower = "0"; model.setDate = DateTime.Now.Date; CacheUntity.SetCache(birdhouse.equipment_id, model); return(Json(new { code = 1, status = "success", msg = "添加成功" })); } catch (Exception e) { LogHelper.Error(JsonConvert.SerializeObject(e)); return(Json(new nologin())); } }
public void Cache_Expire_Test() { string key="expireKey"; DateTime expireDate = DateTime.Now.Add(new TimeSpan(0,0,1)); RedisCache_HashSrategy<CacheModel> _hashStrategy = new RedisCache_HashSrategy<CacheModel>(_client); var model = new CacheModel { Age = 19 }; _hashStrategy.Set(key, model); _hashStrategy.SetExpire(key,expireDate); Thread.Sleep(5000); var model2=_hashStrategy.Get(key); Assert.IsTrue(model2==null); }
/// <summary> /// -处理缓存中和传来的报警信息--添加新的报警信息到变量中 /// </summary> /// <param name="mrtm"></param> /// <param name="cm"></param> private void GetEndUnNormal(Datas mrtm, CacheModel cm) { //0-报警,1-断电,2-调校,3-超量程,4-分站故障 if (int.Parse(cm.State) > 0 && int.Parse(cm.State) < 4) // alarm strbAlarm.Append("'" + iConfig.CoalCode + "','" + mrtm.DevCode + "','" + mrtm.DevName + "','" + mrtm.DevType + "','" + mrtm.DevAddress + "','" + mrtm.DevUnit + "','" + mrtm.MonitorLRV + "','" + mrtm.MonitorURV + "','" + mrtm.AlarmLRV + "','" + mrtm.AlarmURV + "','" + mrtm.TurnOffValue + "','" + mrtm.TurnOnValue + "','" + cm.Atime + "','" + mrtm.RealTime + "','" + GetDuration(cm.Atime, DateTime.Parse(mrtm.RealTime)) + "','0','','" + cm.MaxValue + "','" + cm.MaxValueTime + "','" + cm.State + "'Ï"); else //fault strbFault.Append("'" + iConfig.CoalCode + "','" + mrtm.DevCode + "','" + mrtm.DevName + "','" + mrtm.DevType + "','" + mrtm.DevAddress + "','" + mrtm.DevUnit + "','" + mrtm.MonitorLRV + "','" + mrtm.MonitorURV + "','" + mrtm.AlarmLRV + "','" + mrtm.AlarmURV + "','" + mrtm.TurnOffValue + "','" + mrtm.TurnOnValue + "','" + mrtm.DevState + "','" + mrtm.LinkSenId + "','" + cm.Atime + "','" + mrtm.RealTime + "','" + GetDuration(cm.Atime, DateTime.Parse(mrtm.RealTime)) + "'Ï"); }
private string GetFinishSql(MRtm mrtm,CacheModel cm) { string sqlString = string.Empty; if (int.Parse(cm.State) > 4)//故障 sqlString = "UPDATE [TN_FaultRecode] SET [EndTime] = '" + mrtm.RealTime + "',[Duration] = '" + GetDuration(mrtm.RealTime, cm.Atime) + "' WHERE [CoalCode]='" + mrtm.CoalCode + "' AND [DevCode] = '" + mrtm.DevCode + "' AND [StartTime] = '" + cm.Atime + "';"; else if(int.Parse(cm.State) > 0)//报警 [AlarmETime] ,[Duration] ,[SwitchCount] ,[SwitchDetails] ,[DevMaxValue] ,[DevMaxTime] sqlString = "UPDATE [TN_AlarmRecode] SET [AlarmETime] = '" + mrtm.RealTime + "',[Duration] = '" + GetDuration(mrtm.RealTime, cm.Atime) + "',[SwitchCount]='0',[SwitchDetails]='',[DevMaxValue]='" + cm.MaxValue + "',[DevMaxTime]='" + cm.MaxValueTime + "' WHERE [CoalCode]='" + mrtm.CoalCode + "' AND [DevCode] = '" + mrtm.DevCode + "' AND [AlarmSTime] = '" + cm.Atime + "';"; return sqlString; }
/// <summary> /// Default constructor. /// </summary> public EditModel() { Cache = new CacheModel(); Comments = new CommentModel(); Site = new SiteModel(); Params = new List<object>(); }