public async Task<IHttpActionResult> Get()
        {
            var cache = RedisCache.Connection.GetDatabase();
            var repo = new RedisRepository(cache);

            string owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

            var items = await repo.GetPhotosForUserAsync(owner);
            //Do this so we can get the count
            List<IPhotoModel> typedItems = new List<IPhotoModel>(items);
            
            if(typedItems.Count == 0)
            {
                //Nothing in cache... head off to storage.
                var storageRepo = new StorageRepository(SettingsHelper.LocalStorageConnectionString);
                
                var photos = await storageRepo.GetPhotosFromTableAsync( DAL.Azure.StorageConfig.TableName, owner);
                foreach (var photo in photos)
                {
                    //TODO: Find a MUCH better algorithm than
                    //      iterating every item and calling
                    //      Redis 3 times in a row for each
                    //      item.  This is PAINFUL.
                    await repo.AddPhotoToCachesAsync(photo);
                }
                items = photos;                
            }
            return Ok(items);
        }
        public async Task<IHttpActionResult> GetPhotoModel(string id)
        {
            var cache = RedisCache.Connection.GetDatabase();
            var repo = new RedisRepository(cache);

            //Get a single item from the cache based on its ID
            var photo = await repo.GetPhotoByIDAsync(id);

            if (null == photo)
            {
                //Not in the cache.  Retrieve from storage.
                string connectionString = SettingsHelper.LocalStorageConnectionString;
                string owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
                var storageRepo = new StorageRepository(connectionString);
                photo = await storageRepo.GetPhotoFromTableAsync( DAL.Azure.StorageConfig.PhotosBlobContainerName, owner, id);
                if (null == photo)
                {
                    //Not found in cache or storage.                      
                }
                else
                {                    
                    //Update the cache using the cache aside pattern.
                    await repo.AddPhotoToUserCacheAsync(photo);
                }
            }
            if (null != photo)
            {
                return Ok(photo);
            }
            else
            {
                return NotFound();
            }
        }
        public async Task<IHttpActionResult> Get()
        {
            var cache = RedisCache.Connection.GetDatabase();
            var repo = new RedisRepository(cache);
            var items = await repo.GetAllPhotosAsync();
            
            List<IPhotoModel> typedItems = new List<IPhotoModel>(items);
            if(typedItems.Count == 0)
            {
                //Pull from storage.  This is a cross-partition query,
                //  and will be slower than using Redis.
                var storageConnectionString = SettingsHelper.LocalStorageConnectionString;
                var storageRepo = new StorageRepository(storageConnectionString);
                typedItems = await storageRepo.GetLatestFromTableStorageAsync();
                if(typedItems.Count > 0)
                {
                    foreach (var item in typedItems)
                    {
                        //Add to cache as cache-aside pattern
                        await repo.AddPhotoToAllUsersCacheAsync(item);
                    }
                    items = typedItems;
                }
            }


            return Ok(items);
        }
Example #4
0
 public WeatherForecastController(
     RandomWeatherService weather,
     RedisRepository cache)
 {
     _weather = weather;
     _cache   = cache;
 }
Example #5
0
        public ActionResult RefreshCache()
        {
            //1. Load items from cache
            RedisRepository rr    = new RedisRepository();
            var             items = rr.LoadItems();

            //2. hash the serialized value of items
            PropertyRepository pr = new PropertyRepository();

            pr.MyConnection.Open();
            var itemsFromDb = pr.GetProperty();

            pr.MyConnection.Close();

            if (items == null)
            {
                rr.StoreItems(itemsFromDb);
                return(Content("done"));
            }

            //3. compare the digest produced with the digest produced earlier while stored in application variable
            if (rr.HashValue(JsonConvert.SerializeObject(items)) != rr.HashValue(JsonConvert.SerializeObject(itemsFromDb)))
            {
                //4. if they do not match; storeincache method and re-produce a new hashcode
                rr.StoreItems(itemsFromDb); return(Content("done"));
            }

            return(Content("properties were not updated since they are still the same"));
        }
