public List <int> GetAnosExerciciosPermitidos(Exercicio.tipoExercicio tipoExercicio, int matricula, int idTipoSimulado, bool getOnline = false, int idAplicacao = 1) { if (!RedisCacheManager.CannotCache(RedisCacheConstants.DadosFakes.KeyGetAnosExerciciosPermitidos)) { return(RedisCacheManager.GetItemObject <List <int> >(RedisCacheConstants.DadosFakes.KeyGetAnosExerciciosPermitidos)); } var anos = _exercicioRepository.GetAnosSimulados(matricula, getOnline, idAplicacao, idTipoSimulado); var produtosContratados = _produtoRepository.GetProdutosContratadosPorAnoMatricula(matricula); int ano; try { ano = Utilidades.GetYear(); } catch { ano = DateTime.Today.Year; } var produtosAnoCorrente = produtosContratados.FindAll(x => x.Ano == ano); return(anos); }
public ResponseDTO <List <int> > ObterTemasRevalidaPermitidos(int matriculaId) { var response = new ResponseDTO <List <int> >(); if (!RedisCacheManager.CannotCache(RedisCacheConstants.DadosFakes.KeyObterTemasRevalidaPermitidos)) { return(RedisCacheManager.GetItemObject <ResponseDTO <List <int> > >(RedisCacheConstants.DadosFakes.KeyObterTemasRevalidaPermitidos)); } try { var temasRevalida = _mednetRepo.GetVideosRevalida(matriculaId); var temasPermitidos = temasRevalida.Select(x => x.GrupoId.Value).Distinct().ToList(); response.Sucesso = true; response.Retorno = temasPermitidos; } catch (Exception e) { response.Sucesso = false; response.Retorno = null; response.Mensagem = e.Message; } return(response); }
private bool VersaoBloqueadaCache(string appVersion, int produtoId) { try { var key = String.Format("{0}:{1}", RedisCacheConstants.Config.KeyVersaoBloqueadaCache, appVersion, produtoId); if (!RedisCacheManager.HasAny(key)) { var versao = _versaoAppPermissaoRepository.GetUltimaVersaoBloqueada(produtoId); if (String.IsNullOrEmpty(versao)) // id de produto não existe { return(false); } var bloqueada = VersaoMenorOuIgual(appVersion, versao); RedisCacheManager.SetItemObject(key, bloqueada, TimeSpan.FromHours(1)); return(bloqueada); } else { return(RedisCacheManager.GetItemObject <bool>(key)); } } catch (Exception ex) { throw ex; } }
public List <RespostaConcursoQuestoesDTO> ObterQuestoesAlternativaCache() { try { if (RedisCacheManager.CannotCache(RedisCacheConstants.Questao.KeyGetQuestaoMontaProva)) { return(GetAllQuestoesAlternativa()); } var key = String.Format("{0}:{1}", RedisCacheConstants.Questao.KeyGetQuestaoMontaProva, DateTime.Today.ToString("d")); var questoesMontaProva = RedisCacheManager.GetItemObject <List <RespostaConcursoQuestoesDTO> >(key); if (questoesMontaProva == null) { questoesMontaProva = GetAllQuestoesAlternativa(); if (questoesMontaProva != null) { RedisCacheManager.DeleteGroup(RedisCacheConstants.Questao.KeyGetQuestaoMontaProva); RedisCacheManager.SetItemObject(key, questoesMontaProva); } } return(questoesMontaProva); } catch { return(GetAllQuestoesAlternativa()); } }
/// <summary> /// 获取JWT字符串并存入缓存 /// </summary> /// <param name="tm"></param> /// <param name="expireSliding"></param> /// <param name="expireAbsoulte"></param> /// <returns></returns> public static string IssueJWT(TokenModel tokenModel, TimeSpan expiresSliding, TimeSpan expiresAbsoulte) { DateTime UTC = DateTime.UtcNow; Claim[] claims = new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, tokenModel.Sub), //Subject, new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), //JWT ID,JWT的唯一标识 new Claim(JwtRegisteredClaimNames.Iat, UTC.AddMinutes(30).ToString(), ClaimValueTypes.Integer64), //Issued At,JWT颁发的时间,采用标准unix时间,用于验证过期 }; JwtSecurityToken jwt = new JwtSecurityToken( issuer: Config.JWTInfo.Issuer, //jwt签发者,非必须 //audience: tokenModel.Uname,//jwt的接收该方,非必须 claims: claims, //声明集合 notBefore: UTC, expires: UTC.AddHours(12), //指定token的生命周期,unix时间戳格式,非必须 signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Config.JWTInfo.SigningKey)), SecurityAlgorithms.HmacSha256) //使用私钥进行签名加密 ); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);//生成最后的JWT字符串 ICacheManager redis = new RedisCacheManager(); redis.Set(encodedJwt, tokenModel, expiresSliding, expiresAbsoulte);//将JWT字符串和tokenModel作为key和value存入缓存 return(encodedJwt); }
public int GetAvaliar(int matricula) { if (!RedisCacheManager.CannotCache(RedisCacheConstants.DadosFakes.KeyGetAvaliar)) { return(RedisCacheManager.GetItemObject <int>(RedisCacheConstants.DadosFakes.KeyGetAvaliar)); } var isCacheEnable = !RedisCacheManager.CannotCache(RedisCacheConstants.AvaliacaoAlunoEntity.KeyAvaliacaoAlunoGetAvaliar); var key = isCacheEnable ? RedisCacheManager.GenerateKey(RedisCacheConstants.AvaliacaoAlunoEntity.KeyAvaliacaoAlunoGetAvaliar, matricula) : null; string bitAvaliarStr = isCacheEnable ? RedisCacheManager.GetItemString(key) : null; if (!String.IsNullOrEmpty(bitAvaliarStr)) { return(Convert.ToInt32(bitAvaliarStr)); } var bitAvaliar = GetAvaliarNonCache(matricula); if (isCacheEnable) { var timeoutHour = 1; RedisCacheManager.SetItemString(key, bitAvaliar.ToString(), TimeSpan.FromHours(timeoutHour)); } return(bitAvaliar); }
public float GetTempoInadimplenciaTimeoutParametro() { var key = RedisCacheConstants.Config.KeyTempoInadimplenciaTimeout; if (!RedisCacheManager.CannotCache(key)) { return(GetTempoInadimplenciaTimeoutParametroCache()); } else { string tempoChecaInadimplencia; using (var ctx = new DesenvContext()) { var configs = from t in ctx.tblParametrosGenericos where t.txtName.Equals("intTimeoutChecaInadimplencia") select t.txtValue; tempoChecaInadimplencia = configs.FirstOrDefault(); } var timeout = float.Parse(tempoChecaInadimplencia, CultureInfo.InvariantCulture); return(timeout); } }
private void CreateManager(bool compress = false) { ConfigureOptions <SchubertRedisOptions> prop = new ConfigureOptions <SchubertRedisOptions>(op => { op.ConnectionString = "127.0.0.1:6379,abortConnect=false,ssl=false"; //op.ConnectionString = "10.66.126.116:19000,abortConnect = false,ssl = false,password = Setpay123,connectTimeout = 10000,syncTimeout = 120000"; op.GZipCompress = compress; op.SerializerName = RedisSerializerNames.JsonNet; }); IOptions <SchubertRedisOptions> options = new OptionsManager <SchubertRedisOptions>(new OptionsFactory <SchubertRedisOptions>(new IConfigureOptions <SchubertRedisOptions>[] { prop }, new IPostConfigureOptions <SchubertRedisOptions> [0])); var sop = new ConfigureOptions <SchubertOptions>(op => { op.AppSystemName = "testapp"; op.Group = "jcgjz"; }); IOptions <SchubertOptions> schubertOptions = new OptionsManager <SchubertOptions>(new OptionsFactory <SchubertOptions>(new IConfigureOptions <SchubertOptions>[] { sop }, new IPostConfigureOptions <SchubertOptions> [0])); _manager = new RedisCacheManager(schubertOptions, options); }
public int GetProgressoVideoDevido(ProgressoVideo progresso) { decimal duracao = 0; try { if (RedisCacheManager.CannotCache(RedisCacheConstants.Video.KeyDuracaoVideoRevisaoAula)) { duracao = _mednetRepository.GetVideoDuracaoPorIdRevisaoAula(progresso.IdRevisaoAula); } else { var key = String.Format("{0}:{1}", RedisCacheConstants.Video.KeyDuracaoVideoRevisaoAula, progresso.IdRevisaoAula); duracao = RedisCacheManager.GetItemObject <decimal>(key); if (duracao == 0) { duracao = _mednetRepository.GetVideoDuracaoPorIdRevisaoAula(progresso.IdRevisaoAula); RedisCacheManager.SetItemObject(key, duracao); } } } catch { duracao = _mednetRepository.GetVideoDuracaoPorIdRevisaoAula(progresso.IdRevisaoAula); } if (progresso.ProgressoSegundo > (int)Math.Ceiling(duracao)) { progresso.ProgressoSegundo = (int)Math.Ceiling(duracao); } return(progresso.ProgressoSegundo); }
public static void SetRedisMessage(string key, string message) { RedisCacheManager manager = new RedisCacheManager(); manager.Set(key, message); //using (ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost")) //{ // // ^^^ store and re-use this!!! // IDatabase db = redis.GetDatabase(); // db.StringSet(key, Encoding.UTF8.GetBytes(message)); //} //string value = db.StringGet("mykey"); // Console.WriteLine(value); // writes: "abcdefg" //using (IRedisNativeClient client = new RedisClient()) //{ // //var clientQueue = client.As<MessageQueueEntity>(); // //var savedCustomer = clientQueue.Store(queueEntity); // client.Set(key, Encoding.UTF8.GetBytes(message)); // //string result = Encoding.UTF8.GetString(client.Get("Mesaj:1")); // // client.Del("Mesaj:1"); // //Console.WriteLine($"Değer : {result}"); //} }
public List <BlackboardGrade> GetGrades(int RowsCount) { var grades = new List <BlackboardGrade>(); var unpulledGradesListCacheKey = CacheSchema.SortedSets.KeyBlackboardGradeUnpulled(); var pulledGradesListCacheKey = CacheSchema.SortedSets.KeyBlackboardGradePulled(RequestIdManager.RequestId); var pulledGradesHistoryListCacheKey = CacheSchema.SortedSets.KeyBlackboardGradePulledHistory(); using (var redisCacheManager = new RedisCacheManager()) { var gradesKeys = PeekGrades(RowsCount); var gradesCacheKeys = gradesKeys.Select(x => new SimpleCacheKey(x)).ToList(); grades = redisCacheManager.GetMultiple <BlackboardGrade>(gradesCacheKeys).ToList(); // transfer keys from UNPULLED list to PULLED list // + add the current PULLED list key to the PULLED History list (to avoid the search on 'SearchPulledGradesLists') if (grades.Count > 0) { var actionAddGradeKeysToPulledList = new RedisTransactionAction(eRedisTransactionActionType.AddToUniqueList, pulledGradesListCacheKey, gradesKeys); var actionRemoveGradeKeysFromUnpulledList = new RedisTransactionAction(eRedisTransactionActionType.RemoveFromUniqueList, unpulledGradesListCacheKey, gradesKeys); var actionAddPulledListToHistory = new RedisTransactionAction(eRedisTransactionActionType.AddToUniqueList, pulledGradesHistoryListCacheKey, new List <string> { pulledGradesListCacheKey.KeyString }); redisCacheManager.MakeTransaction(actionAddGradeKeysToPulledList, actionRemoveGradeKeysFromUnpulledList, actionAddPulledListToHistory); } } return(grades); }
public void GetAsync_WhenCalled_ExpectResponse() { // Arrange var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns( new RedisCacheConfigurationEntity { CacheDuration = 10, RedisCacheDefaultPrefix = "DEFAULT", UseObjectCompression = false }); var jsonSettingsFactory = new JsonSettingsFactory(new CustomMappersConfiguration()); var cacheManager = new RedisCacheManager<Token>( RedisHelpers.ConnectionMultiplexer, mockCacheConfiguration.Object, jsonSettingsFactory.Create()); var tokenStore = new TokenHandleStore( cacheManager, mockCacheConfiguration.Object); // Act var stopwatch = Stopwatch.StartNew(); var token = tokenStore.GetAsync("Existing").Result; stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); Assert.That(token, Is.Not.Null); }
public ActionResult <DtoUser> Post(Refresh refresh) { try { var redisManager = new RedisCacheManager(); _logger.LogInformation("refresh istegi geldi..."); var tokens = new JwtSecurityToken(jwtEncodedString: refresh.authToken); var userId = tokens.Claims.First(c => c.Type == "unique_name").Value; var session = redisManager.Get(userId); if (session == null) { return(BadRequest()); } if (!refresh.authToken.Equals(session)) { return(Forbid()); } var user = _userContext.users.FirstOrDefault(u => u.id.Equals(long.Parse(userId)) && u.refreshtoken.Equals(refresh.refreshToken)); if (user == null) { return(Forbid()); } if (user.refreshtokenexpirationdate > DateTime.Now) { TokenHandler tokenHandler = new TokenHandler(); Token token = tokenHandler.CreateAccessToken(user.id); user.refreshtoken = token.RefreshToken; _userContext.SaveChanges(); redisManager.Remove(user.id.ToString()); redisManager.Set(user.id.ToString(), token.AccessToken, 300); return(Ok(new DtoUser { authToken = token.AccessToken, name = user.name, surname = user.surname, refreshToken = token.RefreshToken })); } return(Forbid()); } catch (Exception e) { _logger.LogError(e.ToString()); return(BadRequest()); } }
public ActionResult Category(int id) { RedisCacheManager manager = new RedisCacheManager(); var products = manager.Get <List <Products> >(id.ToString()); return(View(products)); }
public void SetClaimCache() { var redisConnString = "localhost:6379"; var options = ConfigurationOptions.Parse(redisConnString); options.AllowAdmin = true; options.Proxy = Proxy.Twemproxy; var connection = ConnectionMultiplexer.Connect(options); ICacheManager cacheClient = new RedisCacheManager(connection); var claim = new Claim("test_claim", "testClaimValue"); cacheClient.Add("testClaimCache", claim, TimeSpan.FromMinutes(30)); var claimFromCache = cacheClient.Get <Claim>("testClaimCache"); Assert.IsNotNull(claimFromCache); IEnumerable <Claim> claims = new List <Claim> { claim, claim, claim }; cacheClient.Add("testClaimCacheList", claims, TimeSpan.FromMinutes(30)); var claimsFromCache = cacheClient.Get <IEnumerable <Claim> >("testClaimCacheList"); Assert.IsNotNull(claimsFromCache); }
public List <Int32> GetImagensQuestaoConcursoCache(int questaoID) { try { var key = String.Format("{0}:{1}", RedisCacheConstants.Questao.KeyGetImagensQuestaoConcurso, questaoID); if (RedisCacheManager.CannotCache(RedisCacheConstants.Questao.KeyGetImagensQuestaoConcurso)) { return(GetImagensQuestaoConcurso(questaoID)); } if (RedisCacheManager.HasAny(key)) { return(RedisCacheManager.GetItemObject <List <Int32> >(key)); } else { var lista = GetImagensQuestaoConcurso(questaoID); RedisCacheManager.SetItemObject(key, lista); return(lista); } } catch (Exception) { return(GetImagensQuestaoConcurso(questaoID)); } }
public float GetTempoInadimplenciaTimeoutParametroCache() { string tempoChecaInadimplencia; var key = RedisCacheConstants.Config.KeyTempoInadimplenciaTimeout; if (!RedisCacheManager.HasAny(key)) { using (var ctx = new DesenvContext()) { var configs = from t in ctx.tblParametrosGenericos where t.txtName.Equals("intTimeoutChecaInadimplencia") select t.txtValue; tempoChecaInadimplencia = configs.FirstOrDefault(); } } else { return(RedisCacheManager.GetItemObject <float>(key)); } var timeout = float.Parse(tempoChecaInadimplencia, CultureInfo.InvariantCulture); RedisCacheManager.SetItemObject(key, timeout, TimeSpan.FromHours(1)); return(timeout); }
public static string GetRedisMessage(string key) { RedisCacheManager manager = new RedisCacheManager(); string result = manager.Get(key); var removeResult = manager.Remove(key); return(result); //using (IRedisNativeClient client = new RedisClient()) //{ // //var clientQueue = client.As<MessageQueueEntity>(); // //var savedCustomer = clientQueue.Store(queueEntity); // string result = Encoding.UTF8.GetString(client.Get(key)); // client.Del(key); // return result; // // client.Del("Mesaj:1"); // //Console.WriteLine($"Değer : {result}"); //} return(string.Empty); }
/* * public List<string> SearchPulledGradesLists() * { * // send an empty request id in order to get only the key prefix! * var prefix = CacheSchema.SortedSets.KeyBlackboardGradePulled(string.Empty); * using (var redisCacheManager = new RedisCacheManager()) * return redisCacheManager.SearchKeys(string.Format("{0}*", prefix.KeyString)).ToList();//todo: find a way without doing key searches - suggest changing the cache schema. * } */ public List <string> SearchPulledGradesLists() { var pulledGradesHistoryListCacheKey = CacheSchema.SortedSets.KeyBlackboardGradePulledHistory(); using (var redisCacheManager = new RedisCacheManager()) return(redisCacheManager.GetAllFromUniqueList <string>(pulledGradesHistoryListCacheKey).ToList()); }
public EnumTipoPerfil GetTipoPerfilUsuario(int intEmployeeID) { if (!RedisCacheManager.CannotCache(RedisCacheConstants.DadosFakes.KeyGetTipoPerfilUsuario)) { return((EnumTipoPerfil)RedisCacheManager.GetItemObject <int>(RedisCacheConstants.DadosFakes.KeyGetTipoPerfilUsuario)); } using (var ctx = new DesenvContext()) { var role = ctx.tblCtrlPanel_AccessControl_Persons_X_Roles .Where(b => b.intContactId == intEmployeeID && new List <long>() { 2, 4, 6 }.Contains(b.intRoleId)) .ToList(); if (role == null) { return(EnumTipoPerfil.None); } if (role.Count() == 0) { return(EnumTipoPerfil.None); } if (role.Select(b => b.intRoleId).Any(b => b == 2)) { return(EnumTipoPerfil.Master); } if (role.Select(b => b.intRoleId).Any(b => b == 6)) { return(EnumTipoPerfil.Coordenador); } return(EnumTipoPerfil.Professor); } }
/* * public bool SaveRequestGrades(List<string> gradeKeys) * { * var pulledGradesListCacheKey = CacheSchema.SortedSets.KeyBlackboardGradePulled(RequestIdManager.RequestId); * * using (var redisCacheManager = new RedisCacheManager()) * return redisCacheManager.AddToUniqueList<List<string>>(pulledGradesListCacheKey, gradeKeys); * } */ public bool SaveGradesStatuses(string RequestId, List <GradeStatus> gradeStatuses) { var statusGradesListCacheKey = CacheSchema.SortedSets.KeyBlackboardGradeStatus(RequestId); using (var redisCacheManager = new RedisCacheManager()) return(redisCacheManager.AddToUniqueList <List <GradeStatus> >(statusGradesListCacheKey, gradeStatuses)); }
public List <Combo> GetComboAposLancamentoMsProCache(int idClient, int applicationId, string versaoApp) { if (!RedisCacheManager.CannotCache(RedisCacheConstants.DadosFakes.KeyGetComboAposLancamentoMsPro)) { return(RedisCacheManager.GetItemObject <List <Combo> >(RedisCacheConstants.DadosFakes.KeyGetComboAposLancamentoMsPro)); } try { if (RedisCacheManager.CannotCache(RedisCacheConstants.Combo.KeyGetComboAposLancamentoMsPro)) { return(GetComboAposLancamentoMsPro(idClient, applicationId, versaoApp)); } var key = String.Format("{0}:{1}:{2}:{3}", RedisCacheConstants.Combo.KeyGetComboAposLancamentoMsPro, idClient, applicationId, versaoApp); var combo = RedisCacheManager.GetItemObject <List <Combo> >(key); if (combo == null) { combo = GetComboAposLancamentoMsPro(idClient, applicationId, versaoApp); if (combo != null) { RedisCacheManager.SetItemObject(key, combo); } } return(combo); } catch (Exception) { return(GetComboAposLancamentoMsPro(idClient, applicationId, versaoApp)); } }
private Cliente CacheClienteGetByFilters(String register, int idAplicacao) { if (!RedisCacheManager.CannotCache(RedisCacheConstants.Login.KeyLoginClienteGetByFilters)) { var Key = string.Format("{0}:{1}:{2}", RedisCacheConstants.Login.KeyLoginClienteGetByFilters, register, idAplicacao); var ret = RedisCacheManager.GetItemObject <Cliente>(Key); if (ret != null) { return(ret); } else { var cliente = _clienteRepository.GetByFilters(new Cliente { Register = register }, aplicacao: (Aplicacoes)Convert.ToInt32(idAplicacao)) .FirstOrDefault(); RedisCacheManager.SetItemObject(Key, cliente, TimeSpan.FromMinutes(5)); return(cliente); } } else { return(_clienteRepository.GetByFilters(new Cliente { Register = register }, aplicacao: (Aplicacoes)Convert.ToInt32(idAplicacao)) .FirstOrDefault()); } }
/// <summary> /// /// </summary> public MqConfigService() { _searchService = new RawSqlSearchService(DbConfigHelper.GetConfig()); _computerAccess = new ConfigCenterClusterComputerAccess(DbConfigHelper.GetConfig()); _cacheManager = new RedisCacheManager((int)CacheRegionName.MqConfig); _logger = LoggerFactory.GetLog(); }
public string GetLatestUpdatesRequestId() { var cacheKey = CacheSchema.KeyBlackboardGetUpdatesLatestRequestId(); using (var redisCacheManager = new RedisCacheManager()) return(redisCacheManager.Get <string>(cacheKey)); }
public static List <Produto> GetProdutosContratadosPorAnoComCache(int intClientID) { try { if (RedisCacheManager.CannotCache(RedisCacheConstants.Permissao.GetProdutosContratadosPorAno)) { return(GetProdutosContratadosPorAno(intClientID)); } var key = String.Format("{0}:{1}", RedisCacheConstants.Permissao.GetProdutosContratadosPorAno, intClientID); var produtos = RedisCacheManager.GetItemObject <List <Produto> >(key); if (produtos == null) { produtos = GetProdutosContratadosPorAno(intClientID); if (produtos != null) { RedisCacheManager.SetItemObject(key, produtos, TimeSpan.FromMinutes(RedisCacheConstants.Permissao.ValidadeGetProdutosContratadosPorAno)); } } return(produtos); } catch { return(GetProdutosContratadosPorAno(intClientID)); } }
public RankingSimuladoAluno GetResultadoRankingAluno(int matricula, int idSimulado, int idAplicacao, string especialidade, string unidades, string localidade = "") { try { using (MiniProfiler.Current.Step("Obtendo resultado ranking aluno")) { var simuladoConsolidado = _rankingSimuladoRepository.GetSimuladoConsolidado(matricula, idSimulado); var result = new RankingSimuladoAluno(); if (simuladoConsolidado == null) { result.EstatisticasAlunoRankingOnline = _rankingSimuladoRepository.GetEstatisticaAlunoSimulado(matricula, idSimulado, true); _rankingSimuladoRepository.InsertSimuladoConsolidado(matricula, idSimulado, result.EstatisticasAlunoRankingOnline); } else { result.EstatisticasAlunoRankingOnline = _rankingSimuladoRepository.GetEstatisticaAlunoSimulado(matricula, idSimulado, true); } result.EstatisticasAlunoRankingEstudo = _rankingSimuladoRepository.GetEstatisticaAlunoSimulado(matricula, idSimulado, false); var local = string.IsNullOrEmpty(localidade) ? string.Empty : (localidade.IndexOf('(') > 0 ? localidade.Substring(0, localidade.IndexOf('(')).Trim() : localidade); var rank = new RankingSimuladoAluno(); try { if (RedisCacheManager.CannotCache(RedisCacheConstants.Simulado.KeyRankingSimulado)) { rank = _rankingSimuladoRepository.GetRankingObjetiva(matricula, idSimulado, especialidade, unidades, local); } else { rank = _rankingSimuladoRepository.GetRankingObjetivaCache(matricula, idSimulado, especialidade, unidades, local); } } catch (Exception) { rank = _rankingSimuladoRepository.GetRankingObjetiva(matricula, idSimulado, especialidade, unidades, local); } if (rank != null) { result.Nota = rank.Nota; result.Posicao = rank.Posicao; result.DataRealizacao = rank.Simulado.DtHoraInicio; result.QuantidadeParticipantes = (int)Math.Ceiling(Convert.ToDecimal(getQuantidadeParticipantesRanking(rank.QuantidadeParticipantes)) / 2); } return(result); } } catch (Exception e) { throw e; } }
public void Register(ContainerBuilder builder, ITypeFinder typeFinder, JIFConfig config) { // OPTIONAL: Register controllers builder.RegisterControllers(typeFinder.GetAssemblies().ToArray()); // OPTIONAL: Register model binders that require DI. builder.RegisterModelBinders(typeFinder.GetAssemblies().ToArray()); builder.RegisterModelBinderProvider(); // OPTIONAL: Register web abstractions like HttpContextBase. builder.RegisterModule <AutofacWebTypesModule>(); // OPTIONAL: Enable property injection in view pages. builder.RegisterSource(new ViewRegistrationSource()); // OPTIONAL: Enable property injection into action filters. builder.RegisterFilterProvider(); // OPTIONAL: register dbcontext builder.Register <DbContext>(c => new JIFDbContext("name=JIF.CMS.DB")).InstancePerLifetimeScope(); // OPTIONAL: repositores builder.RegisterGeneric(typeof(EfRepository <>)).As(typeof(IRepository <>)).InstancePerLifetimeScope(); // OPTIONAL: logging builder.RegisterInstance(LogManager.GetLogger(string.Empty)).As <ILog>().SingleInstance(); // OPTIONAL: AuthenticationService builder.RegisterType <CustomizeCookiesAuthenticationService>().As <IAuthenticationService>().InstancePerLifetimeScope(); // OPTIONAL: work context builder.RegisterType <WebWorkContext>().As <IWorkContext>().InstancePerLifetimeScope(); // OPTIONAL: Caches if (config.RedisConfig != null && config.RedisConfig.Enabled) { // 首先是 ConnectionMultiplexer 的封装,ConnectionMultiplexer对象是StackExchange.Redis最中枢的对象。 // 这个类的实例需要被整个应用程序域共享和重用的,所以不需要在每个操作中不停的创建该对象的实例,一般都是使用单例来创建和存放这个对象,这个在官网上也有说明。 // http://www.cnblogs.com/qtqq/p/5951201.html // https://stackexchange.github.io/StackExchange.Redis/Basics //builder.RegisterType<RedisConnectionWrapper>().As<RedisConnectionWrapper>().SingleInstance(); //// TODO: 应该在这里设置配置链接信息, Wrapper 不需要暴漏出来. //builder.RegisterType<RedisConnectionWrapper>().SingleInstance(); var rcm = new RedisCacheManager(config.RedisConfig); builder.RegisterInstance(rcm).As <ICacheManager>().SingleInstance(); } else { builder.RegisterType <MemoryCacheManager>().As <ICacheManager>().SingleInstance(); } // Services builder.RegisterType <ArticleService>().As <IArticleService>().InstancePerLifetimeScope(); builder.RegisterType <SysManagerService>().As <ISysManagerService>().InstancePerLifetimeScope(); builder.RegisterType <AttachmentService>().As <IAttachmentService>().InstancePerLifetimeScope(); }
public ActionResult Index() { RedisCacheManager manager = new RedisCacheManager(); var categories = manager.Get <List <Categories> >("categories"); ViewBag.Categories = categories; return(View()); }
public void start(SCApplication app) { scApp = app; redisCacheManager = app.getRedisCacheManager(); REDIS_KEY_WORD_MASTER_Name = string.Format(REDIS_KEY_WORD_MASTER_TITLE, SCApplication.ServerName); //scApp.getEQObjCacheManager().getLine().ServiceMode = // isActive() ? SCAppConstants.AppServiceMode.Active : SCAppConstants.AppServiceMode.Standby; }
public void Connect_Redis_Test() { RedisCacheManager _redisCacheManager = new RedisCacheManager(); var redisBlogCache = _redisCacheManager.Get <object>("Redis.Blog"); Assert.NotNull(redisBlogCache); }
public void GetAsync_WhenCalled_ExpectResponse() { // Arrange var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns( new RedisCacheConfigurationEntity { CacheDuration = 10, RedisCacheDefaultPrefix = "DEFAULT", UseObjectCompression = false }); var jsonSettingsFactory = new JsonSettingsFactory(new CustomMappersConfiguration()); var cacheManager = new RedisCacheManager<AuthorizationCode>( RedisHelpers.ConnectionMultiplexer, mockCacheConfiguration.Object, jsonSettingsFactory.Create()); var authorizationCodeStore = new AuthorizationCodeStore( cacheManager, mockCacheConfiguration.Object); // Act var stopwatch = Stopwatch.StartNew(); var authorizationCode = authorizationCodeStore.GetAsync("Existing").Result; stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); Assert.That(authorizationCode, Is.Not.Null); Assert.That(authorizationCode.Client, Is.Not.Null); Assert.That(authorizationCode.ClientId, Is.EqualTo("cid")); Assert.That(authorizationCode.CodeChallenge, Is.EqualTo("CodeChallenge")); Assert.That(authorizationCode.CodeChallengeMethod, Is.EqualTo("CodeChallengeMethod")); Assert.That(authorizationCode.CreationTime, Is.EqualTo(new DateTimeOffset(new DateTime(2016, 1, 1)))); Assert.That(authorizationCode.IsOpenId, Is.True); Assert.That(authorizationCode.Nonce, Is.EqualTo("Nonce")); Assert.That(authorizationCode.RedirectUri, Is.EqualTo("RedirectUri")); Assert.That(authorizationCode.RequestedScopes, Is.Not.Null); Assert.That(authorizationCode.RequestedScopes.Count(), Is.EqualTo(1)); Assert.That(authorizationCode.Scopes, Is.Not.Null); Assert.That(authorizationCode.Scopes.Count(), Is.EqualTo(1)); Assert.That(authorizationCode.SessionId, Is.EqualTo("SessionId")); Assert.That(authorizationCode.WasConsentShown, Is.True); Assert.That(authorizationCode.Subject, Is.Not.Null); }
/// <summary> /// Initializes this instance. /// </summary> /// <returns>The <see cref="Caches"/></returns> private static Entities.Caches Initialize() { var jsonSettingsFactory = new JsonSettingsFactory(incomingMappers); var settings = jsonSettingsFactory.Create(); var authorizationCacheManager = new RedisCacheManager<AuthorizationCode>( ConnectionMultiplexer, Configuration, settings); var authorizationCodeStore = new AuthorizationCodeStore( authorizationCacheManager, Configuration); var clientCacheManager = new RedisCacheManager<Client>( ConnectionMultiplexer, Configuration, settings); var clientCache = new ClientStoreCache( clientCacheManager, Configuration); var refreshTokenCacheManager = new RedisCacheManager<RefreshToken>( ConnectionMultiplexer, Configuration, settings); var refreshTokenStore = new RefreshTokenStore( refreshTokenCacheManager, Configuration); var scopeCacheManager = new RedisCacheManager<IEnumerable<Scope>>( ConnectionMultiplexer, Configuration, settings); var scopesCache = new ScopeStoreCache( scopeCacheManager, Configuration); var redisHandleCacheManager = new RedisCacheManager<Token>( ConnectionMultiplexer, Configuration, settings); var tokenHandleStore = new TokenHandleStore( redisHandleCacheManager, Configuration); var userServiceCacheManager = new RedisCacheManager<IEnumerable<Claim>>( ConnectionMultiplexer, Configuration, settings); var userServiceCache = new UserServiceCache( userServiceCacheManager, Configuration); var caches = new Entities.Caches { AuthorizationCodeStore = authorizationCodeStore, ClientCache = clientCache, RefreshTokenStore = refreshTokenStore, ScopesCache = scopesCache, TokenHandleStore = tokenHandleStore, UserServiceCache = userServiceCache }; return caches; }
public void StoreAsync_WhenCalled_ExpectAction() { // Arrange var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns( new RedisCacheConfigurationEntity { CacheDuration = 10, RedisCacheDefaultPrefix = "DEFAULT", UseObjectCompression = false }); var customMappersConfiguration = new CustomMappersConfiguration { ClientMapper = CustomMapperFactory.CreateClientMapper<CustomClient>() }; var jsonSettingsFactory = new JsonSettingsFactory(customMappersConfiguration); var cacheManager = new RedisCacheManager<Token>( RedisHelpers.ConnectionMultiplexer, mockCacheConfiguration.Object, jsonSettingsFactory.Create()); var tokenStore = new TokenHandleStore( cacheManager, mockCacheConfiguration.Object); var claim1 = new Claim("Type1", "Value1"); var claim2 = new Claim("Type2", "Value2"); var client = new CustomClient { Claims = new List<Claim> { claim1, claim2 } }; var token = new Token { Claims = new List<Claim> { claim1, claim2 }, Client = client, Type = "Type", CreationTime = new DateTimeOffset(new DateTime(2016, 1, 1)), Version = 1, Issuer = "Issuer", Lifetime = 120, Audience = "Audience" }; // Act var stopwatch = Stopwatch.StartNew(); tokenStore.StoreAsync("KeyToStore", token).Wait(); stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); var redisValue = RedisHelpers.ConnectionMultiplexer.GetDatabase().StringGet("DEFAULT_THS_KeyToStore"); Assert.That(redisValue.HasValue, Is.True); Console.WriteLine(redisValue); }
public void SetAsync_WhenClaimObjectAndTtlExceeded_ExpectNull() { // arrange const string Key = @"SetAsync_WhenClaimObjectAndTtlExceeded_ExpectNull"; var claim = new Claim("mytype1", "myvalue2"); var claims = new List<Claim> { claim, claim, claim }; var timeSpan = TimeSpan.FromSeconds(5); var mockConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockConfiguration.Setup(r => r.Get).Returns(() => new RedisCacheConfigurationEntity { CacheDuration = 3600, UseObjectCompression = true, RedisCacheDefaultPrefix = @"RedisCacheManagerTests" }); var mockJsonSettingsFactory = new Mock<IJsonSettingsFactory>(); // act var redisCacheManager = new RedisCacheManager<IEnumerable<Claim>>( RedisHelpers.ConnectionMultiplexer, mockConfiguration.Object, new JsonSerializerSettings()); redisCacheManager.SetAsync(Key, claims, timeSpan).Wait(); /*Wait 6 seconds for expiry*/ Task.Delay(6000).Wait(); var result = redisCacheManager.GetAsync(Key).Result; // assert Console.WriteLine(@"Fetched From Cache:{0}", JsonConvert.SerializeObject(result)); Assert.That(result == null); }
public void SetAsync_WhenClientObject_ExpectSuccess() { // arrange const string Key = @"SetAsync_WhenClientObject_ExpectSuccess"; var client = new Client { AllowedScopes = new List<string> { "scope 1", "scope 2" }, Enabled = true }; var timeSpan = TimeSpan.FromSeconds(10); var mockConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockConfiguration.Setup(r => r.Get).Returns(() => new RedisCacheConfigurationEntity { CacheDuration = 3600, UseObjectCompression = true, RedisCacheDefaultPrefix = @"RedisCacheManagerTests" }); var mockJsonSettingsFactory = new Mock<IJsonSettingsFactory>(); // act var redisCacheManager = new RedisCacheManager<Client>( RedisHelpers.ConnectionMultiplexer, mockConfiguration.Object, new JsonSerializerSettings()); redisCacheManager.SetAsync(Key, client, timeSpan).Wait(); var result = redisCacheManager.GetAsync(Key).Result; // assert Console.WriteLine(@"Fetched From Cache:{0}", JsonConvert.SerializeObject(result)); Assert.That(result.GetType() == typeof(Client)); }
public void SetAsync_WhenScopeObject_ExpectSuccess() { // arrange const string Key = @"SetAsync_WhenScopeObject_ExpectSuccess"; var scope = new Scope { Claims = new List<ScopeClaim> { new ScopeClaim(@"fdf") } }; var scopes = new List<Scope> { scope, scope, scope }; var timeSpan = TimeSpan.FromSeconds(10); var mockConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockConfiguration.Setup(r => r.Get).Returns(() => new RedisCacheConfigurationEntity { CacheDuration = 3600, UseObjectCompression = true, RedisCacheDefaultPrefix = @"RedisCacheManagerTests" }); var mockJsonSettingsFactory = new Mock<IJsonSettingsFactory>(); // act var redisCacheManager = new RedisCacheManager<IEnumerable<Scope>>( RedisHelpers.ConnectionMultiplexer, mockConfiguration.Object, new JsonSerializerSettings()); redisCacheManager.SetAsync(Key, scopes, timeSpan).Wait(); var result = redisCacheManager.GetAsync(Key).Result; // assert Console.WriteLine(@"Fetched From Cache:{0}", JsonConvert.SerializeObject(result)); Assert.That(result.GetType() == typeof(List<Scope>)); }
public void SetAsync_WhenClaimObject_ExpectSuccess() { // arrange const string Key = @"SetAsync_WhenClaimObject_ExpectSuccess"; var claim = new Claim("mytype1", "myvalue2"); var claims = new List<Claim> { claim, claim, claim }; var timeSpan = TimeSpan.FromSeconds(10); var mockConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockConfiguration.Setup(r => r.Get) .Returns( () => new RedisCacheConfigurationEntity { CacheDuration = 3600, UseObjectCompression = true, RedisCacheDefaultPrefix = @"RedisCacheManagerTests" }); var jsonSettingsFactory = new JsonSettingsFactory(new CustomMappersConfiguration()); // act var redisCacheManager = new RedisCacheManager<IEnumerable<Claim>>( RedisHelpers.ConnectionMultiplexer, mockConfiguration.Object, jsonSettingsFactory.Create()); redisCacheManager.SetAsync(Key, claims, timeSpan).Wait(); var result = redisCacheManager.GetAsync(Key).Result.ToList(); // assert Console.WriteLine(@"Fetched From Cache:{0}", JsonConvert.SerializeObject(result)); Assert.That(result.GetType(), Is.EqualTo(typeof(List<Claim>))); }
public void RemoveAsync_WhenCalled_ExpectAction() { // Arrange var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns( new RedisCacheConfigurationEntity { CacheDuration = 10, RedisCacheDefaultPrefix = "DEFAULT", UseObjectCompression = false }); var jsonSettingsFactory = new JsonSettingsFactory(new CustomMappersConfiguration()); var cacheManager = new RedisCacheManager<RefreshToken>( RedisHelpers.ConnectionMultiplexer, mockCacheConfiguration.Object, jsonSettingsFactory.Create()); var refreshTokenStore = new RefreshTokenStore( cacheManager, mockCacheConfiguration.Object); // Act var stopwatch = Stopwatch.StartNew(); refreshTokenStore.RemoveAsync("Delete").Wait(); stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); var redisValue = RedisHelpers.ConnectionMultiplexer.GetDatabase().StringGet("DEFAULT_RTS_Delete"); Assert.That(redisValue.HasValue, Is.False); }
public void StoreAsync_WhenCalled_ExpectAction() { // Arrange var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns( new RedisCacheConfigurationEntity { CacheDuration = 10, RedisCacheDefaultPrefix = "DEFAULT", UseObjectCompression = false }); var jsonSettingsFactory = new JsonSettingsFactory(new CustomMappersConfiguration()); var cacheManager = new RedisCacheManager<RefreshToken>( RedisHelpers.ConnectionMultiplexer, mockCacheConfiguration.Object, jsonSettingsFactory.Create()); var refreshTokenStore = new RefreshTokenStore( cacheManager, mockCacheConfiguration.Object); var refreshToken = new RefreshToken { AccessToken = new Token { Client = new Client { ClientId = "cid", }, Claims = new List<Claim> { new Claim("SubjectId", "sid") } }, CreationTime = new DateTimeOffset(new DateTime(2016, 1, 1)), LifeTime = 1600, Version = 1, }; // Act var stopwatch = Stopwatch.StartNew(); refreshTokenStore.StoreAsync("KeyToStore", refreshToken).Wait(); stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); var redisValue = RedisHelpers.ConnectionMultiplexer.GetDatabase().StringGet("DEFAULT_RTS_KeyToStore"); Assert.That(redisValue.HasValue, Is.True); Console.WriteLine(redisValue); }
public void StoreAsync_WhenCalled_ExpectAction() { // Arrange var mockCacheConfiguration = new Mock<IConfiguration<RedisCacheConfigurationEntity>>(); mockCacheConfiguration.Setup(r => r.Get).Returns( new RedisCacheConfigurationEntity { CacheDuration = 10, RedisCacheDefaultPrefix = "DEFAULT", UseObjectCompression = false }); var jsonSettingsFactory = new JsonSettingsFactory(new CustomMappersConfiguration()); var cacheManager = new RedisCacheManager<AuthorizationCode>( RedisHelpers.ConnectionMultiplexer, mockCacheConfiguration.Object, jsonSettingsFactory.Create()); var authorizationCodeStore = new AuthorizationCodeStore( cacheManager, mockCacheConfiguration.Object); var subject = new ClaimsPrincipal( new List<ClaimsIdentity> { new ClaimsIdentity( new List<Claim> { new Claim(Constants.ClaimTypes.Subject, "sid") }) }); var code = new AuthorizationCode { Client = new Client { ClientId = "cid" }, RequestedScopes = new List<Scope> { new Scope { Description = "this is description", Enabled = true, Name = "Scope", DisplayName = "Display Name" } }, Subject = subject }; // Act var stopwatch = Stopwatch.StartNew(); authorizationCodeStore.StoreAsync("KeyToStore", code).Wait(); stopwatch.Stop(); // Assert this.WriteTimeElapsed(stopwatch); var redisValue = RedisHelpers.ConnectionMultiplexer.GetDatabase().StringGet("DEFAULT_ACS_KeyToStore"); Assert.That(redisValue.HasValue, Is.True); Console.WriteLine(redisValue); }