Exemple #1
0
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public LoginInfoModel GetUserInfo(LoginInfoModel userInfo)
        {
            if (userInfo == null || userInfo.Id < 1)
            {
                return(null);
            }
            var key   = CacheMenuListKey + userInfo.Id;
            var model = RedisCacheHelper.Get <LoginInfoModel>(key);

            if (model != null)
            {
                return(model);
            }
            List <int> authorityList = new List <int>();

            userInfo.MenuList = GetMenuList(userInfo.UserId, ref authorityList);
            if (authorityList != null && authorityList.Any())
            {
                userInfo.BusinessPermissionList = authorityList.Select(p => p).Cast <EnumBusinessPermission>().ToList();
            }
            else
            {
                userInfo.BusinessPermissionList = new List <EnumBusinessPermission>();
            }
            if (userInfo.MenuList == null)
            {
                userInfo.MenuList = new List <SysMenuModel>();
            }

            RedisCacheHelper.AddSet(CacheMenuListKey + userInfo.Id, userInfo, new TimeSpan(0, 0, 10));
            return(userInfo);
        }
        public static object GetProductListNew()
        {
            const int    cacheTime = 2;
            const string cacheKey  = "product_list";
            const string lockKey   = cacheKey;

            var cacheValue = RedisCacheHelper.Get <string>(cacheKey);

            if (cacheValue != null)
            {
                // Console.WriteLine("从Redis中读取");
                return(cacheValue);
            }
            else
            {
                lock (lockKey)
                {
                    cacheValue = RedisCacheHelper.Get <string>(cacheKey);
                    if (cacheValue != null)
                    {
                        return(cacheValue);
                    }
                    else
                    {
                        cacheValue = "1111"; //这里一般是 sql查询数据。
                        Console.WriteLine("从数据库中读取");
                        RedisCacheHelper.Add(cacheKey, cacheValue, DateTime.Now.AddSeconds(cacheTime));
                    }
                }
                return(cacheValue);
            }
        }
Exemple #3
0
        /// <summary>
        /// 获取行业类型描述列表
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static IList <DicsModel> GetDicsInfoByKey(string key)
        {
            try
            {
                // 全部的Dics
                IList <DicsModel> lstDics = RedisCacheHelper.Get <List <DicsModel> >(keyDicsInfo);
                if (lstDics == null || lstDics.Where(p => String.IsNullOrWhiteSpace(p.KeyName)).Count() > 0)
                {
                    lstDics = new DicsBLL().GetAllDicsInfo();

                    RedisCacheHelper.Add(keyDicsInfo, lstDics, 60);
                }

                // 根据DicsType 获取相关的字典属性
                var result = (from n in lstDics
                              where n.DicType == key && n.LanguageVersion == (int)LanguageEnum.TraditionalChinese
                              select n).ToList <DicsModel>();

                return(result);
            }
            catch
            {
                return(null);
            }
        }
Exemple #4
0
        public ActionResult EditConfig()
        {
            var id = RedisCacheHelper.Get <int?>(RedisCacheHelper.EnterpriseMemberTypeId);

            ViewBag.MemberTypeId = id.HasValue ? id.Value.ToString() : string.Empty;
            return(PartialView());
        }