Example #6
0
        public async Task <IHttpActionResult> Get()
        {
            var cache = RedisCache.Connection.GetDatabase();
            var repo  = new RedisRepository(cache);
            var items = await repo.GetAllPhotosAsync();

            List <IPhotoModel> typedItems = new List <IPhotoModel>(items);

            if (typedItems.Count == 0)
            {
                //Pull from storage.  This is a cross-partition query,
                //  and will be slower than using Redis.
                var storageConnectionString = SettingsHelper.LocalStorageConnectionString;
                var storageRepo             = new StorageRepository(storageConnectionString);
                typedItems = await storageRepo.GetLatestFromTableStorageAsync();

                if (typedItems.Count > 0)
                {
                    foreach (var item in typedItems)
                    {
                        //Add to cache as cache-aside pattern
                        await repo.AddPhotoToAllUsersCacheAsync(item);
                    }
                    items = typedItems;
                }
            }


            return(Ok(items));
        }
Example #7
0
        public ActionResult StoreInRedis()
        {
            PropertyRepository ir = new PropertyRepository();

            try
            {
                if (ir.MyConnection.State == System.Data.ConnectionState.Closed)
                {
                    ir.MyConnection.Open();
                }

                var list = ir.GetProperty();
                //foreach (var item in list)
                //{
                //    var name = ir.GetPropertyName(item.Name);
                //    item.Name = name;
                //}

                RedisRepository rr = new RedisRepository();

                return(View("Index", list));
            }
            catch (Exception ex)
            {
                ViewBag.Error = ex + " - (Error occurred. Items were not deleted)";
                return(View(new List <Property>()));
            }
            finally
            {
                if (ir.MyConnection.State == System.Data.ConnectionState.Open)
                {
                    ir.MyConnection.Close();
                }
            }
        }
Example #8
0
 internal static async Task SaveToRedisAsync(PhotoModel p, TextWriter log)
 {
     //Use repository to add to all caches
     IDatabase       cache = RedisCache.Connection.GetDatabase();
     RedisRepository repo  = new RedisRepository(cache);
     await repo.AddPhotoToCachesAsync(p);
 }
