Ejemplo n.º 1
0
        public void GetSetNoOptionsRedisTest()
        {
            var testClass = new MyClass()
            {
                Name = "Ali Alp",
                Age  = 38
            };

            _redisService.Set(testClass.Name, testClass);

            var result = _redisService.Get <MyClass>(testClass.Name);

            Assert.Equal(testClass.Name, result.Name);
            Assert.Equal(testClass.Age, result.Age);

            Task.Delay(5100).GetAwaiter().GetResult();


            var result2 = _redisService.Get <MyClass>(testClass.Name);

            Assert.Equal(testClass.Name, result2.Name);
            Assert.Equal(testClass.Age, result2.Age);

            _redisService.RemoveAsync(testClass.Name);
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> GetBoard(Guid boardId)
        {
            var board = await _redisService.Get <Board>(boardId.ToString());

            if (board != null)
            {
                return(Ok(board));
            }
            return(NotFound("Unable to get board for request " + boardId.ToString()));
        }
Ejemplo n.º 3
0
        public DataStatus GenerateDataModel(string username)
        {
            if (string.IsNullOrEmpty(username) || string.IsNullOrWhiteSpace(username))
            {
                throw new ArgumentNullException();
            }

            string customerDataPullStatusDateKey = Keys.CustomerDataPullStatusDate(username);
            string customerDataPullStatusKey     = Keys.CustomerDataPullStatus(username);

            if (!_redisService.KeyExists(customerDataPullStatusDateKey) && !_redisService.KeyExists(customerDataPullStatusKey))
            {
                _redisService.Add(customerDataPullStatusDateKey, DateTime.Now.ToString("d"));
                _redisService.Add(customerDataPullStatusKey, DataPullStatusValue.Idle.ToString());
            }

            string customerDataPullStatus = _redisService.Get <string>(customerDataPullStatusKey);

            if (customerDataPullStatus == DataPullStatusValue.InProgress.ToString() || customerDataPullStatus == DataPullStatusValue.Ready.ToString())
            {
                return(GetStatus(username));
            }

            Task.Run(() =>
            {
                _redisService.Add(customerDataPullStatusKey, DataPullStatusValue.InProgress.ToString());

                var stats  = ChessComClient.GetStats(username);
                var months = ChessComClient.GetMonthlyStats(username);

                _completeArchive = new Dictionary <string, MonthGames>();

                foreach (var monthArchive in months.Archives)
                {
                    var games  = ChessComClient.GetMonthlyGames(monthArchive.AbsoluteUri);
                    var month  = int.Parse(monthArchive.Segments[6]);
                    var year   = int.Parse(monthArchive.Segments[5].Split('/').First());
                    var yyyyMM = new DateTime(year, month, 1).ToString("yyyyMM");

                    _completeArchive.Add(yyyyMM, games);
                    _redisService.Add(Keys.MonthlyNumberOfGames(username, yyyyMM), games.Games.Count);

                    foreach (var game in games.Games)
                    {
                        var gameKey = Keys.Game(username, yyyyMM, game.Url.ToString());
                        _redisService.SortedSetAdd(Keys.MonthlyGames(username, yyyyMM), gameKey, yyyyMM);
                        _redisService.Add(gameKey, game);
                    }
                }

                _redisService.Add(customerDataPullStatusKey, DataPullStatusValue.Ready.ToString());
            });

            return(GetStatus(username));
        }
Ejemplo n.º 4
0
        public IActionResult VideoSearch(string key, string index)
        {
            key = key.Trim();
            if (string.IsNullOrEmpty(key))
            {
                return(Redirect("/video"));
            }
            int.TryParse(index, out int currentIndex);
            currentIndex = currentIndex < 1 ? 1 : currentIndex;
            var pageSize = 10;

            var searchKey    = $"VideoSearch_{key}_{currentIndex}";
            var searchResult = _redisService.Get <VideoSearchResult>(searchKey);

            if (searchResult == null)
            {
                long totalCount = 0;
                searchResult = new VideoSearchResult()
                {
                    PageIndex = currentIndex, PageSize = pageSize
                };
                var result = _videoService.SearchVideo(key, currentIndex, pageSize, out totalCount);
                searchResult.Result     = result;
                searchResult.TotalCount = totalCount;
                searchResult.Key        = key;
                if (result != null && result.Count > 0)
                {
                    _redisService.Set(searchKey, searchResult, 10);
                }
            }
            ViewData["VideoSearchResult"] = searchResult;

            //总榜
            var totalRankingKey = "VideoSearch_TotalRankingKey";

            if (!_memoryCache.TryGetValue(totalRankingKey, out List <VideoRank> totalRankingList))
            {
                totalRankingList = new List <VideoRank>();
                var totalRanking = _videoRankingService.GetTotalRanking(1, 20);
                var rankingList  = _videoService.GetVideoList(totalRanking.Select(x => Convert.ToInt64(x.Key)));
                totalRanking.ForEach(item =>
                {
                    var totalRankingItem = rankingList.FirstOrDefault(x => x.Id == Convert.ToInt64(item.Key));
                    if (totalRankingItem != null)
                    {
                        totalRankingList.Add(ConvertVideoToVideoRank(totalRankingItem, item.Value));
                    }
                });
                _memoryCache.Set(totalRankingKey, totalRankingList, new DateTimeOffset(DateTime.Now.AddHours(1)));//1小时
            }
            ViewData["VideoSearch_TotalRanking"] = totalRankingList;
            return(View());
        }
Ejemplo n.º 5
0
        public async Task Handle(DiscordMessageEvent notification, CancellationToken cancellationToken)
        {
            var message = notification.Content;

            if (notification.IsBot)
            {
                return;
            }

            if (message != "!stats")
            {
                return;
            }

            if (!notification.InGuild)
            {
                return;
            }

            var total = await _redis.Get <long>("connected_client_count");

            var toSend = $"There are currently {total} clients online.";
            var client = await _provider.Get();

            var task = client?.GetGuild(notification.GuildId)?.GetTextChannel(notification.ChannelId)?.SendMessageAsync(toSend);

            if (task != null)
            {
                await task;
            }
        }
        public async Task <RequestTokenResponse> FidectusGetAuthenticationToken(RequestTokenRequest requestTokenRequest, IFidectusConfiguration fidectusConfiguration)
        {
            var requestTokenResponse = await redisService.Get <FidectusAuthenticationToken>(RedisConstants.FidectusAuthenticationTokenKey, requestTokenRequest.ClientId);

            if (!string.IsNullOrWhiteSpace(requestTokenResponse?.AccessToken))
            {
                logger.LogInformation("Reusing cached Fidectus access token...");

                return(new RequestTokenResponse
                {
                    AccessToken = requestTokenResponse.AccessToken,
                    IsSuccessStatusCode = true
                });
            }

            logger.LogInformation("Getting new Fidectus access token...");

            var httpClient = httpClientFactory.CreateClient();

            httpClient.BaseAddress = new Uri(fidectusConfiguration.FidectusAuthUrl);

            var getAuthenticationToken = await PostAsync <RequestTokenRequest, RequestTokenResponse>(httpClient, fidectusConfiguration.FidectusAuthUrl, requestTokenRequest);

            var fidectusAuthenticationToken = new FidectusAuthenticationToken {
                AccessToken = getAuthenticationToken.AccessToken
            };

            await redisService.Set(fidectusAuthenticationToken, 24, RedisConstants.FidectusAuthenticationTokenKey, requestTokenRequest.ClientId);

            logger.LogInformation("New Fidectus access token cached");

            return(getAuthenticationToken);
        }
Ejemplo n.º 7
0
        public void IncrementTestWithExpiry(float first, float second, float expected, int milliSecond)
        {
            var keyName = KeyName();

            _redisService.Remove(keyName);
            _redisService.SetString(keyName, Convert.ToString(first, CultureInfo.InvariantCulture),
                                    TimeSpan.FromMilliseconds(milliSecond));
            var result = _redisService.IncrementString(keyName, second);

            Assert.Equal(expected, result);

            Task.Delay(milliSecond + 1000).GetAwaiter().GetResult();
            var resultAfterDelay = _redisService.Get <string>(keyName);

            Assert.Null(resultAfterDelay);

            _redisService.Remove(keyName);
        }
        private async void OnMessage(object sender, string name, object data)
        {
            var dict    = (Dictionary <string, object>)(data);
            var json    = JsonConvert.SerializeObject(dict, Formatting.Indented);
            var message = JsonConvert.DeserializeObject <EventMessage>(json, new JsonSerializerSettings
            {
                NullValueHandling     = NullValueHandling.Ignore,
                MissingMemberHandling = MissingMemberHandling.Ignore
            });

            if (message == null || message.name == "ADSB_TRACK")
            {
                return;
            }

            var dataObj = message.data.FirstOrDefault();

            if (dataObj == null || dataObj.alertType == "OUTSIDE_OPERATION" || dataObj.alertType == "NO_OPERATION")
            {
                return;
            }

            var key           = $"{dataObj.subject.uniqueIdentifier}-{dataObj.relatedSubject.uniqueIdentifier}-alert";
            var cachedProcess = await _redisService.Get <State>(key);

            var process = new Process();

            if (cachedProcess != null)
            {
                process.CurrentState = cachedProcess.CurrentState;
            }
            else
            {
                cachedProcess = new State();
            }

            if (!cachedProcess.Triggered && !cachedProcess.Handled)
            {
                if (dataObj.alertType == "UAS_NOFLYZONE")
                {
                    await SendAlert(new Alert { droneId = dataObj.subject.uniqueIdentifier, type = "no-fly-zone-alert", reason = "Out of Bounds" });

                    cachedProcess.Triggered = true;
                }

                if (dataObj.alertType == "UAS_COLLISION")
                {
                    await SendAlert(new Alert { droneId = dataObj.subject.uniqueIdentifier, type = "collision-alert", reason = "Collision" });

                    cachedProcess.Triggered = true;
                }
            }
            cachedProcess.CurrentState = process.CurrentState;
            await _redisService.Set(key, cachedProcess);
        }
Ejemplo n.º 9
0
        public async Task <StockResponseModel> Handle(GetStockQuery request, CancellationToken cancellationToken)
        {
            var responseModel = new StockResponseModel();
            var stockModel    = _redisService.Get <StockModel>($"stock:{request.Id}");

            if (stockModel != null)
            {
                responseModel = _mapper.Map <StockResponseModel>(stockModel);
            }
            return(responseModel);
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> PostAsync(HandleAlertResource resource)
        {
            var key = $"{resource.UasOperation}-{resource.DroneID}-{resource.AlertType}";

            var cachedProcess = await _redisService.Get <State>(key);

            cachedProcess.Handled = true;

            await _redisService.Set(key, cachedProcess);

            return(Ok());
        }
Ejemplo n.º 11
0
        public async Task <JsonResult> Index()
        {
            var lResult = mRedisService.Get <List <UserProfile> >("UserInfo");

            if (lResult == null)
            {
                var lUser = mUserService.GetList();
                await mRedisService.SetAsync("UserInfo", lUser, 60);

                lResult = lUser;
            }
            return(new JsonResult(lResult));
        }
Ejemplo n.º 12
0
        public async Task <string> Handle(ConvertCognitoJwtCommand request, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(request.CognitoJwt))
            {
                return(null);
            }
            var key = $"jwt-mapping-{request.CognitoJwt}";
            // Fallback to support legacy aws cognito tokens.
            var userId = await _redis.Get <int?>(key);

            if (!userId.HasValue)
            {
                try
                {
                    var email = await _mediator.Send(new CognitoDecodeTokenCommand { Token = request.CognitoJwt },
                                                     cancellationToken);

                    var user = await _mediator.Send(new GetUserByEmailQuery { Email = email }, cancellationToken);

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

                    userId = user.Id;
                    await _redis.Set(key, user.Id, TimeSpan.FromHours(24));
                }
                catch (Exception e)
                {
                    _logger.LogError(e, request.CognitoJwt);
                    return(null);
                }
            }

            var userById = await _mediator.Send(
                new GetUserByIdQuery { Id = userId.Value, IncludeGroups = true, AllowCached = request.AllowCachedUser },
                cancellationToken);

            var payload = await _mediator.Send(new GetSignInPayloadQuery { User = userById }, cancellationToken);

            var token = await _mediator.Send(new UserCreateSignInJwtCommand { Payload = payload }, cancellationToken);

            return(token.Token);
        }
Ejemplo n.º 13
0
        public async Task WeatherCheck(UTMService utmService)
        {
            List <Flight> flights = await utmService.Operation.GetFlightsInAllOperationsAsync();

            var distinctFlights = flights?.GroupBy(flight => flight.uas.uniqueIdentifier).Select(uas => uas.First()).ToList();

            distinctFlights?.ForEach(async flight =>
            {
                var flightCoordinates = flight.coordinate;
                var weatherResponse   = await _weatherService.GetWeatherAtCoord(latitude: flightCoordinates.latitude.ToString(), longitude: flightCoordinates.longitude.ToString());
                var process           = new Process();
                var key           = $"{flight.uasOperation}-{flight.uas.uniqueIdentifier}-weather";
                var cachedProcess = await _redisService.Get <State>(key);
                if (cachedProcess != null)
                {
                    process.CurrentState = cachedProcess.CurrentState;
                }
                else
                {
                    cachedProcess = new State();
                }

                var validatedRule = _weatherRule.ValidateRule(weatherResponse);
                if (!validatedRule.Success && (process.CurrentState == ProcessState.Active || process.CurrentState == ProcessState.Inactive))
                {
                    process.MoveNext();
                }
                else
                {
                    process.MovePrev();
                }

                if (process.CurrentState == ProcessState.Raised && !cachedProcess.Triggered && !cachedProcess.Handled)
                {
                    cachedProcess.Triggered = true;
                    await SendAlert(new Alert {
                        droneId = flight.uas.uniqueIdentifier, type = "weather-alert", reason = validatedRule.Message
                    });
                }
                cachedProcess.CurrentState = process.CurrentState;
                await _redisService.Set(key, cachedProcess);
            });
        }
Ejemplo n.º 14
0
        public ActionResult <ItemResponse <string> > GetRedis()
        {
            ItemResponse <string> response = null;
            ActionResult          result   = null;

            try
            {
                string pair = _redisService.Get("foo");

                response      = new ItemResponse <string>();
                response.Item = pair;
                result        = Ok200(response);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex.ToString());
                result = StatusCode(500, new ErrorResponse(ex.Message.ToString()));
            }
            return(result);
        }
