private void FetchDBandCache()
        {
            PeopleLocations listOfPeopleLocation = new PeopleLocations();

            try
            {
                using (StreamReader r = new StreamReader(HostingEnvironment.MapPath("~/data/data_large.json")))
                {
                    // get a list of people and places
                    string json = r.ReadToEnd();
                    listOfPeopleLocation = JsonConvert.DeserializeObject <PeopleLocations>(json);
                }

                if (listOfPeopleLocation != null)
                {
                    // check for people and cache for an hour
                    if (listOfPeopleLocation.people != null)
                    {
                        _cacheHelper.Add(cachePeople, listOfPeopleLocation.people, CacheTime);
                    }

                    // check for people and cache for an hour
                    if (listOfPeopleLocation.places != null)
                    {
                        _cacheHelper.Add(cachePlaces, listOfPeopleLocation.places, CacheTime);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error("Unable to fetch ancestry database due to: " + ex.Message, ex);
            }
        }
        public static SSOUserInfo SetUser(SSOUserInfo user)
        {
            //使用时应该存入token到user
            user.Token = AddToken();
            cacheHelper.Add(CacheKeyGroup.Token, user.Token, user, TimeSpan.FromDays(TokenLifeTime));

            return(user);
        }
        public async Task Handle(RegisterVerificationMessage notification, CancellationToken cancellationToken)
        {
            Debug.WriteLine("messagehandled");
            var token = Guid.NewGuid().ToString();
            var host  = _urlOptions.Value.Host;
            var port  = _urlOptions.Value.Port;

            string theEmailLink = $"{host}:{port}/authentication/{notification.User.Id}/{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);
            }
        }
        public async Task Handle(RegisterVerificationMessage notification, CancellationToken cancellationToken)
        {
            var token        = Guid.NewGuid().ToString();
            var theEmailLink = $"https://localhost:44321/confirm_email/{notification.User.Id.ToString()}/{token}";

            _cacheHelper.Add(new CacheDto
            {
                UserId = notification.User.Id,
                Token  = token
            });

            try
            {
                await _sender.SendEmailAsync(new EmailDto
                {
                    Subject        = "BattleTanks registration",
                    RecepientEmail = notification.User.Email,
                    MessageText    = $"For confirm your email please follow the <a href='{theEmailLink}'>link</>"
                });

                var x = _cacheHelper.GetValue(notification.User.Id);

                Debug.WriteLine(x.Token);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
        protected string GetToken(int userId)
        {
            if (userId <= 0)
            {
                return(string.Empty);
            }
            string token = SecurityHelper.EncryptString($"{userId}|{DateTime.Now.ToUnixTimestamp()}");

            _cache.Add(token, userId, TimeSpan.FromMinutes(30));
            return(token);
        }
 public void Add(string groupName, string key, object value)
 {
     try
     {
         cacheHelper.Add(groupName, key, value);
     }
     catch (Exception ex)
     {
         Logger.Error(cacheMode + "Cache Error", ex);
     }
 }
        // GET api/values
        public IEnumerable <string> Get()
        {
            //Db dd = new Db();
            //var ss1 = new Dal.User();
            //ss1.UserName = "******";
            //dd.Users.Add(ss1);
            //dd.SaveChanges();
            string ss = "";

            try
            {
                Util.AddLog(new LogInfo()
                {
                    Describle = "ddd"
                });
            }
            catch (Exception e)
            {
                ss = e.ToString();
                throw;
            }

            ICacheHelper CacheClient = Util.GetCacheClient();

            CacheClient.Add(CacheKeyGroup.AuthenCode, "key", "asdf", TimeSpan.FromMinutes(100));

            var result = CacheClient.Get <string>(CacheKeyGroup.AuthenCode, "key");

            //dd.Patients.Where(a => a.Id == 1).Select(a => new { aa = a.PatientsDatas. });
            //var ss = dd.table2.Select(a => new { a = a.dd, b = a.yy }).First();


            //var host = "172.17.0.12";//实例访问host地址
            //int port = 6379;// 端口信息
            //string instanceId = "crs-77i2ghem";//实例id
            //string pass = "******";//密码

            //RedisClient redisClient = new RedisClient(host, port, instanceId + ":" + pass);
            //string key = "name";
            //string value = "QcloudV5!";
            //redisClient.Set(key, value); //设置值
            //System.Console.WriteLine("set key:[" + key + "]value:[" + value + "]");
            //string getValue = System.Text.Encoding.Default.GetString(redisClient.Get(key)); //读取值
            //System.Console.WriteLine("value:" + getValue);
            //System.Console.Read();

            return(new string[] { "value1", result });
        }
Exemple #8
0
        private List <int> ProcessQuery(SearchEngineConfiguration searchEngine, SearchParams searchParams, out bool isFromCache)
        {
            var indexStats = _cacheHelper.Get <List <int> >(searchEngine.Name);

            isFromCache = true;
            if (null == indexStats || !searchParams.AllowReadingFromCache)
            {
                isFromCache = false;

                HttpWebRequest  httpWebRequest  = (HttpWebRequest)WebRequest.Create(string.Format(searchEngine.Url, searchParams.SearchKeyword, searchParams.NumberOfResultsToConsider));
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                StreamReader    streamReader    = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.ASCII);
                string          rawResponse     = streamReader.ReadToEnd();
                var             resultList      = Regex.Split(rawResponse, searchEngine.UniqueResultSplitter).Skip(1).Select((a, i) => new { Index = i + 1, Url = a.Split(new Char[] { ' ', '<' })[0] }).ToList();
                indexStats = resultList.Where(a => a.Url.ToLower().Contains(searchParams.KeywordForOccurenceCount.ToLower())).Select(a => a.Index).ToList();

                _cacheHelper.Add(searchEngine.Name, indexStats);
            }
            return(indexStats);
        }
Exemple #9
0
        public async Task <Account> LoginAccount(string mobile)
        {
            const int cacheTime            = 360;
            string    accountCacheKey      = string.Format("account_cache_key_{0}", mobile);
            string    accountCacheTokenKey = string.Format("{0}_{1}__", accountCacheKey, "token");
            var       accountCacheToken    = _cacheHelper.Get(accountCacheTokenKey);
            var       account = _cacheHelper.Get(accountCacheKey) as Account;

            if (accountCacheToken != null)
            {
                return(account);
            }
            lock (accountCacheTokenKey)
            {
                accountCacheToken = _cacheHelper.Get(accountCacheTokenKey);
                if (accountCacheToken != null)
                {
                    return(account);
                }
                _cacheHelper.Add(accountCacheTokenKey, "1", cacheTime);

                ThreadPool.QueueUserWorkItem(async(arg) =>
                {
                    using (
                        HttpClient client =
                            new HttpClient(new HttpClientHandler
                    {
                        AutomaticDecompression =
                            System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
                    }))
                    {
                        client.BaseAddress = new Uri(_userCenter);
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        var getLoginUrl = string.Format("api/Account/GetWapLogin?mobile={0}&code={1}", mobile, "");
                        HttpResponseMessage responseLogin = await client.GetAsync(getLoginUrl);
                        if (responseLogin.IsSuccessStatusCode)
                        {
                            var resultLogin = await responseLogin.Content.ReadAsStringAsync();
                            account         = resultLogin.FromJson <Account>();
                            _cacheHelper.Add(accountCacheKey, account, cacheTime * 2);
                        }
                        else
                        {
                            string loginErrorMsg = string.Format("手机号登录失败:" + mobile);
                            logError.Info(loginErrorMsg);
                        }
                    }
                });
            }

            if (account == null)
            {
                using (
                    HttpClient client =
                        new HttpClient(new HttpClientHandler
                {
                    AutomaticDecompression =
                        System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
                }))
                {
                    client.BaseAddress = new Uri(_userCenter);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var getLoginUrl = string.Format("api/Account/GetWapLogin?mobile={0}&code={1}", mobile, "");
                    HttpResponseMessage responseLogin = await client.GetAsync(getLoginUrl);

                    if (responseLogin.IsSuccessStatusCode)
                    {
                        var resultLogin = await responseLogin.Content.ReadAsStringAsync();

                        account = resultLogin.FromJson <Account>();
                    }
                    else
                    {
                        string loginErrorMsg = string.Format("手机号登录失败:" + mobile);
                        logError.Info(loginErrorMsg);
                    }
                }
            }


            return(account);
        }