Example #1
0
        public VideosModel GetVideos(string searchValue)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                return(null);
            }
            var cache = MemoryCacheUtil.GetCacheItem <VideosModel>("PixabayApi_videos_" + searchValue);

            if (cache != null)
            {
                return(cache);
            }

            var url = string.Format("https://pixabay.com/api/videos/?key={0}&q={1}", key, searchValue);

            try
            {
                logger.Debug($"Get:{url}");
                var result     = Get(url);
                var resultJson = JsonConvert.DeserializeObject <VideosModel>(result);
                MemoryCacheUtil.Set("PixabayApi_videos_" + searchValue, resultJson, 3600 * 24);
                return(resultJson);
            }
            catch (Exception ex)
            {
                logger.Error($"获取视频资源:{searchValue} 失败", ex);
                throw ex;
            }
        }
Example #2
0
        public static T GetConfig <T>(string key) where T : class, new()
        {
            T   retValue = new T();
            var models   = MemoryCacheUtil.Get <T>(CacheKeyConfig, nameof(retValue));

            if (models == null)
            {
                var config = new ConfigurationBuilder()
                             .AddInMemoryCollection()
                             .SetBasePath(Directory.GetCurrentDirectory())
                             .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                             .Build();
                retValue = new ServiceCollection()
                           .AddOptions()
                           .Configure <T>(config.GetSection(key))
                           .BuildServiceProvider()
                           .GetService <IOptions <T> >()
                           .Value;
                MemoryCacheUtil.Set(CacheKeyConfig, retValue, TimeSpan.FromDays(30));
            }
            else
            {
                retValue = models;
            }
            return(retValue);
        }
Example #3
0
        /// <summary>
        /// 获取日志
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static ILog GetLogger(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return(null);
            }

            if (MemoryCacheUtil.Contains(name))
            {
                return(MemoryCacheUtil.GetCacheItem <ILog>(name));
            }
            else
            {
                lock (lockObject)
                {
                    if (MemoryCacheUtil.Contains(name))
                    {
                        return(MemoryCacheUtil.GetCacheItem <ILog>(name));
                    }
                    var logger     = CreateLoggerInstance(name);
                    var now        = DateTime.Now.AddDays(1);
                    var expireDate = new DateTime(now.Year, now.Month, now.Day); // 晚上0点过期
                    MemoryCacheUtil.Set(name, logger, expireDate);
                    return(logger);
                }
            }
        }
Example #4
0
        public ImagesModel GetImages(string searchValue, int pageIndex, int pageSize)
        {
            if (string.IsNullOrEmpty(searchValue))
            {
                return(null);
            }
            var cache = MemoryCacheUtil.GetCacheItem <ImagesModel>($"PixabayApi_Images_{searchValue}_{pageIndex}_{pageSize}");

            if (cache != null)
            {
                return(cache);
            }

            var url = string.Format("https://pixabay.com/api/?key={0}&q={1}&image_type=photo&lang=zh&page={2}&per_page={3}", key, searchValue, pageIndex, pageSize);

            try
            {
                logger.Debug($"Get:{url}");
                var result     = Get(url);
                var resultJson = JsonConvert.DeserializeObject <ImagesModel>(result);
                // 缓存24小时
                MemoryCacheUtil.Set($"PixabayApi_Images_{searchValue}_{pageIndex}_{pageSize}", resultJson, 3600 * 24);
                return(resultJson);
            }
            catch (Exception ex)
            {
                logger.Error($"获取图片资源:{searchValue} 失败", ex);
                throw ex;
            }
        }
Example #5
0
        /// <summary>
        /// 缓存过期获取access_token
        /// </summary>
        public void SetAccessToken()
        {
            var getAccessTokenUrl = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={Constants.WxAppId}&secret={Constants.WxSecret}";
            var rep2    = HttpUtil.GetString(getAccessTokenUrl);
            var repObj2 = rep2.GetModel <Code2SessionRep>();

            MemoryCacheUtil.Set(Constants.WxAccessToken, repObj2?.Access_Token ?? "", 120);
        }
Example #6
0
 private string GetTestData87(string val)
 {
     return(MemoryCacheUtil.TryGetValue <string>(CacheKey.KeyPre + val, () =>
     {
         Log("计算值");
         return "返回:" + val;
     }, 10));
 }