Ejemplo n.º 15
0
        public async Task <List <GithubRepository> > Get_Github_Repository(User user, IRedisService _SRedisService)
        {
            List <GithubRepository> rtn = null;
            string json = await _SRedisService.Get((int)enumRedis.repository, user.id.ToString());

            if (json == null)
            {
                rtn = Get_Github_Repository(user.github_username);
                bool isOk = await _SRedisService.Set((int)enumRedis.repository, user.id.ToString(), JsonConvert.SerializeObject(rtn), DateTime.Now.AddHours(1));

                if (!isOk)
                {
                    throw new Exception("Redis'e İlgili Değer Yazılamadı");
                }
            }
            else
            {
                rtn = JsonConvert.DeserializeObject <List <GithubRepository> >(json);
            }
            return(rtn);
        }
Ejemplo n.º 16
0
 /// <summary>
 ///     key
 /// </summary>
 /// <param name="key"></param>
 /// <returns></returns>
 public string Get(string key)
 {
     return(_redisService.Get(key));
 }
Ejemplo n.º 17
0
 public Task <string> Fetch(string key)
 {
     return(_redis.Get <string>(key));
 }
Ejemplo n.º 18
0
 public async Task <IActionResult> Connected()
 {
     return(Ok(await _redis.Get <long>("connected_client_count")));
 }
Ejemplo n.º 19
0
        public ActionResult GetVote()
        {
            Vote vote = _redisService.Get(_redisKey);

            return(new JsonCamelCaseResult(vote, JsonRequestBehavior.AllowGet));
        }