Exemple #5
0
        public void RedisRemove()
        {
            RedisCacheHelper.Remove("kim2");
            string str = RedisCacheHelper.Get <string>("kim2");

            Assert.AreEqual(null, str);
        }
        public static object GetProductListNew()
        {
            const int    cacheTime = 30;
            const string cacheKey  = "product_list";
            //缓存标记。
            const string cacheSign = cacheKey + "_sign";

            var sign = RedisCacheHelper.Get <string>(cacheSign);
            //获取缓存值
            var cacheValue = RedisCacheHelper.Get <string>(cacheKey);

            if (sign != null)
            {
                return(cacheValue); //未过期,直接返回。
            }
            else
            {
                RedisCacheHelper.Add(cacheSign, "1", DateTime.Now.AddSeconds(cacheTime));
                ThreadPool.QueueUserWorkItem((arg) =>
                {
                    cacheValue = "2222";                                                                //这里一般是 sql查询数据。
                    RedisCacheHelper.Add(cacheKey, cacheValue, DateTime.Now.AddSeconds(cacheTime * 2)); //日期设缓存时间的2倍,用于脏读。
                });

                return(cacheValue);
            }
        }
        public async Task <ActionResult> Chat(string id)
        {
            var receiverObject = await UserManager.Users.SingleOrDefaultAsync(a => a.Id == id);

            ViewBag.receiverName = receiverObject.UserName;
            var currentLoggedUser = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            ViewBag.SenderName            = currentLoggedUser.UserName;
            ViewBag.currentLoggedUserName = currentLoggedUser.UserName;

            //Retrieve messages of loggedIn/Current User and receiver messages
            var lstSampleObject          = RedisCacheHelper.Get <List <SampleObject> >("redisChat");
            List <SampleObject> chatList = new List <SampleObject>();

            if (lstSampleObject != null)
            {
                foreach (var items in lstSampleObject)
                {
                    if ((items.senderUName == currentLoggedUser.UserName && items.receiverUName == receiverObject.UserName) ||
                        (items.senderUName == receiverObject.UserName && items.receiverUName == currentLoggedUser.UserName)
                        )
                    {
                        chatList.Add(items);
                    }
                }
            }
            return(View(chatList));
        }
        public ActionResult saveDataInRedis(string senderName, string receiverName, string msginput)
        {
            var lstSampleObject = RedisCacheHelper.Get <List <SampleObject> >("redisChat");

            if (lstSampleObject == null)
            {
                lstSampleObject = new List <SampleObject> {
                    new SampleObject
                    {
                        senderUName   = senderName,
                        receiverUName = receiverName,
                        textMsg       = msginput
                    }
                };
            }
            else
            {
                lstSampleObject.Add(
                    new SampleObject
                {
                    senderUName   = senderName,
                    receiverUName = receiverName,
                    textMsg       = msginput
                });
            }
            RedisCacheHelper.Set("redisChat", lstSampleObject);
            return(Json(new { status = true }));
        }
        public dynamic GetAuthorizationCode(string code, string state, string clientId, string redirectUri = "")
        {
            string redisCode = RedisCacheHelper.Get <string>(tenantId, "GetCode" + clientId) ?? "";

            returnData.Note = state;
            if (string.IsNullOrEmpty(redisCode))
            {
                returnData.Massage = "code过期";
                return(returnData);
            }
            if (!redisCode.Equals(code))
            {
                returnData.Massage = "code有误";
                return(returnData);
            }
            string accesstoken = Guid.NewGuid().ToString("N");

            returnData.Massage = accesstoken;
            RedisCacheHelper.Add(tenantId, "GetAuthorizationCode" + clientId, accesstoken, DateTime.Now.AddMinutes(accesstokenValidTime));

            RedisCacheHelper.Remove(tenantId, "GetCode" + clientId);
            if (!string.IsNullOrEmpty(redirectUri))
            {
                HttpContext.Current.Response.Redirect(redirectUri + "?code=" + code + "&state=" + state, true);
            }
            return(returnData);
        }
        public dynamic ValidatedCaldavUser(string loginName, string token)
        {
            //判断这个人是否在北森数据库
            var user = AccountProxy.GetAssociatedUsersByLoginName(loginName);

            if (user == null)
            {
                return(null);
            }


            var userGuid = RedisCacheHelper.Get <string>(user.TenantId, MakeUserGuidKey(loginName));

            if (userGuid == null)
            {
                return(null);
            }

            if (SecurityHelper.GetMd5($"{user.TenantId}_{user.UserId}_Schedule_{userGuid}") == token)
            {
                //校验通过,去获取数据
                return("获取到北森的数据了!!!");
            }

            return(null);
        }