Example #7
0
        /// <summary>
        /// 通过存储过程获取CGL不良信息及不良条数
        /// </summary>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <returns></returns>
        public List <AIORAA> GetCGLNgInfoByProc(DateTime startDate, DateTime endDate)
        {
            aIORAAs = new List <AIORAA>();
            int MaxNgCount = 0;

            sampleRaas = new List <AIORAA>();
            OracleParameter[] oracleParameters = new OracleParameter[]
            {
                new OracleParameter("startDate", OracleDbType.Varchar2),
                new OracleParameter("endDate", OracleDbType.Varchar2),
                new OracleParameter("rs", OracleDbType.RefCursor, ParameterDirection.Output),
                new OracleParameter("NGCOUNT", OracleDbType.Int32, ParameterDirection.Output)
            };
            oracleParameters[0].Value = startDate.GetDateTimeFormats()[99];
            oracleParameters[1].Value = endDate.GetDateTimeFormats()[99];
            DataSet dataSet = MemoryCacheUtil.GetOrAddCacheItem(startDate.ToShortDateString() + endDate.ToShortDateString(),
                                                                () =>
            {
                ReadingDb(100, 2);   //进入数据库访问时初始化一个进度到窗口
                return(OraHelper.GetDataSet("pkg_aio.proc_GetCGL_NG_INFO", oracleParameters, CommandType.StoredProcedure));
            }, "cglNgInfo");

            aIORAAs    = Util.ToList <AIORAA>(dataSet.Tables[0]);
            MaxNgCount = MemoryCacheUtil.GetOrAddCacheItem(startDate.ToShortDateString() + endDate.ToShortDateString() + "MaxNgCount",
                                                           () => Convert.ToInt32(oracleParameters[3].Value.ToString()), "MaxNgCount");

            string snIn = "";
            //for (int i = 0; i < aIORAAs.Count; i++)
            //{
            //    snIn+= aIORAAs[i].SN.Substring(36, 17)+"'";
            //    aIORAAs[i] = GetMachineInfo(aIORAAs[i]);
            //    processCount++;
            //}
            int pageSize  = 1000;
            int totalPage = MaxNgCount % pageSize == 0 ? MaxNgCount / pageSize : MaxNgCount / pageSize + 1;

            if (MemoryCacheUtil.GetCacheItem <object>(startDate.ToShortDateString() + endDate.ToShortDateString() + "completeCglNg") == null)
            {
                for (int i = 0; i < totalPage; i++)
                {
                    List <string> ss = (aIORAAs.Skip(i * pageSize).Take(pageSize)).Select(p => "'" + p.SN.Substring(36, 17) + "'").ToList();
                    snIn = string.Join(",", ss);
                    GetMachineInfo(snIn, aIORAAs);
                    ReadingDb(totalPage, i + 1);
                }
            }
            else
            {
                ReadingDb(100, 100);//如果缓存中有数据直接将进度条置为 100%
            }
            sampleRaas = MemoryCacheUtil.GetOrAddCacheItem(startDate.ToShortDateString() + endDate.ToShortDateString() + "completeCglNg",
                                                           () => { return(sampleRaas); }, "completeCglNg");
            return(sampleRaas);
        }
Example #8
0
 private static Form CacheForm <T>() where T : Form, new()
 {
     return(MemoryCacheUtil.GetOrAddCacheItem <Form>(typeof(T).Name, () =>
     {
         var form = new T();
         form.Owner = Utils.Shell;
         //form.Dock = DockStyle.Fill;
         form.TopLevel = false;
         return form;
     }, null, DateTime.MaxValue));
 }
Example #9
0
        /// <summary>
        /// 条件过滤设备
        /// </summary>
        /// <param name="machineNo"></param>
        /// <returns></returns>
        public DataTable GetMachineNo(string machineNo)
        {
            string sql = "SELECT AIO001,AIO002 FROM dbo.BASAIO";

            if (machineNo.Length > 0)
            {
                sql += " where AIO001 like '%" + machineNo + "%'";
            }
            DataTable dt = MemoryCacheUtil.GetOrAddCacheItem("machineNos",
                                                             () => SqlHelper.GetDataTable(sql), "machineType.dt");

            return(dt);
        }
 /// <summary>
 /// 清除用户权限信息缓存
 /// </summary>
 public static void Clear(IPersistBroker broker)
 {
     UserPrivliege.Clear();
     ServiceContainer.ResolveAll <IRole>().Each(item =>
     {
         (item as BasicRole).Broker = broker;
         item.ClearCache();
         MemoryCacheUtil.RemoveCacheItem(item.GetRoleKey);
         MemoryCacheUtil.Set(item.GetRoleKey, new RolePrivilegeModel()
         {
             Role = item.GetSysRole(), Privileges = item.GetRolePrivilege()
         }, 3600 * 12);
     });
 }
