public static string SaveNamedTmpFile(Image image, ICaptureDetails captureDetails, OutputFormat outputFormat, int quality, bool reduceColors) { string pattern = conf.OutputFileFilenamePattern; if (pattern == null || string.IsNullOrEmpty(pattern.Trim())) { pattern = "greenshot ${capturetime}"; } string filename = FilenameHelper.GetFilenameFromPattern(pattern, outputFormat, captureDetails); // Prevent problems with "other characters", which causes a problem in e.g. Outlook 2007 or break our HTML filename = Regex.Replace(filename, @"[^\d\w\.]", "_"); // Remove multiple "_" filename = Regex.Replace(filename, @"_+", "_"); string tmpFile = Path.Combine(Path.GetTempPath(), filename); LOG.Debug("Creating TMP File: " + tmpFile); // Catching any exception to prevent that the user can't write in the directory. // This is done for e.g. bugs #2974608, #2963943, #2816163, #2795317, #2789218 try { ImageOutput.Save(image, tmpFile, true, quality, reduceColors, false); tmpFileCache.Add(tmpFile, tmpFile); } catch (Exception e) { // Show the problem MessageBox.Show(e.Message, "Error"); // when save failed we present a SaveWithDialog tmpFile = ImageOutput.SaveWithDialog(image, captureDetails); } return(tmpFile); }
public void SetUp() { cacheHelper = new CacheHelper(); cacheHelper.Add("object1", "key1"); cacheHelper.Add("object2", "key2"); cacheHelper.Add("object3", "key3"); cacheHelper.Add("object4", "key4"); _count = cacheHelper.GetAllCount(); }
//public MoviesDTO GetMoviesByGenre(int genreId) //{ // string cacheKey = string.Format("GENRE_MOVIE_CACHE_KEY_{0}", genreId); // var movies = (MoviesDTO)_cacheHelper.Get(cacheKey); // if (movies == null) // { // var request = new RestRequest(string.Format("/genre/{0}/movies", genreId)); // movies = base.ExecuteRequest<MoviesDTO>(request); // _cacheHelper.Add(new CacheItem(cacheKey, movies)); // } // return movies; //} public GenresDTO GetGenres() { var genres = (GenresDTO)_cacheHelper.Get("GENRE_CACHE_KEY"); if (genres == null) { var request = new RestRequest("genre/movie/list"); genres = base.ExecuteRequest <GenresDTO>(request); _cacheHelper.Add(new CacheItem("GENRE_CACHE_KEY", genres)); } return(genres); }
/// <summary> /// Get Latest tv from themoviedb API /// </summary> /// <returns>Tv</returns> public TvDTO GetLatest() { var tv = (TvDTO)_cacheHelper.Get("LATEST_TV"); if (tv == null) { var request = new RestRequest("tv/latest"); tv = base.ExecuteRequest <TvDTO>(request); _cacheHelper.Add("LATEST_TV", tv); } return(tv); }
public static User LoadSingle(long userId, bool notFromCache = false) { if (userId == 0) { return(null); } User toRet; if (!CacheHelper.Get(Module + "_" + userId.ToUiString(), out toRet) || notFromCache) { var predicate = PredicateBuilder.True <User>(); predicate = predicate.And(e => e.Id == userId); var userRepository = new UserRepository(); toRet = userRepository.LoadSearch(predicate).First(); if (toRet != null) { if (toRet.Roles.Where(r => r.Id == Constants.FullAdminRole).Any()) { toRet.IsFullPermission = true; } CacheHelper.Add(Module + "_" + toRet.Id.ToUiString(), toRet, BlCommon.DefaultTimeOut()); } else { //Force cash refresh for module entry CacheHelper.Clear(Module + "_" + userId.ToUiString()); } } return(toRet); }
private void FillPanelWithComponents() { string value; // Try to retrieve data from the cache if (!CacheHelper.TryGetItem(CACHE_KEY, out value)) { var controls = FormUserControlInfoProvider.GetFormUserControls("UserControlDisplayName,UserControlCodeName,UserControlDescription,UserControlThumbnailGUID", "UserControlShowInBizForms = 1 AND UserControlPriority = 100", "UserControlDisplayName"); StringBuilder content = new StringBuilder(); foreach (var control in controls) { string iconUrl; if (control.UserControlThumbnailGUID == Guid.Empty) { iconUrl = GetImageUrl("CMSModules/CMS_FormEngine/custom.png"); } else { iconUrl = ResolveUrl(MetaFileURLProvider.GetMetaFileUrl(control.UserControlThumbnailGUID, "icon")); } content.AppendFormat("<div title=\"{0}\"><div class=\"form-component component_{1}\" ondblclick=\"FormBuilder.addNewField('{1}','',-1);FormBuilder.scrollPosition=9999;FormBuilder.showSavingInfo();\"><span class=\"component-label\">{2}</span><img src=\"{3}\" alt=\"{1}\" /></div></div>", ResHelper.LocalizeString(control.UserControlDescription), control.UserControlCodeName, control.UserControlDisplayName, iconUrl); } value = content.ToString(); var dependency = CacheHelper.GetCacheDependency(FormUserControlInfo.OBJECT_TYPE + "|all"); CacheHelper.Add(CACHE_KEY, value, dependency, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5)); } pnlFormComponents.Controls.Add(new LiteralControl(value)); }
public virtual List <T> GetData <T, U>(Expression <Func <T, bool> > expression) where T : class, new() where U : IQuerySurface { string newCacheKey = CacheKey; if (expression != null) { newCacheKey = string.Format("{0}:{1}", CacheKey, expression.ToString()); } List <T> data = CacheHelper != null && CacheExpiry > 0 ? CacheHelper.Get(newCacheKey) as List <T> : null; if (data == null) { SubSonicRepository <T> repository = GetRepository <T, U>(); if (expression != null) { data = repository.Find(expression).ToList(); } else { data = repository.GetAll().ToList(); } if (CacheHelper != null) { CacheHelper.Add(newCacheKey, data, DateTime.Now.AddSeconds(CacheExpiry)); } } return(data); }
/// <summary> /// 设置登录用户cache /// </summary> /// <param name="info">登录用户信息</param> static void SetYongHuCache(EyouSoft.Model.SSO.MYongHuInfo info) { string cacheKey = string.Format(EyouSoft.Model.CacheKey.LoginYongHu, info.YongHuId); CacheHelper.Remove(cacheKey); CacheHelper.Add(cacheKey, info, DateTime.Now.AddHours(12)); }
public DataTable RunQueryDataTable(string query, IDataParameter[] parameters) { string key = CacheHelper.Key(query, parameters); if (!CacheHelper.Exists(key)) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add(); using (MySqlDataAdapter da = new MySqlDataAdapter(query, Connection)) { da.SelectCommand.CommandType = CommandType.Text; if (parameters != null) { foreach (MySqlParameter parameter in parameters) { if (parameter != null) { da.SelectCommand.Parameters.Add(parameter); } } } da.Fill(dt); CacheHelper.Add <DataTable>(dt, key); } return(dt); } else { return(CacheHelper.Get <DataTable>(key)); } }
public void Add_Successfully() { cacheHelper.Add("testObject", "testKey"); var count = cacheHelper.GetAllCount(); Assert.AreEqual(_count + 1, count); }
public HttpResponseMessage Sign([FromBody] LoginParameter loginPara) { string res = mUserMgr.Login(loginPara.MobileOrEmail, loginPara.Password); MsgInfo loginMsg = JsonConvert.DeserializeObject <MsgInfo>(res); if (!loginMsg.IsError) { LoginUsers loginUser = JsonConvert.DeserializeObject <LoginUsers>(loginMsg.Msg); string strUserData = JsonConvert.SerializeObject(loginUser); //保存身份信息 FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, loginUser.Mobile, DateTime.Now, DateTime.Now.AddHours(12), false, strUserData); CacheHelper.Add("LoginKey_" + Guid.NewGuid(), FormsAuthentication.Encrypt(Ticket)); //CookieHelper.Add(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(Ticket), RootDomain);//加密身份信息,保存至Cookie loginMsg.Msg = loginPara.ReturnUrl; if (loginPara.IsRemember) { CookieHelper.Add("remember", loginUser.Mobile + "$" + Security.DESEncrypt(loginPara.Password), RootDomain); } else { CookieHelper.Remove("remember"); } } return(loginMsg.toJson()); }
public CompaniesEntity[] GetCompanies(int?id = 0, String name = "") { ValidSecurityToken(authHeader); CompaniesController controller = new CompaniesController(); CompaniesEntity[] companies; if (CacheHelper.Exists("GetCompanies") == false) { CacheHelper.Add("GetCompanies", controller.GetCompanies(), DateTime.Now.AddDays(1)); } CacheHelper.Get("GetCompanies", out companies); if (!string.IsNullOrEmpty(name) && id <= 0) { return(companies.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToArray()); } else if (string.IsNullOrEmpty(name) && id > 0) { return(companies.Where(x => x.Id == id).ToArray()); } else if (!string.IsNullOrEmpty(name) && id > 0) { return(companies.Where(x => x.Id == id && x.Name.ToLower().Contains(name.ToLower())).ToArray()); } return(companies); }
public SizeEntity[] GetPetSize(int?id = 0, String name = "") { ValidSecurityToken(authHeader); PetsController controller = new PetsController(); SizeEntity[] size; if (id < 0) { CacheHelper.Add("GetPetsSize", controller.GetPetsSize(), DateTime.Now.AddDays(1)); } if (CacheHelper.Exists("GetPetsSize") == false) { CacheHelper.Add("GetPetsSize", controller.GetPetsSize(), DateTime.Now.AddDays(1)); } CacheHelper.Get("GetPetsSize", out size); if (!string.IsNullOrEmpty(name) && id <= 0) { return(size.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToArray()); } else if (string.IsNullOrEmpty(name) && id > 0) { return(size.Where(x => x.Id == id).ToArray()); } else if (!string.IsNullOrEmpty(name) && id > 0) { return(size.Where(x => x.Id == id && x.Name.ToLower().Contains(name.ToLower())).ToArray()); } return(size); }
public BreedEntity[] GetPetBreed(int?subSpeciesId = 0, String name = "") { ValidSecurityToken(authHeader); SpeciesController controller = new SpeciesController(); BreedEntity[] breed; if (subSpeciesId < 0) { CacheHelper.Add("GetBreed", controller.GetBreed(), DateTime.Now.AddDays(1)); } if (CacheHelper.Exists("GetBreed") == false) { CacheHelper.Add("GetBreed", controller.GetBreed(), DateTime.Now.AddDays(1)); } CacheHelper.Get("GetBreed", out breed); if (!string.IsNullOrEmpty(name) && subSpeciesId <= 0) { return(breed.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToArray()); } else if (string.IsNullOrEmpty(name) && subSpeciesId > 0) { return(breed.Where(x => x.Id == subSpeciesId).ToArray()); } else if (!string.IsNullOrEmpty(name) && subSpeciesId > 0) { return(breed.Where(x => x.Id == subSpeciesId && x.Name.ToLower().Contains(name.ToLower())).ToArray()); } return(breed); }
public SpeciesEntity[] GetPetSpecies(String name = "") { ValidSecurityToken(authHeader); SpeciesController controller = new SpeciesController(); SpeciesEntity[] species; if (name == "clean") { CacheHelper.Add("GetSpecies", controller.GetSpecies(), DateTime.Now.AddDays(1)); } if (CacheHelper.Exists("GetSpecies") == false) { CacheHelper.Add("GetSpecies", controller.GetSpecies(), DateTime.Now.AddDays(1)); } CacheHelper.Get("GetSpecies", out species); if (string.IsNullOrEmpty(name)) { return(species); } else { return(species.Where(x => x.Name.ToLower().Contains(name.ToLower())).ToArray()); } }
protected DataTable RunProcedureDataTable(string storedProcName, IDataParameter[] parameters) { string key = CacheHelper.Key(storedProcName, parameters); if (!CacheHelper.Exists(key)) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add(); MySqlDataAdapter da = new MySqlDataAdapter(storedProcName, Connection); da.SelectCommand.CommandType = CommandType.StoredProcedure; foreach (MySqlParameter parameter in parameters) { if (parameter != null) { da.SelectCommand.Parameters.Add(parameter); } } da.Fill(dt); CacheHelper.Add <DataTable>(dt, key); return(dt); } else { return(CacheHelper.Get <DataTable>(key)); } }
public static object GetAllActiveCultures(EvaluationContext context, params object[] parameters) { //Get the cultures from the cache if they exist string strCultures = CacheHelper.GetItem("GetAllActiveCulturesQueryStringCache") as string; if (String.IsNullOrWhiteSpace(strCultures)) { //Build Query var cultureQuery = new DataQuery("cms.culture.selectsitecultures"); cultureQuery.AddColumns("CultureCode"); QueryDataParameters queryParameters = new QueryDataParameters(); queryParameters.Add("@SiteID", SiteContext.CurrentSiteID); cultureQuery.Parameters = queryParameters; DataSet cultures = cultureQuery.Result; //Store all cultures in a string with each culture separated by | if (!DataHelper.DataSourceIsEmpty(cultures)) { foreach (DataRow culture in cultures.Tables[0].Rows) { strCultures += culture["CultureCode"] + "|"; } } //Remove trailing | strCultures = strCultures.Remove(strCultures.Length - 1); //Store resulting string in the cache CacheHelper.Add("GetAllActiveCulturesQueryStringCache", strCultures, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration); } return(strCultures); }
public string Captcha(string value) { CookieContainer _cookies = new CookieContainer(); var htmlResult = string.Empty; using (var wc = new CookieAwareWebClient(_cookies)) { wc.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc.Headers[HttpRequestHeader.KeepAlive] = "300"; htmlResult = wc.DownloadString(urlBaseReceitaFederal + paginaPrincipal); } if (htmlResult.Length > 0) { var wc2 = new CookieAwareWebClient(_cookies); wc2.Headers[HttpRequestHeader.UserAgent] = "Mozilla/4.0 (compatible; Synapse)"; wc2.Headers[HttpRequestHeader.KeepAlive] = "300"; byte[] data = wc2.DownloadData(urlBaseReceitaFederal + paginaCaptcha); CacheHelper.Add("CookieReceitaFederal_" + value, _cookies); return("data:image/jpeg;base64," + System.Convert.ToBase64String(data, 0, data.Length)); } return(string.Empty); }
/// <summary> /// 查询所有的仓库数据信息 /// </summary> /// <returns></returns> public List <StorageEntity> GetList() { string Key = string.Format(CacheKey.JOOSHOW_STORAGE_CACHE, this.CompanyID); List <StorageEntity> listResult = CacheHelper.Get <List <StorageEntity> >(Key); if (!listResult.IsNullOrEmpty()) { return(listResult); } StorageEntity entity = new StorageEntity(); entity.IncludeAll(); entity.OrderBy(a => a.ID, EOrderBy.DESC); entity.Where(a => a.IsDelete == (int)EIsDelete.NotDelete) .And(a => a.CompanyID == this.CompanyID); SysDepartEntity depart = new SysDepartEntity(); depart.Include(item => new { DepartName = item.DepartName }); entity.Left <SysDepartEntity>(depart, new Params <string, string>() { Item1 = "DepartNum", Item2 = "SnNum" }); listResult = this.Storage.GetList(entity); if (!listResult.IsNullOrEmpty()) { CacheHelper.Add(Key, listResult); } return(listResult); }
/// <summary> /// Gets the moyers superior. /// </summary> /// <returns></returns> private static IEnumerable <Tuple <decimal, decimal, decimal> > GetBoltonPreviousRelationTable() { List <Tuple <decimal, decimal, decimal> > result; if (CacheHelper.Get(CacheKey.BoltonPreviousTableKey, out result)) { return(result); } result = new List <Tuple <decimal, decimal, decimal> >(); using (var reader = new StreamReader(new MemoryStream(ResourceFiles.BoltonPreviousRelationReferences))) { string line; while ((line = reader.ReadLine()) != null && !string.IsNullOrEmpty(line)) { var items = line.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); var item1 = decimal.Parse(items[0].Trim(), CultureInfo.InvariantCulture); var item2 = decimal.Parse(items[1].Trim(), CultureInfo.InvariantCulture); var item3 = decimal.Parse(items[2].Trim(), CultureInfo.InvariantCulture); result.Add(new Tuple <decimal, decimal, decimal>(item1, item2, item3)); } } CacheHelper.Add(result, CacheKey.BoltonPreviousTableKey); return(result); }
public Maybe <ApiKey> Get(string key) { var fromCache = CacheHelper <ApiKey> .Get(key); if (fromCache.HasValue) { return(fromCache); } using (var client = GetClient()) { var apiKey = client.FirstOrDefault <ApiKey>(@"SELECT * FROM Api_Key WHERE Deleted = 0 AND [Key] = @0", key); if (apiKey != null) { apiKey.Methods = client.Fetch <ApiKeyMethod>(@"SELECT * FROM Api_KeyMethod WHERE Deleted = 0 AND KeyID = @0", apiKey.Id); apiKey.Fields = new HashSet <ApiKeyField>(client.Fetch <ApiKeyField>(@"SELECT * FROM Api_KeyField WHERE Deleted = 0 AND KeyID = @0", apiKey.Id)); CacheHelper <ApiKey> .Add(apiKey.Key, apiKey); } return(apiKey.ToMaybe()); } }
public static DisplayGroup GetDisplayGroup(string groupID, string userid, string role = null) { string key = CacheHelper.DisplayGroupPrefix + userid + "@" + groupID; if (CacheHelper.Contains(key)) { return(CacheHelper.Get <DisplayGroup>(key)); } DisplayGroup result = null; using (var _gorillaCtx = new MSGorillaEntities()) { Group group = new GroupManager().GetGroupByID(groupID, _gorillaCtx); if (!string.IsNullOrEmpty(role)) { result = new DisplayGroup(group, role); } else { result = new DisplayGroup(group, userid, _gorillaCtx); } } CacheHelper.Add(key, result); return(result); }
public List <CategoryInfo> GetAllCategoryForSearch(string prefix, bool isActive, AspxCommonInfo aspxCommonObj) { try { int itemID = 0; List <CategoryInfo> catList = new List <CategoryInfo>(); if (!CacheHelper.Get("CategoryForSearch" + aspxCommonObj.StoreID.ToString() + aspxCommonObj.PortalID.ToString() + "_" + aspxCommonObj.CultureName, out catList)) { List <KeyValuePair <string, object> > parameterCollection = CommonParmBuilder.GetParamSPUC(aspxCommonObj); parameterCollection.Add(new KeyValuePair <string, object>("Prefix", prefix)); parameterCollection.Add(new KeyValuePair <string, object>("IsActive", isActive)); parameterCollection.Add(new KeyValuePair <string, object>("ItemID", itemID)); OracleHandler sqlH = new OracleHandler(); catList = sqlH.ExecuteAsList <CategoryInfo>("usp_Aspx_GetCategoryList", parameterCollection); CacheHelper.Add(catList, "CategoryForSearch" + aspxCommonObj.StoreID.ToString() + aspxCommonObj.PortalID.ToString() + "_" + aspxCommonObj.CultureName); } return(catList); } catch (Exception e) { throw e; } }
private void GetSmileys() { const string emoticonPath = @"/nforum/emoticons/"; var sb = new StringBuilder(); FileInfo[] rgFiles; if (!CacheHelper.Get(CacheHelper.CacheNameSmileys(), out rgFiles)) { var di = new DirectoryInfo(Server.MapPath(emoticonPath)); rgFiles = di.GetFiles("*.png"); CacheHelper.Add(rgFiles, CacheHelper.CacheNameSmileys()); } foreach (var fi in rgFiles) { var freindlyName = fi.Name.Replace(".png", "").Replace("-", " "); var jsFileName = (emoticonPath + fi.Name).Replace("\\", "\\\\"); sb.Append("<span>"); sb.AppendFormat("<a href=\"javascript:;\" onmousedown=\"tinyMCE.execCommand('mceInsertContent',false,'<img src="{0}" alt="{1}">');\"><img src=\'{0}\' alt=\'{1}\'></a>", jsFileName, freindlyName); sb.Append("</span>"); } litEmoticons.Text = sb.ToString(); }
private IEnumerable <dynamic> GetMenuColumns(MenuColumnType ctype) { string key = ServiceConst.MenuColumnListCache; var list = CacheHelper.Get <IEnumerable <dynamic> >(key); if (list == null || list.Count() < 1) { var columnSql = this.GetSqlLam <MenuColumn>(); columnSql.Where(m => m.ENABLED == true); columnSql.SelectAll(); var tableSql = columnSql.Join <MenuTable>((c, t) => c.TABLEID == t.ID, aliasName: "b"); tableSql.Select(m => new { m.ALIASNAME }); list = this.GetDynamicList(columnSql.GetSql(), columnSql.GetParameters()); CacheHelper.Add(key, list); } if (list != null) { int type = (int)ctype; list = list.Where(m => m.TYPE == type); } return(list); }
private Category GetCategoryModel(string name, string group = null) { string me = whoami(); if (string.IsNullOrEmpty(group)) { group = MembershipHelper.DefaultGroup(me); } else { MembershipHelper.CheckMembership(group, me); } if (CacheHelper.Contains(CreateCacheCategoryKey(name, group))) { return(CacheHelper.Get <Category>(CreateCacheCategoryKey(name, group))); } Category result = _categoryManager.GetCategory(name, group); if (result == null) { throw new CategoryNotFoundException(); } CacheHelper.Add(CreateCacheCategoryKey(name, group), result); return(result); }
/// <summary> /// /// </summary> /// <returns></returns> public Tuple <bool, string> GetQiNiuHost() { try { var cacheToken = CacheHelper.Get <string> ("qiniuhostkey"); var host = cacheToken.IsNullOrEmpty() ? _redisCommonService.Get <string> ("qiniuhostkey") : cacheToken; if (!host.IsNullOrEmpty()) { return(new Tuple <bool, string> (true, host)); } var result = Helper.HttpRequestHelper.GateWaySync <Result <String> > ("ps.qiniu.host.get", new Dictionary <string, dynamic> ()); if (result.IsSuccess) { CacheHelper.Add("qiniuhostkey", result.Data.Trim('"'), 1440); _redisCommonService.Set("qiniuhostkey", result.Data.Trim('"'), TimeSpan.FromDays(1)); return(new Tuple <bool, string> (true, result.Data.Trim('"'))); } return(new Tuple <bool, string> (false, "")); } catch (Exception e) { return(new Tuple <bool, string> (false, e.Message)); } }
public async Task Handle(RegisterVerificationMessage notification, CancellationToken cancellationToken) { Debug.WriteLine("messagehandled"); var token = Guid.NewGuid().ToString(); string theEmailLink = "http://localhost:61985/authentication/" + notification.User.Id.ToString() + "/" + token; _cacheHepler.Add(new CacheDTO { UserId = notification.User.Id, Token = token }); try { await _sender.SendEmailAsync(new EmailDTO { Subject = "EventExpress registration", RecepientEmail = notification.User.Email, MessageText = $"For confirm your email please follow the <a href='{theEmailLink}'>link</>" }); var x = _cacheHepler.GetValue(notification.User.Id); Debug.WriteLine(x.Token); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
protected void hypENG_ServerClick(object sender, EventArgs e) { WebUtils.SetCookie(this, "languageName", Constant.DB.langEng); WebUtils.SetCookie(this, "languageID", Constant.DB.LangId_En.ToString()); CacheHelper.Add("languageName", Constant.DB.langEng); CacheHelper.Add("languageID", Constant.DB.LangId_En.ToString()); Response.Redirect(WebUtils.RedirectHomePage()); }
/// <summary> /// This method used to retrieve the address list from CSV file. /// </summary> /// <returns>Address List</returns> internal List<Address> GetAllAddresses() { List<Address> addressList = new List<Address>(); string cacheKeyName = "CSVAddressList"; string cacheDurantion = Constants.CacheTimeDuration; // Get from Cache try { if (CacheHelper.Exists(cacheKeyName)) { CacheHelper.Get(cacheKeyName, out addressList); if (addressList == null) { CacheHelper.Clear(cacheKeyName); } } if (!CacheHelper.Exists(cacheKeyName)) { string csvPath = string.Empty; if (HttpContext.Current != null) { csvPath = HttpContext.Current.Server.MapPath(Constants.FileLocation); } else { csvPath = "D:\\Projects\\IsobarAssignment\\ClosestAddress\\ClosestAddress\\CSV\\Address_List_Australia.txt"; } if (!string.IsNullOrWhiteSpace((csvPath))) { using (StreamReader reader = new StreamReader(csvPath)) { while (!reader.EndOfStream) { string line = reader.ReadLine(); if (!string.IsNullOrWhiteSpace(line.Trim().Substring(line.LastIndexOf(' ')))) { addressList.Add(new Address { Name = line.Trim().Substring(0, line.LastIndexOf(' ')).Trim(), KM = Convert.ToInt32(line.Trim().Substring(line.LastIndexOf(' ')).Trim()) }); } } } } if (addressList != null && addressList.Count > 0) { CacheHelper.Add(addressList, cacheKeyName, Convert.ToDouble(cacheDurantion)); } } } catch (Exception ex) { LogWrite.LogError(ex); } return addressList; }