Exemplo n.º 1
0
        public void SerializeObjects(int iterations)
        {
            ResetStopwatch("String Serialize");
            ResetStopwatch("String Deserialize");

            SimpleObject simple;

            for (int i = 0; i < iterations; i++)
            {
                simple = new SimpleObject()
                {
                    MyString = "Hello Franz", MyValue = i
                };

                StartStopwatch("String Serialize");
                DistributedCache.Insert("SerializationPerformanceTest" + i, simple, DateTime.UtcNow.AddSeconds(60));
                StopStopwatch("String Serialize");
            }

            for (int i = 0; i < iterations; i++)
            {
                StartStopwatch("String Deserialize");
                simple = DistributedCache.Get <SimpleObject>("SerializationPerformanceTest" + i);
                StopStopwatch("String Deserialize");

                Assert.IsNotNull(simple);
                Assert.AreEqual(simple.MyValue, i);
                Assert.AreEqual(simple.MyString, "Hello Franz");
            }

            StopAndTraceStopwatch("String Serialize");
            StopAndTraceStopwatch("String Deserialize");
        }
Exemplo n.º 2
0
        public void ValueTest()
        {
            int x = 123;

            DistributedCache.Insert("ValueTest", x, DateTime.UtcNow.AddSeconds(30));
            int y = DistributedCache.Get <int>("ValueTest");
        }
 public void DistributedCache_Get_ThrowsExceptionIfNoDistributedCacheProviderIsRegistered()
 {
     using (new MunqContext())
     {
         var exception = Assert.Throws <KeyNotFoundException>(() => DistributedCache.Get <object>("x"));
         Assert.Contains(typeof(IDistributedCache).Name, exception.Message);
     }
 }
Exemplo n.º 4
0
        public void ObjectTest()
        {
            SimpleProtoObject simple = new SimpleProtoObject()
            {
                MyString = "Hello Franz", MyValue = 100
            };

            DistributedCache.Insert("SimpleObject", simple, DateTime.UtcNow.AddSeconds(30));
            SimpleProtoObject cachedObject = DistributedCache.Get <SimpleProtoObject>("SimpleObject");
        }
Exemplo n.º 5
0
        public string Get()
        {
            var value = "boy".ToBytes();

            DistributedCache.Get("hello");

            DistributedCache.Refresh("hello");

            DistributedCache.Set("hello", value, Options.Value);

            return("hello");
        }
Exemplo n.º 6
0
        public object GetObject <T>(string key)
        {
            if (key != string.Empty)
            {
                byte[] data              = DistributedCache.Get(key);
                var    bytesAsString     = Encoding.UTF8.GetString(data);
                var    deserializeObject = JsonConvert.DeserializeObject <T>(bytesAsString);
                return(deserializeObject);
            }

            return(null);
        }
Exemplo n.º 7
0
 /// <summary>
 /// 获取服务器列表
 /// </summary>
 /// <returns></returns>
 public List <string> GetAllServers()
 {
     if (_servers.Count == 0)
     {
         _servers = DistributedCache.Get(CacheKeys.InstuctionServerCacheKey) as List <string>;
     }
     if (_servers == null)
     {
         _servers = new List <string>();
     }
     return(_servers);
 }
Exemplo n.º 8
0
 private bool HasReceived(string cacheKey)
 {
     try
     {
         return(DistributedCache.Get(cacheKey) != null);
     }
     catch (Exception ex)
     {
         MetricsKeys.Cache_Error.MeterMark();
         string errMsg = "分布式缓存出现异常:" + DistributedCache.ProviderName + ", " + ex.GetString();
         Process.Error(cacheKey, "分布式缓存", "DistributedCacheProvider.Provider.Add", cacheKey, errMsg, "");
         return(false);
     }
 }
        public void DistributedCache_Get_ThrowsExceptionIfValueIsNotOfRequestedType()
        {
            using (new MunqContext())
            {
                var registrar = Dependency.Resolve <IDependencyRegistrar>();

                var cache = A.Fake <IDistributedCache>();
                registrar.RegisterInstance(cache);

                A.CallTo(() => cache.Get <int>("SomeKey"))
                .Throws <InvalidCastException>();

                Assert.Throws <InvalidCastException>(() => DistributedCache.Get <int>("SomeKey"));
            }
        }
