/// <summary> /// Gets (and adds if necessary) an item from the cache with the specified absolute expiration date (from NOW) /// </summary> /// <typeparam name="TT"></typeparam> /// <param name="cacheKey"></param> /// <param name="priority"></param> /// <param name="refreshAction"></param> /// <param name="cacheDependency"></param> /// <param name="timeout">This will set an absolute expiration from now until the timeout</param> /// <param name="getCacheItem"></param> /// <param name="syncLock"></param> /// <returns></returns> private TT GetCacheItem <TT>(string cacheKey, CacheItemPriority priority, CacheItemRemovedCallback refreshAction, CacheDependency cacheDependency, TimeSpan?timeout, Func <TT> getCacheItem, object syncLock) { var result = _cache.Get(cacheKey); if (result == null) { lock (syncLock) { result = _cache.Get(cacheKey); if (result == null) { result = getCacheItem(); if (result != null) { //we use Insert instead of add if for some crazy reason there is now a cache with the cache key in there, it will just overwrite it. _cache.Insert(cacheKey, result, cacheDependency, timeout == null ? System.Web.Caching.Cache.NoAbsoluteExpiration : DateTime.Now.Add(timeout.Value), TimeSpan.Zero, priority, refreshAction); } } } } return(result.TryConvertTo <TT>().Result); }
public List <T> GetList <T>(string keyColl) where T : class { var list = new List <T>(); if (this._cache.Get(keyColl) != null) { var keys = (List <string>)_cache.Get(keyColl); var tmpKeys = new List <string>(); if (!keys.Any()) { return(new List <T>()); } foreach (var item in keys) { tmpKeys.Add(item); var data = (T)_cache.Get(item); if (data != null) { list.Add(data); } } if (tmpKeys.Any()) { var json = Newtonsoft.Json.JsonConvert.SerializeObject(tmpKeys) + ""; _cache.Remove(keyColl); _cache.Insert(keyColl, json); } } return(list); }
/// <summary> /// 设置缓存 /// </summary> /// <param name="Key">主键</param> /// <param name="obj">键值</param> /// <param name="dp">依赖项</param> public static void Set(string Key, object obj, CacheDependency dp) { if (ObjCache[Key] != null) { ObjCache.Remove(Key); } ObjCache.Insert(Key, obj, dp); }
public void InsertToCache(string key, object obj, int timeout) { if (string.IsNullOrEmpty(key) || obj == null) { return; } cache.Insert(key, obj, null, DateTime.Now.AddMinutes(timeout), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null); }
/// <summary> /// 启动更新数据缓存 /// </summary> /// <param name="obj"></param> public void ExecUpdateCacheData() { System.Web.Caching.Cache currCache = HttpRuntime.Cache; int cacheMinute = 50; bool executeFlag = true; while (executeFlag) { executeFlag = false; try { #region 缓存处理 //加载缓存服务配置 DataTable dtservconfig = BaseServiceUtility.GetServiceConfig(APPConfig.GetAPPConfig().GetConfigValue("ServiceConfigPath", "")); currCache.Insert("serviceConfig", dtservconfig, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, cacheMinute, 0)); //缓存默认公共语言包 string defaultlang = APPConfig.GetAPPConfig().GetConfigValue("currlang", ""); string commoni18nLangPath = string.Format(APPConfig.GetAPPConfig().GetConfigValue("Commoni18nLang", ""), defaultlang); DataTable i18nCommonCurrLang = BaseServiceUtility.GetI18nLang(commoni18nLangPath); currCache.Insert("i18nCommonCurrLang", i18nCommonCurrLang, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, cacheMinute, 0)); //缓存默认各模块语言包,多个模块独立累加 string FrameNodei18nLang = string.Format(APPConfig.GetAPPConfig().GetConfigValue("FrameNodei18nLang", ""), defaultlang); DataTable i18nFrameNodei18nLang = BaseServiceUtility.GetI18nLang(FrameNodei18nLang); currCache.Insert("i18nFrameNodei18nLang", i18nFrameNodei18nLang, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, cacheMinute, 0)); //缓存数据节点 DistributeDataNodeManagerParams distManagerParam = new DistributeDataNodeManagerParams(); //分布式管理参数 FrameNodeBizCommon fnodecom = new FrameNodeBizCommon(); distManagerParam = fnodecom.GetDistributeDataNodeManager("1"); if (distManagerParam.DistributeDataNodes.Count > 0) { currCache.Insert("dataNodes", distManagerParam, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, cacheMinute, 0)); } //缓存业务节点 DataTable dtbiznodeaddrconfig = BaseServiceUtility.GetBizNodesConfig(APPConfig.GetAPPConfig().GetConfigValue("XmldataPath", "") + "\\SSY_BIZNODE_ADDR.xml"); currCache.Insert("bizNodeConfig", dtbiznodeaddrconfig, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, cacheMinute, 0)); Common.Utility.RecordLog("完成节点中心配置缓存!", this.logpathForDebug, this.isLogpathForDebug); #endregion } catch (Exception ex) { //记录结果 Common.Utility.RecordLog("配置节点中心缓存,发生异常!原因:" + ex.Message, this.logpathForDebug, this.isLogpathForDebug); } Thread.Sleep(this.internalTime * 60000);//延迟秒级别 executeFlag = true; } }
/// <summary> /// 创建缓存项的文件依赖 /// </summary> /// <param name="key">缓存Key</param> /// <param name="obj">object对象</param> /// <param name="fileName">文件绝对路径</param> public static void Insert(string key, object obj, string fileName) { key = ConfigHelper.AppSettings(CacheNamePrefix) + key; //创建缓存依赖项 CacheDependency dep = new CacheDependency(fileName); //创建缓存 ObjCache.Insert(key, obj, dep); }
public void Set(string key, object data) { string json = data.ToJsonString(); if (string.IsNullOrEmpty(key) || data == null) { return; } cache.Insert(key, json, null, DateTime.Now.AddMinutes(TimeOut), TimeSpan.Zero, CacheItemPriority.High, callBack); }
/// <summary> /// 加入当前对象到缓存中 /// </summary> /// <param name="objId">key for the object</param> /// <param name="o">object</param> public void AddObject(string objId, object o) { if (objId == null || objId.Length == 0 || o == null) { return; } CacheItemRemovedCallback callBack = new CacheItemRemovedCallback(onRemove); webCacheforfocus.Insert(objId, o, null, DateTime.Now.AddMinutes(TimeOut), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, callBack); }
public void Insert(string key, object value) { lock (AspNetCache.cacheLocker) { if (cache.Get(key) != null) { cache.Remove(key); } cache.Insert(key, value); } }
public bool AddCache <T>(string key, T value) { try { _cache.Insert(key, value, null, DateTime.Now.AddSeconds(this.TimeOut), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, null); } catch (Exception) { return(false); } return(true); }
/// <summary> /// 插入缓存 /// </summary> /// <param name="key"></param> /// <param name="obj"></param> /// <returns></returns> public bool Insert(string key, object obj) { if (obj == null) { return(false); } lock (LockObject) { cache.Insert(key, obj, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration); } return(true); }
/// <summary> /// Store the data, overwrite if already exist /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public override void Set(string key, object value, DateTime?ExpireDateTime) { //只存入本地内存 if (ExpireDateTime != null) { _Cache.Insert(key, value, null, Convert.ToDateTime(ExpireDateTime), TimeSpan.Zero, CacheItemPriority.Normal, null); } else { _Cache.Insert(key, value); } }
/// <summary> /// SetServiceObject /// </summary> /// <param name="key">key</param> /// <param name="value">obj</param> /// <param name="dep">dep</param> /// <param name="seconds">seconds</param> /// <param name="priority">priority</param> public static void Insert( string key, object value, CacheDependency dep, int seconds, CacheItemPriority priority) { if (value != null) { Cache.Insert( key, value, dep, DateTime.Now.AddSeconds(_factor * seconds), TimeSpan.Zero, priority, null); } }
public static void Set_Add(this System.Web.Caching.Cache cache, string Key, object Value, int Hour) { if (cache[Key] == null) { cache.Insert(Key, Value, null, DateTime.Now.AddHours(Hour), System.Web.Caching.Cache.NoSlidingExpiration); } else { //object temp = cache[Key]; cache.Remove(Key); cache.Insert(Key, Value, null, DateTime.Now.AddHours(Hour), System.Web.Caching.Cache.NoSlidingExpiration); } }
/// <summary> /// 加入当前对象到缓存中 /// </summary> public virtual void Add(string key, object value, Microsoft.Practices.EnterpriseLibrary.Caching.CacheItemPriority scavengingPriority, Microsoft.Practices.EnterpriseLibrary.Caching.ICacheItemRefreshAction refreshAction, params Microsoft.Practices.EnterpriseLibrary.Caching.ICacheItemExpiration[] expirations) { if (expirations[0] is Microsoft.Practices.EnterpriseLibrary.Caching.Expirations.AbsoluteTime) { DateTime expire = ((Microsoft.Practices.EnterpriseLibrary.Caching.Expirations.AbsoluteTime)expirations[0]).AbsoluteExpirationTime.ToLocalTime(); webCache.Insert(key, value, null, expire, System.Web.Caching.Cache.NoSlidingExpiration); } if (expirations[0] is Microsoft.Practices.EnterpriseLibrary.Caching.Expirations.SlidingTime) { TimeSpan expire = ((Microsoft.Practices.EnterpriseLibrary.Caching.Expirations.SlidingTime)expirations[0]).ItemSlidingExpiration; webCache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, expire); } }
public static PageInfo Init(string path) { PageInfo pi = null; if (Config.Main.PageCache == 0) { pi = new PageInfo(path); } else { System.Web.Caching.Cache cache = HttpContext.Current.Cache; string cacheKey = "CachedPageInfo['" + Sota.Web.SimpleSite.Path.Full + "']"; if (cache[cacheKey] == null) { pi = new PageInfo(path); if (pi.Path.Length > 0) { if (pi.IsPagex) { cache.Insert(cacheKey , pi , new CacheDependency(new string[] { pi.DataFileName, HttpContext.Current.Request.MapPath(Config.ConfigFolderPath + Keys.UrlPathDelimiter + Keys.ConfigPagex) }) , DateTime.Now.AddMinutes(Config.Main.PageCache) , TimeSpan.Zero); } else { cache.Insert(cacheKey , pi , new CacheDependency(pi.DataFileName) , DateTime.Now.AddMinutes(Config.Main.PageCache) , TimeSpan.Zero); } } } else { pi = (PageInfo)cache[cacheKey]; } } if (pi.Path.Length == 0) { return(null); } HttpContext.Current.Items[Keys.ContextPageInfo] = pi; return(pi); }
public void Put(string key, object value) { Ensure.NotNullOrWhiteSpace(key, "key"); Ensure.NotNull(value, "value"); string cacheKey = GetCacheKey(key); if (cache[cacheKey] != null) { cache.Remove(cacheKey); } if (!rootCacheKeyStored) { StoreRootCacheKey(); } cache.Insert(cacheKey, new DictionaryEntry(key, value), new CacheDependency(null, new[] { rootCacheKey }), System.Web.Caching.Cache.NoAbsoluteExpiration, this.Expiration, this.Priority, null); }
/// <inheritdoc /> public void Put(object key, object value) { if (key == null) { throw new ArgumentNullException(nameof(key), "null key not allowed"); } if (value == null) { throw new ArgumentNullException(nameof(value), "null value not allowed"); } var cacheKey = GetCacheKey(key); if (Log.IsDebugEnabled()) { Log.Debug( _cache[cacheKey] != null ? "updating value of key '{0}' to '{1}'." : "adding new data: key={0}&value={1}", cacheKey, value); } if (!_rootCacheKeyStored) { StoreRootCacheKey(); } _cache.Insert( cacheKey, new DictionaryEntry(key, value), new CacheDependency(null, new[] { _rootCacheKey }), UseSlidingExpiration ? System.Web.Caching.Cache.NoAbsoluteExpiration : DateTime.UtcNow.Add(Expiration), UseSlidingExpiration ? Expiration : System.Web.Caching.Cache.NoSlidingExpiration, Priority, null); }
/// <summary> /// 设置当前应用程序指定CacheKey的Cache值 /// </summary> /// <param name="CacheKey"> /// <param name="objObject"> public void Add(string CacheKey, object objObject) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject); AddFileCache(CacheKey, objObject); }
/// <summary> /// 设置当前应用程序指定CacheKey的Cache值 /// </summary> /// <param name="CacheKey"> /// <param name="objObject"> public void Add(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration); AddFileCache(CacheKey, objObject); }
/// <summary> /// 按秒缓存对象 并建立具有优先级的依赖项 /// </summary> /// <param name="key"></param> /// <param name="obj"></param> /// <param name="dep"></param> /// <param name="seconds"></param> /// <param name="priority"></param> public static void Insert(string key, object obj, CacheDependency dep, int seconds, CacheItemPriority priority) { if (obj != null) { _cache.Insert(CachePrefix + key, obj, dep, DateTime.Now.AddSeconds(Factor * seconds), TimeSpan.Zero, priority, null); } }
/// <summary> /// 设置数据缓存 /// </summary> public static void SetCache(string CacheKey, object objObject, int expiration) { System.Web.Caching.Cache objCache = HttpRuntime.Cache; DateTime expirationTime = DateTime.Now.AddMinutes(expiration); objCache.Insert(CacheKey, objObject, null, expirationTime, Cache.NoSlidingExpiration); }
private void PutItem( string qualifiedKey, string key, string dependencyKey, object value, TimeSpan expiryTime, bool sliding) { var dependency = dependencyKey == null ? null : new CacheDependency(null, new [] { dependencyKey }); var absExpiration = sliding ? System.Web.Caching.Cache.NoAbsoluteExpiration : Platform.Time.Add(expiryTime); var slidingExpiration = sliding ? expiryTime : System.Web.Caching.Cache.NoSlidingExpiration; _cache.Insert( qualifiedKey, new DictionaryEntry(key, value), dependency, absExpiration, slidingExpiration, CacheItemPriority.Normal, OnCacheItemRemoved); }
private static void BaseInsert(string key, object value, CacheDependency dep, DateTime absoluteExpiration, TimeSpan slidingExpiration, System.Web.Caching.CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback) { if (value != null) { _cache.Insert(key, value, dep, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); } }
/// <summary> /// Adds the specified key and object to the cache. /// </summary> /// <param name="key">key</param> /// <param name="obj">object</param> /// <param name="dep">cache dependency</param> public void Add(string key, object obj, CacheDependency dep) { if (IsEnabled && (obj != null)) { _cache.Insert(key, obj, dep, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.AboveNormal, null); } }
public static string GetVersionNumber(System.Web.Caching.Cache cache) { const string versionNumberCacheKey = "versionNumber"; string versionNumber = string.Empty; try { versionNumber = (string)cache.Get(versionNumberCacheKey); } catch { } if (string.IsNullOrEmpty(versionNumber)) { const string style = "color:{0};font-weight:{1};"; string colour = "white"; string weight = "normal"; System.Reflection.Assembly executingAssembly = System.Reflection.Assembly.GetExecutingAssembly(); if (executingAssembly != null) { System.Reflection.AssemblyName executingAssemblyName = executingAssembly.GetName(); if (executingAssemblyName != null) { versionNumber = executingAssemblyName.Version.Major + "." + executingAssemblyName.Version.Minor + "." + executingAssemblyName.Version.Build + " "; } } #if DEBUG versionNumber += "DEBUG"; // Two attributes below are Handled via CSS colour = "bddbf2"; weight = "normal"; // Add the database name we are currently connected to. string databaseName = "unknown"; try { using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Orchestrator"].ConnectionString)) { databaseName = con.Database; } } catch {} versionNumber = string.Format("{0} <span>{1}</span>", versionNumber, databaseName); #endif if (versionNumber != string.Empty) { versionNumber = "<span style=\"" + string.Format(style, colour, weight) + "\">v" + versionNumber + "</span>"; try { cache.Insert(versionNumberCacheKey, versionNumber); } catch { } } } return(versionNumber); }
public void Insert(string key, object value, int cacheTime) { System.Web.Caching.Cache caches = cache; DateTime now = DateTime.Now; caches.Insert(key, value, null, now.AddSeconds(cacheTime), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, null); }
public static void SetCacheByFileDependency(string CacheKey, object objObject, System.Web.Caching.CacheDependency cd, DateTime absoluteExpiration, TimeSpan slidingExpiration) { CacheItemRemovedCallback onRemove = new CacheItemRemovedCallback(RemovedCallback); System.Web.Caching.Cache objCache = HttpRuntime.Cache; objCache.Insert(CacheKey, objObject, cd, absoluteExpiration, slidingExpiration, CacheItemPriority.High, onRemove); }
protected static int _timeOut = 720; // 设置缓存存活期为720分钟(12小时) /// <summary> /// 设置到期相对时间[单位:/分钟] /// </summary> //public int TimeOut //{ // set { _timeOut = value > 0 ? value : 6000; } // get { return _timeOut > 0 ? _timeOut : 6000; } //} /// <summary> /// 设置当前应用程序指定CacheKey的Cache值 /// </summary> /// <param name="CacheKey"></param> /// <param name="objObject"></param> public static void SetCache(string CacheKey, object objObject) { if (CacheKey == null || CacheKey.Length == 0 || objObject == null) { return; } webCache.Insert(CacheKey, objObject, null, DateTime.UtcNow.AddMinutes(_timeOut), System.Web.Caching.Cache.NoSlidingExpiration); }
public FieldCacheFacade() { string xmlFile = HttpContext.Current.Server.MapPath("~/schemamapping.xml"); CacheDependency xmlDependency = new CacheDependency(xmlFile); Cache cache = new Cache(); cache.Insert("", null, xmlDependency); }
public void AddObject(string objId, object o) { if (string.IsNullOrEmpty(objId) || string.IsNullOrEmpty(objId.Trim())) { return; } CacheItemRemovedCallback callback = new CacheItemRemovedCallback(onRemove); if (TimeOut == 7200) { webCache.Insert(objId, o, null, DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.High, callback); } else { webCache.Insert(objId, o, null, DateTime.Now.AddSeconds(TimeOut), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, callback); } }
public static IEnumerable<IPublishedContent> GetMotos(Cache motosCache) { var motos = motosCache["Motos"] as IEnumerable<IPublishedContent>; if (motos == null) { var expiration = UmbracoHelper.TypedContentSingleAtXPath("/root/sysSiteSettings").GetPropertyValue<int>("cacheExpTimeMotos"); motos = UmbracoHelper.TypedContentAtXPath("/root/mainpage/Catalog//Bike"); motosCache.Insert("Motos", motos, null, DateTime.Now.AddHours(expiration), TimeSpan.Zero); return motos; } return motos; }
public static Credential CreateInstance(string uid, Cache cache) { if (cache != null && !cache.Exists(uid)) { Credential c = new Credential(uid, cache); cache.Insert(uid, c, null, DateTime.MaxValue, DefaultDuration); return c; } else { return cache[uid] as Credential; } }
public static BritBoxingTwitterInfo Create(Cache cache, TwitterService service, bool useCache) { if (!useCache) { return new BritBoxingTwitterInfo(cache, service); } var info = cache["BritBoxingTwitterInfo"] as BritBoxingTwitterInfo; if (info == null) { info = new BritBoxingTwitterInfo(cache, service); cache.Insert("BritBoxingTwitterInfo", info); } return info; }
public AboutPresentationModel() { Cache = HttpContext.Current.Cache; if (Cache["key"] == null) //Initialize the datasource { List<Message> collection = new List<Message>(); //Some example data, for demo purpose collection.Add(new Message { Name = "Peter Pan", MessageText = "Ping pong pan..." }); collection.Add(new Message { Name = "bart Simpson", MessageText = "The sky is blue, you are yellow" }); collection.Add(new Message { Name = "John Doe", MessageText = "Hi, I'am John" }); Cache.Insert("key", collection.AsEnumerable(), null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(30)); } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); _cache = Context.Cache; BusinessLogic.Parameter.Parameter par = new BusinessLogic.Parameter.Parameter(); DataSet.DSParameter ds = par.GetParamerter(); System.TimeSpan span = new TimeSpan(0, 0, 2, 20, 0); _cache.Insert("data", ds, null, Cache.NoAbsoluteExpiration, span, CacheItemPriority.Default, new CacheItemRemovedCallback(RefreshData)); }
internal static void SaveCachedReport(Report r, string file, Cache c) { if (!ReportHelper.DoCaching) // caching is disabled return; c.Insert(file, r.ReportDefinition, new CacheDependency(file)); return; }
private static void CacheJson(Cache cache, string key, object value, string pathToFile) { CacheDependency dependency = new CacheDependency(pathToFile); cache.Insert(key, value, dependency, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, JsonItemRemovedCallback); }
/// <summary> /// Gets the member list. /// </summary> /// <param name="Refresh"> /// if set to <c>true</c> [refresh]. /// </param> /// <param name="ADDomain"> /// The AD domain. /// </param> /// <param name="AppCache"> /// The app cache. /// </param> /// <returns> /// A System.Data.DataTable value... /// </returns> /// <remarks> /// </remarks> public static DataTable GetMemberList(bool Refresh, string ADDomain, Cache AppCache) { // see if we want to refresh, if not, get it from the cache if available if (! Refresh) { var tmp = AppCache.Get("ADUsersAndGroups" + ADDomain); if (tmp != null) { return ((DataSet)tmp).Tables[0]; } } // create dataset using (var ds = new DataSet()) { using (var dt = new DataTable()) { ds.Tables.Add(dt); var dc = new DataColumn("DisplayName", typeof(string)); dt.Columns.Add(dc); dc = new DataColumn("AccountName", typeof(string)); dt.Columns.Add(dc); dc = new DataColumn("AccountType", typeof(string)); dt.Columns.Add(dc); // add built in users first dt.Rows.Add(new object[] { "Admins", "Admins", "group" }); dt.Rows.Add(new object[] { "All Users", "All Users", "group" }); dt.Rows.Add(new object[] { "Authenticated Users", "Authenticated Users", "group" }); dt.Rows.Add(new object[] { "Unauthenticated Users", "Unauthenticated Users", "group" }); // construct root entry using (var rootEntry = GetDomainRoot(ADDomain)) { if (ADDomain.Trim().ToLower().StartsWith("ldap://")) { var DomainName = GetNetbiosName(rootEntry); // get users/groups var mySearcher = new DirectorySearcher(rootEntry); mySearcher.Filter = "(|(objectClass=group)(&(objectClass=user)(objectCategory=person)))"; mySearcher.PropertiesToLoad.Add("cn"); mySearcher.PropertiesToLoad.Add("objectClass"); mySearcher.PropertiesToLoad.Add("sAMAccountName"); SearchResultCollection mySearcherSearchResult; try { mySearcherSearchResult = mySearcher.FindAll(); foreach (SearchResult resEnt in mySearcherSearchResult) { var entry = resEnt.GetDirectoryEntry(); var name = (string)entry.Properties["cn"][0]; var abbreviation = (string)entry.Properties["sAMAccountName"][0]; var accounttype = GetAccountType(entry); dt.Rows.Add( new object[] { name, DomainName + "\\" + abbreviation, accounttype.ToString() }); } } catch { throw new Exception("Could not get users/groups from domain '" + ADDomain + "'."); } } else if (ADDomain.Trim().ToLower().StartsWith("winnt://")) { var DomainName = rootEntry.Name; // Get the users rootEntry.Children.SchemaFilter.Add("user"); foreach (DirectoryEntry user in rootEntry.Children) { var fullname = (string)user.Properties["FullName"][0]; var accountname = user.Name; dt.Rows.Add( new object[] { fullname, DomainName + "\\" + fullname, ADAccountType.user.ToString() }); } // Get the users rootEntry.Children.SchemaFilter.Add("group"); foreach (DirectoryEntry user in rootEntry.Children) { var fullname = user.Name; var accountname = user.Name; dt.Rows.Add( new object[] { fullname, DomainName + "\\" + fullname, ADAccountType.group.ToString() }); } } } // add dataset to the cache AppCache.Insert("ADUsersAndGroups" + ADDomain, ds); // return datatable return dt; } } }
public void SetCache(Cache cache, string cacheKey, object value, int? tenantId = null, int expirationSeconds = 0) { string key = GetTenantCacheKey(cacheKey, tenantId); if (expirationSeconds == 0) { cache[key] = value; } else { DateTime cacheUntil = DateTime.UtcNow.AddSeconds(expirationSeconds); cache.Insert(key, value, null, cacheUntil, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Default, null); } }
/// <summary> /// /// </summary> /// <param name="connectionString"></param> /// <param name="cmdType"></param> /// <param name="cmdText"></param> /// <param name="commandParameters"></param> /// <returns></returns> //-------------------------------------------------------------------------------------------------------------- public static SqlDataReader ExecuteCacheReader(string connectionString, CommandType cmdType, string cmdText,string CacheKey, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(connectionString); PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); SqlCacheDependency dependency = new SqlCacheDependency(cmd); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); Cache cache = new Cache(); cache.Add(CacheKey, "", dependency, System.Web.Caching.Cache.NoAbsoluteExpiration,System.Web.Caching.Cache.NoSlidingExpiration,System.Web.Caching.CacheItemPriority.Default , null); cache.Insert(CacheKey, rdr, dependency); return (SqlDataReader)cache.Get(CacheKey) ; // conn.Close(); // System.Web.HttpContext.Current.Response.Write(ex.Message.ToString()); }
protected string TryFindViewFromViewModel(Cache cache, object viewModel) { if (viewModel != null) { var viewModelType = viewModel.GetType(); var cacheKey = "ViewModelViewName_" + viewModelType.FullName; var cachedValue = (string)cache.Get(cacheKey); if (cachedValue != null) { return cachedValue != NoVirtualPathCacheValue ? cachedValue : null; } while (viewModelType != typeof(object)) { var viewModelName = viewModelType.Name; var namespacePart = viewModelType.Namespace.Substring("FODT.".Length); var virtualPath = "~/" + namespacePart.Replace(".", "/") + "/" + viewModelName.Replace("ViewModel", "") + ".cshtml"; if (Exists(virtualPath) || VirtualPathProvider.FileExists(virtualPath)) { cache.Insert(cacheKey, virtualPath, null /* dependencies */, Cache.NoAbsoluteExpiration, _defaultCacheTimeSpan); return virtualPath; } viewModelType = viewModelType.BaseType; } // no view found cache.Insert(cacheKey, NoVirtualPathCacheValue, null /* dependencies */, Cache.NoAbsoluteExpiration, _defaultCacheTimeSpan); } return null; }
/// <summary> /// SaveImage saves the bytes to a file and returns the file name. The cache is used to remember /// the temporary file names and to timeout (and delete) the file. /// </summary> /// <param name="ba"></param> /// <param name="c"></param> /// <returns></returns> static internal string SaveImage(string path, byte[] ba, Cache c) { Stream io = null; string filename; string url; try { io = ImageHelper.GetIOStream(path, out filename, out url); io.Write(ba, 0, ba.Length); io.Close(); io = null; ImageCallBack icb = new ImageCallBack(); CacheItemRemovedCallback onRemove = new CacheItemRemovedCallback(icb.RemovedCallback); c.Insert(Path.GetFileNameWithoutExtension(filename), filename, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero, CacheItemPriority.Normal, onRemove); } finally { if (io != null) io.Close(); } return url; }
public void insertCache(string key, object value , CacheDependency dependency) { Cache cache = new Cache(); cache.Insert(key, value, dependency); }