Exemple #11
0
        public static IList <DicsModel> GetDicsInfoByKeyAllLanguage(string key)
        {
            try
            {
                // 全部的Dics
                IList <DicsModel> lstDics = RedisCacheHelper.Get <List <DicsModel> >(keyDicsInfo);
                if (lstDics == null)
                {
                    lstDics = new DicsBLL().GetAllDicsInfo();

                    RedisCacheHelper.Add(keyDicsInfo, lstDics, 60);
                }

                // 根据DicsType 获取相关的字典属性
                var result = (from n in lstDics
                              where n.DicType == key
                              select n).ToList <DicsModel>();

                return(result);
            }
            catch
            {
                return(null);
            }
        }
Exemple #12
0
        private void Recive_Client(string msg, string stname)
        {
            string[] cmd = msg.Split(',');
            switch (cmd[0])
            {
            case "ReadName":
                SendMsgToClient(stname, RedisCacheHelper.Get <string>("OPTest_Name"));

                break;

            case "ReadAge":
                SendMsgToClient(stname, RedisCacheHelper.Get <string>("OPTest_Age"));

                break;

            case "WriteName":
                RedisCacheHelper.Add <string>("OPTest_Name", cmd[1]);
                SendMsgToClient(stname, "WriteNameOK");

                break;

            case "WriteAge":
                RedisCacheHelper.Add <string>("OPTest_Age", cmd[1]);
                SendMsgToClient(stname, "WriteAgeOK");

                break;
            }
        }
        public ActionResult <Account> GetAccounts(string name           = "",
                                                  string sort_type      = "",
                                                  int page_index        = -1,
                                                  string field_selected = "")
        {
            List <Object> list;

            if (string.IsNullOrEmpty(sort_type))
            {
                sort_type = "asc";
            }
            if (string.IsNullOrEmpty(field_selected))
            {
                field_selected = "AccountId, NameAccount, EmailAccount, PhoneAccount, StatusId, RoleId";
            }

            if (name == "" && sort_type == "asc" && page_index == -1 && field_selected == "AccountId, NameAccount, EmailAccount, PhoneAccount, StatusId, RoleId")
            {
                var result = RedisCacheHelper.Get("ListAccounts", _redisCache);

                if (result == null)
                {
                    list = _accountService.getAccount(name, sort_type, page_index, ITEM_PER_PAGE, field_selected);


                    if (list == null)
                    {
                        return(NotFound());
                    }
                    else
                    {
                        var data = JsonConvert.SerializeObject(list);
                        List <AccountDto> listDto = JsonConvert.DeserializeObject <List <AccountDto> >(data);

                        RedisCacheHelper.Set("ListAccounts", listDto, _redisCache);

                        return(Ok(list));
                    }
                }
                else
                {
                    return(Ok(result));
                }
            }
            else
            {
                list = _accountService.getAccount(name, sort_type, page_index, ITEM_PER_PAGE, field_selected);
                if (list.Count == 0)
                {
                    return(NotFound());
                }
                else
                {
                    return(Ok(list));
                }
            }
        }
        public List <string> GetList()
        {
            var cacheKey = "list";

            var lista = RedisCache.Get <List <string> >(cacheKey);

            if (lista != null)
            {
                return(lista);
            }
            else
            {
                RedisCache.Set(cacheKey, new List <string> {
                    "pippo", "pluto", "paperino"
                }, 60);
                return(RedisCache.Get <List <string> >(cacheKey));
            }
        }
Exemple #15
0
        public void RedisAdd()
        {
            DateTime dtime = new DateTime(2019, 03, 10);

            RedisCacheHelper.Add <string>("kim2", "test", dtime);
            string str = RedisCacheHelper.Get <string>("kim2");

            Assert.AreEqual("test", str);
        }