Example #11
0
        public static T Get <T>(string key, Func <T> fetch)
        {
            T result = MemoryCacheUtil.Get <T>(key);

            if (result == null)
            {
                result = fetch();
                if (result != null)
                {
                    MemoryCacheUtil.Set(key, result);
                }
            }
            return(result);
        }
Example #12
0
        /// <summary>
        /// 获取设备倾向性数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="startDate"></param>
        /// <param name="endDate"></param>
        /// <param name="machineNo"></param>
        /// <returns></returns>
        public List <T> GetCGLQXX <T>(DateTime startDate, DateTime endDate, string machineNo, out List <AIOLAV> aIOLAVs)
        {
            SqlParameter[] sqlParameters = new SqlParameter[]
            {
                new SqlParameter("@startDate", startDate),
                new SqlParameter("@endDate", endDate),
                new SqlParameter("@machineNo", machineNo)
            };
            DataSet dataSet = MemoryCacheUtil.GetOrAddCacheItem((startDate.ToShortDateString() + endDate.ToShortDateString() + machineNo),
                                                                () => SqlHelper.GetDataSetByProcedure("AIO_GetMachineTrend", sqlParameters), "QxxAndLimitAve");

            aIOLAVs = Util.ToList <AIOLAV>(dataSet.Tables[1]);
            return(Util.ToList <T>(dataSet.Tables[0]));
        }
Example #13
0
        public static IApplicationBuilder UseSysRole(this IApplicationBuilder app)
        {
            var roles  = ServiceContainer.ResolveAll <IRole>();
            var broker = PersistBrokerFactory.GetPersistBroker();

            new SysRolePrivilegeService(broker).CreateRoleMissingPrivilege();

            // 权限读取到缓存
            roles.Each(item => MemoryCacheUtil.Set(item.GetRoleKey, new RolePrivilegeModel()
            {
                Role = item.GetSysRole(), Privileges = item.GetRolePrivilege()
            }, 3600 * 12));

            return(app);
        }
Example #14
0
        public static bool Set(string key, DateTimeOffset?absoluteExpiration, object obj)
        {
            bool isok = false;

            if (obj != null)
            {
                if (!absoluteExpiration.HasValue)
                {
                    absoluteExpiration = DateTimeOffset.Now.AddSeconds(3);
                }
                MemoryCacheUtil.Set(key, obj, absoluteExpiration.Value);
                isok = true;
            }
            return(isok);
        }
Example #15
0
        /// <summary>
        /// 刷新Token
        /// </summary>
        public static AccessTokenResponse RefreshToken()
        {
            var result      = WeChatApi.GetAccessToken(_appid, _secret);
            var accessToken = new AccessTokenResponse()
            {
                AccessToken = result.AccessToken,
                Expire      = result.Expire
            };

            MemoryCacheUtil.RemoveCacheItem("AccessToken");
            MemoryCacheUtil.Set("AccessToken", accessToken);
            var logger = LogFactory.GetLogger("wechat");

            logger.Debug("获取微信access_token成功:" + accessToken.AccessToken);
            return(accessToken);
        }
Example #16
0
        /// <summary>
        /// 获取角色权限
        /// </summary>
        /// <param name="roleName"></param>
        /// <returns></returns>
        public IEnumerable <sys_role_privilege> GetRolePrivilege()
        {
            var key = $"{PRIVILEGE_PREFIX}_{RoleName}";

            return(MemoryCacheUtil.GetOrAddCacheItem(key, () =>
            {
                var sql = @"
SELECT * FROM sys_role_privilege
WHERE sys_roleidName = @name
";
                var dataList = Broker.RetrieveMultiple <sys_role_privilege>(sql, new Dictionary <string, object>()
                {
                    { "@name", Role.GetDescription() }
                });
                return dataList;
            }, DateTime.Now.AddHours(12)));
        }