Exemplo n.º 10
0
        public void Get_DoesNotThrow_WhenNoCachedValueForValueType()
        {
            // Arrange
            var key = Guid.NewGuid().ToString();
            var msDistributedCache = Substitute.For <IDistributedCache>();

            msDistributedCache.Get(key).Returns((byte[])null);
            const int expectedValue = default(int);
            var       sut           = new DistributedCache(msDistributedCache, Substitute.For <ILogger <DistributedCache> >());

            // Act
            var result = sut.Get <int>(key);

            // Assert
            Assert.AreEqual(expectedValue, result);
        }
        public void DistributedCache_Get_UsesRegisteredDistributedCacheProvider()
        {
            using (new MunqContext())
            {
                var registrar = Dependency.Resolve <IDependencyRegistrar>();

                var cache = A.Fake <IDistributedCache>();
                registrar.RegisterInstance(cache);

                A.CallTo(() => cache.Get <int>("SomeKey"))
                .Returns(13579);

                var actual = DistributedCache.Get <int>("SomeKey");
                Assert.Equal(13579, actual);

                A.CallTo(() => cache.Get <int>("SomeKey"))
                .MustHaveHappened(Repeated.Exactly.Once);
            }
        }
 private async Task <List <AppConfigCacheModel> > LoadFromRedis()
 {
     return(await DistributedCache.Get <List <AppConfigCacheModel> >(_cacheKey));
 }
Exemplo n.º 13
0
 private async Task <List <InvoiceStatusCacheModel> > LoadFromRedis()
 {
     return(await DistributedCache.Get <List <InvoiceStatusCacheModel> >(_cacheKey));
 }
Exemplo n.º 14
0
 private async Task <List <TaskPriorityCacheModel> > LoadFromRedis()
 {
     return(await DistributedCache.Get <List <TaskPriorityCacheModel> >(_cacheKey));
 }
Exemplo n.º 15
0
 private async Task <List <ReceiptDescriptionCacheModel> > LoadFromRedis()
 {
     return(await DistributedCache.Get <List <ReceiptDescriptionCacheModel> >(_cacheKey));
 }
 private async Task <List <ManufacturerCacheModel> > LoadFromRedis()
 {
     return(await DistributedCache.Get <List <ManufacturerCacheModel> >(_cacheKey));
 }
Exemplo n.º 17
0
 private async Task <List <ProductUnitCacheModel> > LoadFromRedis()
 {
     return(await DistributedCache.Get <List <ProductUnitCacheModel> >(_cacheKey));
 }