Exemple #16
0
        /* DI 容器测试
         * static void Main(string[] args)
         * {
         *  IServiceCollection services = new ServiceCollection()
         *      .AddSingleton<IFoo, Foo>()
         *      .AddSingleton<IBar>(new Bar())
         *      .AddSingleton<IBaz>(b => new Baz())
         *      .AddSingleton<IGux, Gux>();
         *
         *  IServiceProvider serviceProvider = services.BuildServiceProvider();
         *
         *
         *  Console.WriteLine("serviceProvider.GetService<IFoo>(): {0}", serviceProvider.GetService<IFoo>());
         *  Console.WriteLine("serviceProvider.GetService<IBar>(): {0}", serviceProvider.GetService<IBar>());
         *  Console.WriteLine("serviceProvider.GetService<IBaz>(): {0}", serviceProvider.GetService<IBaz>());
         *  Console.WriteLine("serviceProvider.GetService<IGux>(): {0}", serviceProvider.GetService<IGux>());
         *
         *  Console.ReadKey();
         * }
         */
        /// <summary>
        /// core的 configuration 配置调用
        /// </summary>
        ///<param name="args"></param>
        static void Main(string[] args)
        {
            RedisCacheHelper.Add <string>("mystring", "123456", new TimeSpan(10000));

            var redis = RedisCacheHelper.Get <string>("mystring");

            Console.WriteLine(redis);

            Console.ReadKey();
        }
Exemple #17
0
        public IActionResult GetListComplexObject()
        {
            List <SampleObject> lstSampleObject = new List <SampleObject>();

            if (RedisCacheHelper.GetDatabase() != null)
            {
                lstSampleObject = RedisCacheHelper.Get <List <SampleObject> >("test2");
            }
            return(View(lstSampleObject));
        }
Exemple #18
0
        public IActionResult GetSimpleComplexObject()
        {
            SampleObject sampleObject = new SampleObject();

            if (RedisCacheHelper.GetDatabase() != null)
            {
                sampleObject = RedisCacheHelper.Get <SampleObject>("test1");
            }
            return(View(sampleObject));
        }
Exemple #19
0
 /// <summary>
 /// 获取用户信息
 /// </summary>
 /// <param name="tokenKey"></param>
 /// <param name="requestUrl"></param>
 /// <returns></returns>
 public static QjCurrentUser ValidateToken(string tokenKey)
 {
     lock (StaticLock.TokenLock)
     {
         var userInfo = RedisCacheHelper.Get <QjCurrentUser>($"{StaticLock.UserRedisKeyPrefix}{tokenKey}");
         if (userInfo != null && userInfo.ID > 0)
         {
             return(userInfo);
         }
         return(null);
     }
 }
Exemple #20
0
        public int GetCurrentMemberId()
        {
            string token = System.Web.HttpContext.Current.Request.Headers["token"];

            if (string.IsNullOrWhiteSpace(token))
            {
                return(0);
            }
            var client = new RedisCacheHelper <Model.Member>();
            var cache  = client.Get(token);

            return(cache == null || cache.id <= 0 ? 0 : cache.id);
        }