Example #17
0
        public static T Get <T>(string key, TimeSpan?slidingExpiration, Func <T> fetch)
        {
            T result = MemoryCacheUtil.Get <T>(key);

            if (result == null)
            {
                result = fetch();
                if (result != null)
                {
                    if (!slidingExpiration.HasValue)
                    {
                        slidingExpiration = TimeSpan.FromMinutes(30);
                    }
                    MemoryCacheUtil.Set(key, result, slidingExpiration.Value);
                }
            }
            return(result);
        }
Example #18
0
        public static T Get <T>(string key, DateTimeOffset?absoluteExpiration, Func <T> fetch)
        {
            T result = MemoryCacheUtil.Get <T>(key);

            if (result == null)
            {
                result = fetch();
                if (result != null)
                {
                    if (!absoluteExpiration.HasValue)
                    {
                        absoluteExpiration = DateTimeOffset.Now.AddSeconds(3);
                    }
                    MemoryCacheUtil.Set(key, result, absoluteExpiration.Value);
                }
            }
            return(result);
        }
Example #19
0
        /// <summary>
        /// 设置实时开奖信息
        /// </summary>
        /// <param name="cacheKeyPre"></param>
        /// <param name="realTimeInfoDto"></param>
        /// <param name="absoluteExpiration"></param>
        public static string SetRealTimeDrawInfo(string cacheKeyPre, LotteryRealTimeInfoDto realTimeInfoDto, DateTimeOffset?absoluteExpiration = null, bool isIgnoreNullAndZero = true)
        {
            if (!absoluteExpiration.HasValue)
            {
                absoluteExpiration = DateTimeOffset.Now.AddSeconds(3);
            }

            string jsonRealTime = string.Empty;

            if (isIgnoreNullAndZero)
            {
                jsonRealTime = JsonUtil.SerializeFilterZeroAndNull(realTimeInfoDto);
            }
            else
            {
                jsonRealTime = JsonUtil.Serialize(realTimeInfoDto);
            }

            MemoryCacheUtil.Set(cacheKeyPre + "0", jsonRealTime, absoluteExpiration.Value); // 最新开奖的缓存3秒,以便及时取得最新开奖结果
            return(jsonRealTime);
        }
Example #20
0
        /// <summary>
        /// 今日历史数据缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="periodDrawRecords"></param>
        /// <param name="absoluteExpiration"></param>
        /// <returns></returns>
        public static string SetHistoryDrawInfoToday(string cacheKey, List <PeriodDrawRecordDto> periodDrawRecords, DateTimeOffset?absoluteExpiration = null, bool isIgnoreNullAndZero = true)
        {
            if (!absoluteExpiration.HasValue)
            {
                absoluteExpiration = DateTimeOffset.Now.AddSeconds(3);
            }

            string jsonHistoryDraw = string.Empty;

            if (isIgnoreNullAndZero)
            {
                jsonHistoryDraw = JsonUtil.SerializeFilterZeroAndNull(periodDrawRecords);
            }
            else
            {
                jsonHistoryDraw = JsonUtil.Serialize(periodDrawRecords);
            }

            MemoryCacheUtil.Set(cacheKey, jsonHistoryDraw, absoluteExpiration.Value); // 属于今日期次的缓存3秒
            return(jsonHistoryDraw);
        }
Example #21
0
        /// <summary>
        /// 非今日历史数据,滑动缓存
        /// </summary>
        /// <param name="cacheKey"></param>
        /// <param name="periodDrawRecords"></param>
        /// <param name="slidingExpiration"></param>
        /// <returns></returns>
        public static string SetHistoryDrawInfoNoToday(string cacheKey, List <PeriodDrawRecordDto> periodDrawRecords, TimeSpan?slidingExpiration = null, bool isIgnoreNullAndZero = true)
        {
            if (!slidingExpiration.HasValue)
            {
                slidingExpiration = TimeSpan.FromMinutes(30);
            }

            string jsonHistoryDraw = string.Empty;

            if (isIgnoreNullAndZero)
            {
                jsonHistoryDraw = JsonUtil.SerializeFilterZeroAndNull(periodDrawRecords);
            }
            else
            {
                jsonHistoryDraw = JsonUtil.Serialize(periodDrawRecords);
            }

            MemoryCacheUtil.Set(cacheKey, jsonHistoryDraw, slidingExpiration.Value);
            return(jsonHistoryDraw);
        }