Example #9
0
        private void btnSearch_Click(object sender, EventArgs e)
        {
            var key = this.txtKey.Text.Trim();
            if (string.IsNullOrEmpty(key))
            {
                MessageBox.Show("请输入key值");
                return;
            }

            try
            {
                using (var redis = new RedisRepository())
                {
                    var keys = redis.SearchKeys(key);
                    if (!keys.Any())
                    {
                        MessageBox.Show("暂无结果!");
                        return;
                    }

                    foreach (var item in keys)
                    {
                        this.lstResult.Items.Add(item);
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("查询失败!");
            }
        }
Example #10
0
        private void btnClear_Click(object sender, EventArgs e)
        {
            var key = this.txtKey.Text.Trim();
            if (string.IsNullOrEmpty(key))
            {
                MessageBox.Show("请输入key值");
                return;
            }

            if (MessageBox.Show("确定要删除?", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK)
            {
                return;
            }

            try
            {
                using (var redis = new RedisRepository())
                {
                    var keys = redis.SearchKeys(key);
                    if (!keys.Any())
                    {
                        MessageBox.Show("暂无结果!");
                        return;
                    }
                    redis.DelKeys(keys);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("删除失败!");
            }

            MessageBox.Show("删除成功!");
        }
Example #11
0
        public async Task <IHttpActionResult> GetPhotoModel(string id)
        {
            var cache = RedisCache.Connection.GetDatabase();
            var repo  = new RedisRepository(cache);

            //Get a single item from the cache based on its ID
            var photo = await repo.GetPhotoByIDAsync(id);

            if (null == photo)
            {
                //Not in the cache.  Retrieve from storage.
                string connectionString = SettingsHelper.LocalStorageConnectionString;
                string owner            = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
                var    storageRepo      = new StorageRepository(connectionString);
                photo = await storageRepo.GetPhotoFromTableAsync(DAL.Azure.StorageConfig.PhotosBlobContainerName, owner, id);

                if (null == photo)
                {
                    //Not found in cache or storage.
                }
                else
                {
                    //Update the cache using the cache aside pattern.
                    await repo.AddPhotoToUserCacheAsync(photo);
                }
            }
            if (null != photo)
            {
                return(Ok(photo));
            }
            else
            {
                return(NotFound());
            }
        }
Example #12
0
 public AccountController(IConfiguration configuration, RedisRepository redisRepository)
 {
     _securityServices = new SecurityServices(configuration);
     _databaseServices = new DatabaseServices(configuration);
     _dataServices     = new DataServices();
     _redisRepository  = redisRepository;
 }
Example #13
0
        public async Task <IHttpActionResult> Get()
        {
            var cache = RedisCache.Connection.GetDatabase();
            var repo  = new RedisRepository(cache);

            string owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;

            var items = await repo.GetPhotosForUserAsync(owner);

            //Do this so we can get the count
            List <IPhotoModel> typedItems = new List <IPhotoModel>(items);

            if (typedItems.Count == 0)
            {
                //Nothing in cache... head off to storage.
                var storageRepo = new StorageRepository(SettingsHelper.LocalStorageConnectionString);

                var photos = await storageRepo.GetPhotosFromTableAsync(DAL.Azure.StorageConfig.TableName, owner);

                foreach (var photo in photos)
                {
                    //TODO: Find a MUCH better algorithm than
                    //      iterating every item and calling
                    //      Redis 3 times in a row for each
                    //      item.  This is PAINFUL.
                    await repo.AddPhotoToCachesAsync(photo);
                }
                items = photos;
            }
            return(Ok(items));
        }
Example #14
0
        internal static async Task SaveToRedisAsync(PhotoModel p, TextWriter log)
        {
            //Use repository to add to all caches
            IDatabase cache = RedisCache.Connection.GetDatabase();
            RedisRepository repo = new RedisRepository(cache);
            await repo.AddPhotoToCachesAsync(p);

        }
        public void TestTable()
        {
            string[] actualResult = null;
            var      sut          = new RedisRepository();

            Assert.DoesNotThrowAsync(async() => actualResult = await sut.TestTable("user:1"));

            Assert.AreEqual(4, actualResult.Length);
        }
        public void TestConvert()
        {
            var actualResult = 0;
            var sut          = new RedisRepository();

            Assert.DoesNotThrowAsync(async() => actualResult = await sut.ConvertTest("foo", 1));

            Assert.AreEqual(111, actualResult);
        }
Example #17
0
        /// <summary>
        /// Clears the user cache
        /// </summary>
        /// <returns>200 OK</returns>
        public async Task <IHttpActionResult> Delete(string id)
        {
            var    cache = RedisCache.Connection.GetDatabase();
            var    repo  = new RedisRepository(cache);
            string owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            await repo.ClearUserCacheAsync(owner);

            return(Ok());
        }
Example #18
0
        /// <summary>
        /// Clears the entire user cache
        /// </summary>
        /// <returns>200 OK</returns>
        public async Task <IHttpActionResult> Delete()
        {
            var cache = RedisCache.Connection.GetDatabase();
            var repo  = new RedisRepository(cache);

            await repo.ClearAllUsersCacheAsync();

            return(Ok());
        }
Example #19
0
 public CodeController(RedisRepository redisRepository, SmsService smsService, IConfiguration iConfiguration, MongoRepository mongoRepository)
 {
     _redisRepository = redisRepository;
     _smsService      = smsService;
     _mongoRepository = mongoRepository;
     _isDebug         = iConfiguration["IsDebug"].TryBool();
     _defaultCode     = iConfiguration["DefaultCode"];
     _ipLimitCount    = iConfiguration["IpLimitCount"].TryInt(10);
 }
Example #20
0
        public CustomControllerCache()
        {
            UnitOfWork           = new UnitOfWorkCQRS(new EscarGoContext());
            QueueRepositoryAsync = new QueueRepositoryAsync();
            ITableStorageRepository tablestorageRepository = new TableStorageRepository();
            IRedisRepository        redisRepository        = new RedisRepository(tablestorageRepository);

            Builder            = new ViewModelBuilderQueue(UnitOfWork, redisRepository);
            TicketModelBuilder = new TicketModelBuilderCache(UnitOfWork, QueueRepositoryAsync);
        }
Example #21
0
 public ReactionService(
     IActivityStreamRepository activityStream,
     RedisRepository redis,
     IActivityStreamContentRepository activityContent,
     IRateLimitService rateLimitService)
 {
     _activityStream   = activityStream;
     _redis            = redis;
     _activityContent  = activityContent;
     _rateLimitService = rateLimitService;
 }
Example #22
0
 public BindSqlReferencesToActivityStreamWhenReading(
     RedisRepository redis,
     StringRepository strings,
     SimpleDbContext db,
     IActivityStreamContentRepository contentRepository)
 {
     _redis             = redis;
     _strings           = strings;
     _db                = db;
     _contentRepository = contentRepository;
 }
        public void InsertUserShouldCorrect()
        {
            var user = new UserEntity
            {
                Id = 1, Code = "Admin", Password = "******", IsActive = true
            };

            var sut = new RedisRepository();

            Assert.DoesNotThrowAsync(async() => await sut.InsertUser(user));
        }
        public RedisRepositoryTests()
        {
            _logger = new LoggerConfiguration()
                      .MinimumLevel.Verbose()
                      .WriteTo.Console()
                      .WriteTo.InMemory()
                      .CreateLogger();
            ConnectionMultiplexer muxer = ConnectionMultiplexer.Connect("192.168.99.100:6379");

            _conection       = muxer.GetDatabase();
            _redisRepository = new RedisRepository(_logger, _conection);
        }
Example #25
0
        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    _repository = null;
                }

                disposed = true;
            }
        }
Example #26
0
        public void TestGet_GivenMyKey_ShouldReturnHello()
        {
            //---------------Set up test pack-------------------

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            var testRepo   = new RedisRepository(_redisContext);
            var testObject = testRepo.GetById("mykey");

            //---------------Test Result -----------------------
            Assert.AreEqual("Hello", testObject.Value);
        }
Example #27
0
 public HandlerWhenWritingPipe(
     IObjectReferenceService ids,
     IObjectReferenceService handles,
     StringRepository strings,
     ITagService tags,
     RedisRepository redis)
 {
     _ids     = ids;
     _handles = handles;
     _strings = strings;
     _tags    = tags;
     _redis   = redis;
 }
        public void TestSet()
        {
            var redisRepository = new RedisRepository(_connectionMultiplexer);

            redisRepository.Set("a1", new A {
                X = 1, Y = 2
            });

            var a = redisRepository.Get <A>("a1");

            Assert.AreEqual(1, a.X);
            Assert.AreEqual(2, a.Y);
        }
        public async Task <Contest> GetContestById(int id)
        {
            var contest = await RedisRepository.Get <Contest>(ContestsKey + id);

            if (contest != null)
            {
                return(contest);
            }
            contest = await Db.Contests.Where(c => c.Id == id).FirstOrDefaultAsync();

            await RedisRepository.Add(ContestsKey + id, contest);

            return(contest);
        }
        public async Task <IEnumerable <Contest> > GetAllContests()
        {
            var contests = await RedisRepository.Get <IEnumerable <Contest> >(ContestsKey);

            if (contests != null)
            {
                return(contests);
            }
            contests = await Db.Contests.ToListAsync();

            await RedisRepository.Add(ContestsKey, contests);

            return(contests);
        }
Example #31
0
 public OutboxActivityActionHandlerWhenWritingPipe(
     IObjectReferenceService ids,
     IObjectReferenceService handles,
     StringRepository strings,
     ITagService tags,
     RedisRepository redis,
     IRateLimitService rateLimitService)
 {
     _ids              = ids;
     _handles          = handles;
     _strings          = strings;
     _tags             = tags;
     _redis            = redis;
     _rateLimitService = rateLimitService;
 }
Example #32
0
        public void TestRepoVsDataSources()
        {
            var productId = 13860428;
            var redisRepo = new RedisRepository();
            var redSky    = new RedSkyApi();
            var redis     = new RedisDB();

            var redSkyData = redSky.GetNonPriceDataById(productId);
            var repoData   = redisRepo.GetProductById(productId);
            var redisData  = redis.GetPriceData(productId);

            Assert.AreEqual(repoData.name, redSkyData.name);
            Assert.AreEqual(repoData.id, redSkyData.id);
            Assert.AreEqual(repoData.current_price.value, redisData.value);
            Assert.AreEqual(repoData.current_price.currency_code, redisData.currency_code);
        }
Example #33
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var requireAuthorizePolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidIssuer              = Configuration["TokenOptions:Issuer"],
                    ValidAudience            = Configuration["TokenOptions:Audience"],
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["TokenOptions:SecurityKey"]))
                };
            });


            services.AddHttpContextAccessor();
            services.AddScoped <ISharedIdentityService, SharedIdentityService>();
            services.AddScoped <IBasketService, BasketService>();

            services.Configure <RedisSettings>(Configuration.GetSection("RedisSettings"));
            services.AddSingleton <RedisRepository>(sp =>
            {
                var redisSettings = sp.GetRequiredService <IOptions <RedisSettings> >().Value;

                var redis = new RedisRepository(redisSettings.Host, redisSettings.Port);

                redis.Connect();

                return(redis);
            });

            services.AddControllers(opt =>
            {
                opt.Filters.Add(new AuthorizeFilter(requireAuthorizePolicy));
            });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Course.Services.Basket", Version = "v1"
                });
            });
        }