Exemple #21
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            try
            {
                var controller  = context.Controller as BaseApiController;
                var httpContext = controller.HttpContext;

                var    Identity       = context.HttpContext.User.Identity;
                var    Ip             = httpContext.Connection.LocalIpAddress;
                string controllerName = context.ActionDescriptor.RouteValues["controller"];
                string actionName     = context.ActionDescriptor.RouteValues["action"];

                string ccid = "";
                if (Identity != null && (Identity is Identity) && ((Identity)Identity).CurrentUser != null)
                {
                    ccid = ((Identity)Identity).CurrentUser.ID.ToString() + ":";
                }

                string url = httpContext.Request.Scheme.ToString();
                url += httpContext.Request.Host.ToString();
                url += httpContext.Request.Path.ToString();
                url += httpContext.Request.QueryString.ToString();
                if (httpContext.Request.Method == "GET")
                {
                    #region 查询Redis

                    string str       = "";
                    string textJson  = JsonConvert.SerializeObject(url);
                    var    aes       = new AESEncrypt();
                    var    aesString = aes.Encrypt(textJson, StaticConfig.AESKey, StaticConfig.AESIV);
                    var    temp      = RedisCacheHelper.Get <dynamic>($"{StaticLock.CacheRedisKeyPrefix}{controllerName}:{actionName}:{ccid}{CacheTitle}{aesString}");

                    //清空以什么名称开始的KEY数据
                    //RedisCacheHelper.RemoveAllNameList($"{StaticLock.CacheRedisKeyPrefix}{CacheTitle}");

                    if (temp != null)
                    {
                        dynamic obj    = JsonConvert.DeserializeObject <dynamic>(temp);
                        var     result = new JsonResult(obj);
                        context.Result = result;
                        return;
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
            }
            base.OnActionExecuting(context);
        }
        public dynamic GetValidationAuthorization(string accessToken, string clientId)
        {
            string redisAccesstoken = RedisCacheHelper.Get <string>(tenantId, "GetAuthorizationCode" + clientId) ?? "";

            if (accessToken.Equals(redisAccesstoken))
            {
                returnData.Massage = true;
                return(returnData);
            }
            else
            {
                returnData.Massage = false;
                return(returnData);
            }
        }
Exemple #23
0
 public IQueryable <T_Category> GetAllCategories()
 {
     if (!RedisCacheHelper.Exist("Categories"))
     {
         RedisCacheHelper.Set("Categories", dal.LoadEntities(c => true));
     }
     else
     {
         var category = RedisCacheHelper.Get <IQueryable <T_Category> >("Categories");
         if (category == null)
         {
             RedisCacheHelper.Set("Categories", dal.LoadEntities(c => true));
         }
     }
     return(RedisCacheHelper.Get <IQueryable <T_Category> >("Categories"));
 }
Exemple #24
0
 /// <summary>
 /// 短链接根据帧验证来判断
 /// </summary>
 /// <param name="frame_token"></param>
 /// <returns></returns>
 public static bool Judge_vendor_code(string frame_token)
 {
     try
     {
         string key   = "supplier_code:" + frame_token;
         string value = RedisCacheHelper.Get <string>(key);
         if (value != null)
         {
             return(true);
         }
     }
     catch (Exception ex)
     {
         ToolAPI.XMLOperation.WriteLogXmlNoTail("Judge_vendor_code异常", ex.Message);
     }
     return(false);
 }
        public JsonResult MemberType(int MemberTypeId, int MemberId, int?LevelId)
        {
            if (LevelId == 0)
            {
                LevelId = null;
            }
            var    enterpriseBindId = RedisCacheHelper.Get <int>(RedisCacheHelper.EnterpriseMemberTypeId);
            Member memberEntity     = _memberContract.View(MemberId);



            // 更新为企业会员需要校验选中的会员等级
            if (MemberTypeId == enterpriseBindId)
            {
                if (!LevelId.HasValue || LevelId.Value <= 0)
                {
                    return(Json(OperationResult.Error("企业会员需要选择会员等级类型")));
                }

                var level = _memberLevelContract.MemberLevels.Where(m => !m.IsDeleted && m.IsEnabled && m.Id == LevelId.Value).FirstOrDefault();
                if (level.UpgradeType != UpgradeType.企业)
                {
                    return(Json(OperationResult.Error("请选择有效的企业会员等级类型")));
                }
                memberEntity.LevelId = LevelId.Value;
            }
            else
            {
                // 更新为非企业会员时,如果是之前是企业会员,那么之前的会员等级需要清空
                if (memberEntity.MemberTypeId == enterpriseBindId)
                {
                    memberEntity.LevelId = null;
                }
            }

            memberEntity.UpdatedTime  = DateTime.Now;
            memberEntity.MemberTypeId = MemberTypeId;

            OperationResult oper = _memberContract.Update(memberEntity);

            return(Json(oper));
        }
Exemple #26
0
        /// <summary>
        /// 获取全部的商家信息
        /// </summary>
        /// <returns></returns>
        public static Dictionary <int, string> GetSuppliers()
        {
            try
            {
                // 全部的Dics
                Dictionary <int, string> dicSuppliers = RedisCacheHelper.Get <Dictionary <int, string> >(keySupplierInfo);
                if (dicSuppliers == null)
                {
                    dicSuppliers = new Supplier.SupplierBLL().GetSupplierNames();

                    RedisCacheHelper.Add(keyDicsInfo, dicSuppliers, 60);
                }

                return(dicSuppliers);
            }
            catch
            {
                return(null);
            }
        }
        public ActionResult MemberType(int Id)
        {
            Member member = _memberContract.View(Id);
            List <SelectListItem> list = _memberTypeContract.SelectList(string.Empty);
            // 去除企业会员
            var enterpriseBindId = RedisCacheHelper.Get <int>(RedisCacheHelper.EnterpriseMemberTypeId);

            ViewBag.EnterpriseMemberTypeId = enterpriseBindId;
            list.RemoveAll(s => s.Value == enterpriseBindId.ToString());
            foreach (SelectListItem item in list)
            {
                if (item.Value == member.MemberTypeId.ToString())
                {
                    item.Selected = true;
                }
            }
            ViewBag.ListItem = list;
            ViewBag.MemberId = Id;
            return(PartialView(member));
        }
Exemple #28
0
 /// <summary>
 /// 刷新 Token
 /// </summary>
 /// <param name="token">Token</param>
 /// <param name="dto">用户信息</param>
 /// <returns></returns>
 public async Task RefreshTokenAsync(string token)
 {
     await Task.Run(() =>
     {
         if (redisCacheHelper.Exist(token))
         {
             bool isExisted        = false;
             TokenModel tokenModel = redisCacheHelper.Get <TokenModel>(token, out isExisted);
             //先重新生成token
             redisCacheHelper.Set(token, tokenModel, new DistributedCacheEntryOptions
             {
                 AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(Convert.ToDouble(jwtConfig.WebExp))
             });
         }
         else
         {
             throw new Exception("未获取到当前 Token 信息");
         }
     }).ConfigureAwait(false);
 }
Exemple #29
0
 /// <summary>
 /// 认证厂商识别码是否正确且返回帧验证
 /// </summary>
 /// <param name="register_send_frame">厂商识别码</param>
 /// <returns>帧验证码</returns>
 public static string Judge_vendor_code(object register_send_frame)
 {
     try
     {
         Register_send_frame rsf = JsonConvert.DeserializeObject <Register_send_frame>(register_send_frame.ToString());
         if (rsf != null && !string.IsNullOrEmpty(rsf.vendor_code))
         {
             string key   = "supplier_code:" + rsf.vendor_code;
             string value = RedisCacheHelper.Get <string>(key);
             if (value != null)
             {
                 return(System.Guid.NewGuid().ToString("N"));
             }
         }
     }
     catch (Exception ex)
     {
         ToolAPI.XMLOperation.WriteLogXmlNoTail("Judge_vendor_code异常", ex.Message);
     }
     return(null);
 }
        /// <summary>
        /// 添加会员界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Create()
        {
            var enterpriseBindId = RedisCacheHelper.Get <int>(RedisCacheHelper.EnterpriseMemberTypeId);

            ViewBag.EnterpriseMemberTypeId = enterpriseBindId;

            var memberTypes = _memberTypeContract.SelectList(string.Empty);

            memberTypes.RemoveAll(m => m.Value == enterpriseBindId.ToString());
            ViewBag.MemberType = memberTypes;

            int       adminId = AuthorityHelper.OperatorId ?? 0;
            MemberDto dto     = new MemberDto();
            var       store   = _storeContract.QueryManageStore(adminId).Where(s => s.IsAttached).FirstOrDefault();

            if (store.IsNotNull())
            {
                dto.StoreId   = store.Id;
                dto.StoreName = store.StoreName;
            }
            return(PartialView(dto));
        }