Example #22
0
        private void InitControls()
        {
            klineMenu.Tag = MemoryCacheUtil.GetCacheItem <Form>(nameof(FormKline));
            AnaMenu.Tag   = MemoryCacheUtil.GetCacheItem <Form>(nameof(FormAnalysis));


            ContextMenuStrip contextMenuStrip = new ContextMenuStrip(new Container());

            contextMenuStrip.Items.AddRange(new ToolStripItem[]
            {
                new ToolStripMenuItem("Exit", null, Exit)
            });

            _notifyIcon = new NotifyIcon()
            {
                Icon             = Resources.Bitcoin,
                ContextMenuStrip = contextMenuStrip,
                Visible          = true
            };
            _notifyIcon.DoubleClick += new EventHandler(HandleDoubleClick);
        }
Example #23
0
        public Captcha GenerateCaptcha()
        {
            const string dicString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

            var random = new Random();
            var text   = new char[4];

            for (var i = 0; i < 4; ++i)
            {
                text[i] = dicString[random.Next(0, dicString.Length - 1)];
            }

            var captchaId = Guid.NewGuid();

            MemoryCacheUtil.SetItem(captchaId.ToString(), text);

            return(new Captcha
            {
                Id = captchaId,
                Image = Convert.ToBase64String(CaptchaUtil.CreateCaptcha(new string(text)))
            });
        }
Example #24
0
        /// <summary>
        /// 获取角色
        /// </summary>
        /// <param name="roleName"></param>
        /// <returns></returns>
        public sys_role GetSysRole()
        {
            var key = $"{ROLE_PREFIX}_{RoleName}";

            return(MemoryCacheUtil.GetOrAddCacheItem(key, () =>
            {
                var role = Broker.Retrieve <sys_role>("select * from sys_role where name = @name", new Dictionary <string, object>()
                {
                    { "@name", Role.GetDescription() }
                });
                if (role == null)
                {
                    role = new sys_role()
                    {
                        Id = Guid.NewGuid().ToString(),
                        name = Role.GetDescription(),
                        is_basic = true
                    };
                    Broker.Create(role);
                }
                return role;
            }, DateTime.Now.AddHours(12)));
        }
Example #25
0
        //获取小程序码
        public MyResult <object> GetUnlimited(int userId = 0)
        {
            MyResult result = new MyResult();

            if (userId <= 0)
            {
                return(result.SetStatus(ErrorCode.InvalidData, "用户Id为空 请联重新登陆"));
            }
            var user = base.First <User>(predicate => predicate.Id == userId);

            if (user == null)
            {
                return(result.SetStatus(ErrorCode.InvalidData, "用户不存在"));
            }
            if (!string.IsNullOrEmpty(user.UPic))
            {
                result.Data = PathUtil.CombineWithRoot(user.UPic);
                return(result);
            }
            var access_token = MemoryCacheUtil.Get(Constants.WxAccessToken);

            if (access_token == null)
            {
                SetAccessToken();
                access_token = MemoryCacheUtil.Get(Constants.WxAccessToken);
            }
            var UnlimitedUrl = $"https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={access_token}";
            var _scene       = $"inviter_id={userId}";
            var rep          = HttpUtil.PostByte(UnlimitedUrl, new { scene = _scene, is_hyaline = false }.GetJson(), "application/json");
            var url          = ImageHandlerUtil.SaveByteImage(rep, $"{Constants.WxPic}/{userId}");

            user.UPic = url;
            base.Update(user, true);
            result.Data = PathUtil.CombineWithRoot(url);
            return(result);
        }
Example #26
0
 public static string GetHistoryDrawInfo(string cacheKey)
 {
     return(MemoryCacheUtil.GetString(cacheKey));
 }
Example #27
0
 /// <summary>
 /// 获取实时开奖信息
 /// </summary>
 /// <param name="cacheKeyPre"></param>
 /// <returns></returns>
 public static string GetRealTimeDrawInfo(string cacheKeyPre)
 {
     return(MemoryCacheUtil.GetString(cacheKeyPre + "0"));
 }
Example #28
0
 /// <summary>
 /// 清除角色缓存
 /// </summary>
 public void ClearCache()
 {
     MemoryCacheUtil.RemoveCacheItem($"{PRIVILEGE_PREFIX}_{RoleName}");
     MemoryCacheUtil.RemoveCacheItem($"{ROLE_PREFIX}_{RoleName}");
 }