Example #34
0
        public ActionResult Index()
        {
            PropertyRepository pr = new PropertyRepository();

            try
            {
                //1. Load items from cache
                RedisRepository rr    = new RedisRepository();
                var             items = rr.LoadItems();

                //2. hash the serialized value of items
                pr.MyConnection.Open();
                var itemsFromDb = pr.GetProperty();
                pr.MyConnection.Close();

                if (items == null)
                {
                    rr.StoreItems(itemsFromDb);
                    items = rr.LoadItems();
                }

                //3. compare the digest produced with the digest produced earlier while stored in application variable
                if (rr.HashValue(JsonConvert.SerializeObject(items)) != rr.HashValue(JsonConvert.SerializeObject(itemsFromDb)))
                {
                    //4. if they do not match
                    //storeincache method and re-produce a new hashcode
                    rr.StoreItems(itemsFromDb);
                    items = rr.LoadItems();
                }

                return(View(items));
            }
            catch (Exception ex)
            {
                LoggingRepository.ReportError(ex);
                ViewBag.Error = ex + " - (Error occurred while querying items)";
                return(View(new List <Property>()));
            }
            finally
            {
                if (pr.MyConnection.State == System.Data.ConnectionState.Open)
                {
                    pr.MyConnection.Close();
                }
            }
        }