Exemplo n.º 18
0
        private void CheckTwoFactorAuthentication(string username, LoginRequest request)
        {
            bool isTwoFactorReq = !string.IsNullOrEmpty(request.TwoFactorGuid) || request.TwoFactorCode != null;

            if (isTwoFactorReq)
            {
                Check.NotNullOrEmpty(request.TwoFactorGuid, "twoFactorGuid");
                Check.NotNull(request.TwoFactorCode, "twoFactorCode");

                var key  = "TwoFactorAuth:" + request.TwoFactorGuid;
                var data = DistributedCache.Get <TwoFactorData>(key);
                if (data == null || data.Username == null || data.Username != username)
                {
                    throw new ValidationError("Can't validate credentials. Please try login again!");
                }

                data.RetryCount++;
                if (data.RetryCount > 3)
                {
                    DistributedCache.Set <TwoFactorData>(key, null);
                    throw new ValidationError("Can't validate credentials. Please try login again!");
                }
                else
                {
                    DistributedCache.Set(key, data);
                }

                if (data.TwoFactorCode != request.TwoFactorCode)
                {
                    throw new ValidationError("Validation code is invalid. Please check and try again.");
                }

                // login success. clear to not let same two factor guid/two factor code two be reused later
                DistributedCache.Set <TwoFactorData>(key, null);

                return;
            }

            var user = Dependency.Resolve <IUserRetrieveService>().ByUsername(username) as UserDefinition;

            if (user != null &&
                ((user.TwoFactorAuth == Administration.TwoFactorAuthType.SMS &&
                  user.MobilePhoneVerified &&
                  UserRepository.IsValidPhone(user.MobilePhoneNumber)) ||
                 (user.TwoFactorAuth == Administration.TwoFactorAuthType.Email)))
            {
                var env = Config.Get <EnvironmentSettings>();

                // you may disable two factor auth when <compilation debug="true" /> in web.config, by uncommenting lines below
                // if (HttpContext.IsDebuggingEnabled)
                //    return;

                var md5  = new MD5CryptoServiceProvider().ComputeHash(Encoding.UTF8.GetBytes(request.Password ?? ""));
                var data = new TwoFactorData
                {
                    RetryCount    = 0,
                    Username      = username,
                    TwoFactorCode = new Random().Next(9000) + 1000
                };

                // this is to prevent users from sending too many SMS in a certain time interval
                var throttler = new Throttler("TwoFactorAuthThrottle:" + username, TimeSpan.FromMinutes(5), 10);
                if (!throttler.Check())
                {
                    throw new ValidationError(
                              "Can't proceed with two factor authentication. You are over your validation limit!");
                }

                var twoFactorGuid = Guid.NewGuid().ToString("N");

                string authenticationMessage;
                if (user.TwoFactorAuth == Administration.TwoFactorAuthType.SMS)
                {
                    var mobile = user.MobilePhoneNumber.Trim();
                    Dependency.Resolve <Administration.ISMSService>().Send(
                        phoneNumber: mobile,
                        text: "Please use code " + data.TwoFactorCode + " for Allocation login.",
                        reason: "Sent by Allocation system for two factor authenication by SMS (" + user.Username +
                        ")");

                    // mask mobile number
                    mobile = mobile.Substring(0, 2) + new string('*', mobile.Length - 4) +
                             mobile.Substring(mobile.Length - 2, 2);
                    authenticationMessage = "Please enter code sent to your mobile phone with number " + mobile +
                                            " in <span class='counter'>{0}</span> seconds." +
                                            ((Dependency.Resolve <Administration.ISMSService>() is Administration
                                              .FakeSMSService)
                                                ? " (You can find a text file under App_Data/SMS directory, as you haven't configured SMS service yet)"
                                                : "");
                }
                else
                {
                    EmailHelper.Send(
                        address: user.Email,
                        subject: "Your two-factor authentication code for Allocation login",
                        body: "Please use code " + data.TwoFactorCode + " for Allocation login.");
                    authenticationMessage = "Please enter code sent to your e-mail adress in {0} seconds." +
                                            " (If you didn't configure an SMTP server, you can find e-mails under App_Data/Mail directory";
                }

                DistributedCache.Set("TwoFactorAuth:" + twoFactorGuid, data, TimeSpan.FromMinutes(2));
                throw new ValidationError("TwoFactorAuthenticationRequired",
                                          authenticationMessage + "|" + twoFactorGuid, "Two factor authentication is required!");
            }
        }
 private async Task <List <CustomerUserCacheModel> > LoadFromRedis()
 {
     return(await DistributedCache.Get <List <CustomerUserCacheModel> >(_cacheKey));
 }
Exemplo n.º 20
0
        public ActionResult <IEnumerable <string> > Get()
        {
            //SmtpConfig
            //var connectionString = Config.GetConnectionString("SqlServer");

            //TblUser model = new TblUser()
            //{
            //	ID = Guid.NewGuid(),
            //	Name = "Young",
            //	DataCreated = DateTimeOffset.Now
            //};
            //access.DataAccess<TblUser> userDataAccess = new access.DataAccess<TblUser>(_context);
            //bool result = userDataAccess.Add(model);

            //if (result)
            //{
            //	model.Name = "Young+Lau";
            //	result = userDataAccess.Update(model);

            //	if (result)
            //	{
            //		model.Name = "Young+Lau+Hello,World";
            //		result = userDataAccess.Update(model, false, model.ID);

            //		if (result)
            //		{
            //			var m = userDataAccess.QueryByID(model.ID);

            //			if (m != null)
            //			{
            //				var lst = userDataAccess.QueryAll(t => t.ID != null);

            //				if (lst != null)
            //				{
            //					//
            //				}
            //			}
            //		}
            //	}
            //}
            //Assert.NotNull(model);
            //Assert.Equal(true, result);

            #region

            if (HttpContext.Session == null || !HttpContext.Session.IsAvailable)
            {
                HttpContext.Session.SetString("UserID", "1000");               //Microsoft.AspNetCore.Http
            }

            //添加
            bool booladd = cache.Add("id", "sssss");
            //验证
            bool boolExists = cache.Exists("id");
            //获取
            object obj = cache.Get("id");
            //删除
            bool boolRemove = cache.Remove("id");
            //修改
            bool boolModify = cache.Modify("id", "ssssssss");

            #endregion

            return(new string[] { "value1", "value2" });
        }
Exemplo n.º 21
0
        private string GetCacheValue(string key)
        {
            var value = DistributedCache.Get(key);

            return(DistributedCache.FormatCacheValue(value));
        }