Example #35
0
        static void Main(string[] args)
        {
            IConfiguration config = new ConfigurationBuilder().
                                    SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "AppSettings"))
                                    .AddJsonFile(ConfigFileName)
                                    .Build();
            //Create the redis factory - substitute any factory in this place
            IRedisCacheFactory redisFactory = new RedisCacheFactory(config);
            //Create the cosmos factory
            ICosmosFactory cosmosFactory = new CosmosFactory(config);
            //Create the redis store instance
            IRedisRepository redisStore = new RedisRepository(redisFactory);
            //Create the cosmos store instance
            ICosmosRepository cosmosStore = new SqlCosmosRepository(cosmosFactory);
            //create the write-through cache strategy

            /*ICacheStrategy cacheStrategy = new WriteThroughCache(redisStore, cosmosStore);
             * //create an instance of the test execution class
             * var cacheOperationsTest = new ExecuteCacheStrategy(cacheStrategy);*/

            // Read Values from command line or read data from file
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="userDTO"></param>
        /// <returns></returns>
        public OperationResult Login(UserDTO userDTO)
        {
            OperationResult result = new OperationResult();

            if (!string.IsNullOrWhiteSpace(userDTO.EmailAddress) || !string.IsNullOrWhiteSpace(userDTO.Password))
            {
                result.Success = false;
                result.Messages.Add("请填写用户名和密码");
                result.Code = ((int)RequestFailCode.ParametersMissing).ToString();
            }

            var user = _userDomainService.GetUser(userDTO.EmailAddress, userDTO.Password);

            if (user == null)
            {
                result.Success = false;
                result.Messages.Add("用户名或密码不正确");
                result.Code = ((int)RequestFailCode.PasswordError).ToString();
                return(result);
            }

            //如果存在的化,保存到Redis
            var tokenModel = new TokenDTO()
            {
                TokenId        = GuidUtility.GetGuid(),
                UserId         = user.Id,
                ExpiredDate    = DateTime.Now.AddSeconds(3600),
                RefreshTokenId = GuidUtility.GetGuid()
            };

            RedisRepository.SaveUserToken(tokenModel);

            result.Success = true;
            result.Data    = tokenModel;

            return(result);
        }
        /// <summary>
        /// Clears the entire user cache
        /// </summary>
        /// <returns>200 OK</returns>
        public async Task<IHttpActionResult> Delete()
        {
            var cache = RedisCache.Connection.GetDatabase();
            var repo = new RedisRepository(cache);

            await repo.ClearAllUsersCacheAsync();
            
            return Ok();
        }
 /// <summary>
 /// Clears the user cache
 /// </summary>
 /// <returns>200 OK</returns>
 public async Task<IHttpActionResult> Delete(string id)
 {
     var cache = RedisCache.Connection.GetDatabase();
     var repo = new RedisRepository(cache);
     string owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
     await repo.ClearUserCacheAsync(owner);
     return Ok();
 }