Example #1
0
        private WpiHelper GetWpiHelper(int UserId)
        {
            string CACHE_KEY = GetKey_object(UserId);

            if (_cache.Contains(CACHE_KEY))
            {
                WpiHelper result = (WpiHelper)_cache[CACHE_KEY];

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

            string[] feeds = (string[])_cache[GetKey_Feeds(UserId)];
            if (null == feeds)
            {
                throw new Exception("BUG:No feeds in cache.");
            }

            WpiHelper            wpi = new WpiHelper(feeds);
            ICacheItemExpiration exp = new SlidingTime(TimeSpan.FromMinutes(LIVE_IN_CACHE_MINUTES));

            _cache.Add(CACHE_KEY, wpi, CacheItemPriority.Normal, null, exp);
            //Debug.WriteLine(string.Format("GetWpiHelper: put in cache. User {0}", UserId));

            return(wpi);
        }
 private ICacheItemExpiration[] GetCacheExpirations()
 {
     ICacheItemExpiration[] cachingExpirations = new ICacheItemExpiration[2];
     cachingExpirations[0] = new AbsoluteTime(new TimeSpan(0, 0, ConvertExpirationTimeToSeconds(absoluteExpiration)));
     cachingExpirations[1] = new SlidingTime(new TimeSpan(0, 0, ConvertExpirationTimeToSeconds(slidingExpiration)));
     return(cachingExpirations);
 }
Example #3
0
        //获取设置的异常过期策略
        private void GetICacheItemExpiration(string interval, string assemblyName, string className, ref ICacheItemExpiration[] ie)
        {
            switch (className)
            {
            case "Microsoft.ApplicationBlocks.Cache.ExpirationsImplementations.SlidingTime":
                double dinterval = double.Parse(interval);
                ie    = new SlidingTime[1];
                ie[0] = new SlidingTime(TimeSpan.FromSeconds(dinterval));
                break;

            case "Microsoft.ApplicationBlocks.Cache.ExpirationsImplementations.AbsoluteTime":
                double          secondsAfter = double.Parse(interval);
                System.DateTime dt           = System.DateTime.Now.AddSeconds(secondsAfter);
                ie    = new AbsoluteTime[1];
                ie[0] = new AbsoluteTime(dt);
                break;

            case "Microsoft.ApplicationBlocks.Cache.ExpirationsImplementations.FileDependency":
                ie    = new FileDependency[1];
                ie[0] = new FileDependency(interval);
                break;

            case "Microsoft.ApplicationBlocks.Cache.ExpirationsImplementations.ExtendedFormatTime":
                ie    = new ExtendedFormatTime[1];
                ie[0] = new ExtendedFormatTime(interval);
                break;

            default:
                ICacheItemExpiration ieTemp = Assembly.Load(assemblyName).CreateInstance(className) as ICacheItemExpiration;
                ie    = Array.CreateInstance(ieTemp.GetType(), 1) as ICacheItemExpiration[];
                ie[0] = ieTemp;
                break;
            }
        }
Example #4
0
        public override List <AspnetUserExtInfo> GetList()
        {
            string key = _cacheKeyPrefix + "_UserExtList";

            List <AspnetUserExtInfo> list = (List <AspnetUserExtInfo>)_cache.GetData(key);

            if (list == null)
            {
                list = new List <AspnetUserExtInfo>();
                string    spname = "aspnet_UserExtentInfo_GetList";
                Database  db     = DatabaseFactory.CreateDatabase(_connectionStringName);
                DbCommand comm   = db.GetStoredProcCommand(spname);
                db.AddParameter(comm, "@ReturnValue", DbType.Int32, ParameterDirection.ReturnValue,
                                String.Empty, DataRowVersion.Default, null);
                db.AddInParameter(comm, "@ApplicationName", DbType.String, _applicationName);
                DataSet ds = db.ExecuteDataSet(comm);
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    list.Add(BuildUserExtInfo(row));
                }
                SlidingTime            slidingExpired = new SlidingTime(new TimeSpan(0, 2, 0, 0, 0));
                ICacheItemExpiration[] expiredList    = { slidingExpired };

                _cache.Add(key, list, CacheItemPriority.Normal, null, expiredList);
            }
            return(list);
        }
        public void WillExpireOnSchedule()
        {
            SlidingTime expiration = new SlidingTime(TimeSpan.FromSeconds(1.5));

            Thread.Sleep(2000);
            Assert.IsTrue(expiration.HasExpired(), "Should have expired after enough time elapsed");
        }
        public override IDataReader GetDataReader(
            IGxConnectionManager connManager,
            IGxConnection con,
            GxParameterCollection parameters,
            string stmt, ushort fetchSize,
            bool forFirst, int handle,
            bool cached, SlidingTime expiration,
            bool hasNested,
            bool dynStmt)
        {
            IDataReader idatareader;

            if (NpgsqlAssembly.GetName().Version.Major == 1)
            {
                GXLogging.Debug(log, "ExecuteReader: client cursor=" + hasNested + ", handle '" + handle + "'" + ", hashcode " + this.GetHashCode());
                idatareader = new GxDataReader(connManager, this, con, parameters, stmt, fetchSize, forFirst, handle, cached, expiration, dynStmt);
            }
            else
            {
                if (!hasNested)                //Client Cursor
                {
                    GXLogging.Debug(log, "ExecuteReader: client cursor=" + hasNested + ", handle '" + handle + "'" + ", hashcode " + this.GetHashCode());
                    idatareader = new GxDataReader(connManager, this, con, parameters, stmt, fetchSize, forFirst, handle, cached, expiration, dynStmt);
                }
                else                 //Server Cursor
                {
                    GXLogging.Debug(log, "ExecuteReader: server cursor=" + hasNested + ", handle '" + handle + "'" + ", hashcode " + this.GetHashCode());
                    idatareader = new GxPostgresqlMemoryDataReader(connManager, this, con, parameters, stmt, fetchSize, forFirst, handle, cached, expiration, dynStmt);
                }
            }
            return(idatareader);
        }
Example #7
0
        /// <summary>
        /// 添加缓存 过期时间
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="timespan">过期时间默认2分钟 缓存在最后一次访问之后多少时间后过期</param>
        public static void Add(string key, object value, TimeSpan timespan)
        {
            timespan = timespan == null ? new TimeSpan(0, 2, 0) : timespan;
            SlidingTime expireTime = new SlidingTime(timespan);

            cache.Add(key, value, CacheItemPriority.Normal, null, expireTime);
        }
        public override void OnActionExecuting(ActionExecutingContext actionExecutingContext)
        {
            LoadConfiguration();
            if (!_isEnabled)
            {
                return;
            }

            var         today             = DateTime.UtcNow;
            HttpContext httpContext       = actionExecutingContext.HttpContext;
            var         connectionFeature = httpContext.Features.Get <IHttpConnectionFeature>();
            var         ipAddress         = connectionFeature == null ? string.Empty : connectionFeature.RemoteIpAddress.ToString();
            var         actionName        = actionExecutingContext.RouteData.Values["Action"].ToString();
            var         controllerName    = actionExecutingContext.RouteData.Values["Controller"].ToString();
            var         record            = new CacheableResponse
            {
                ActionName     = actionName,
                ControllerName = controllerName,
                IpAdress       = ipAddress
            };
            var jsonResponse = record.GetIdentifier();
            var cachedData   = GetValue(jsonResponse);

            if (cachedData == null)
            {
                return;
            }

            var cacheableResponse = cachedData as CacheableResponse;

            if (cacheableResponse == null)
            {
                return;
            }

            var needToRefresh = cacheableResponse.UpdateDateTime.AddMinutes(SlidingTime) <= today;

            if (!needToRefresh && cacheableResponse.NumberOfRequests >= NumberOfRequests)
            {
                var numberOfRemainingRequests = 0;
                var timeResetTime             = (cacheableResponse.UpdateDateTime.AddMinutes(SlidingTime) - today).TotalSeconds;
                var message = string.Format(
                    RateLimitationConstants.ErrorMessage,
                    NumberOfRequests.ToString(CultureInfo.InvariantCulture),
                    SlidingTime.ToString(CultureInfo.InvariantCulture));

                var headers = actionExecutingContext.HttpContext.Response.Headers;

                actionExecutingContext.Result = new ContentResult
                {
                    StatusCode  = 429,
                    Content     = message,
                    ContentType = "text/plain"
                };
                headers.Add(RateLimitationConstants.XRateLimitLimitName, NumberOfRequests.ToString(CultureInfo.InvariantCulture));
                headers.Add(RateLimitationConstants.XRateLimitRemainingName, numberOfRemainingRequests.ToString(CultureInfo.InvariantCulture));
                headers.Add(RateLimitationConstants.XRateLimitResetName, timeResetTime.ToString(CultureInfo.InvariantCulture));
            }
        }
        private ICacheItemExpiration[] GetCacheExpirations()
        {
            CachingStoreProviderData cacheStorageProviderData = GetCacheStorageProviderData();

            ICacheItemExpiration[] cachingExpirations = new ICacheItemExpiration[2];
            cachingExpirations[0] = new AbsoluteTime(new TimeSpan(0, 0, ConvertExpirationTimeToSeconds(cacheStorageProviderData.AbsoluteExpiration)));
            cachingExpirations[1] = new SlidingTime(new TimeSpan(0, 0, ConvertExpirationTimeToSeconds(cacheStorageProviderData.SlidingExpiration)));
            return(cachingExpirations);
        }
Example #10
0
        public void CtorForLoadingInitializesExpirationsToMatchLastAccessedTime()
        {
            DateTime  historicalTimestamp = DateTime.Now - TimeSpan.FromHours(1.0);
            CacheItem item = new CacheItem(historicalTimestamp, "foo", "bar", CacheItemPriority.NotRemovable, null,
                                           new SlidingTime(TimeSpan.FromHours(17.0), DateTime.Now));

            SlidingTime expiration = item.Expirations[0] as SlidingTime;

            Assert.AreEqual(historicalTimestamp, expiration.TimeLastUsed);
        }
Example #11
0
        //Cache SlidingTime
        public GenericType Add <GenericType>(object Key, GenericType c, TimeSpan refreshTime)
        {
            if (Key != null)
            {
                SlidingTime expireTime = new SlidingTime(refreshTime);
                cacheManager.Add(getKey(Key), c, CacheItemPriority.Normal, null, expireTime);
            }

            return(c);
        }
        public void WillUpdateLastTouchedTimeWhenNotified()
        {
            DateTime initialTimeStamp = DateTime.Now - TimeSpan.FromSeconds(5.0);
            TimeSpan expirationWindow = TimeSpan.FromSeconds(5.0);
            SlidingTime slidingTime = new SlidingTime(expirationWindow, initialTimeStamp);

            DateTime now = DateTime.Now;

            slidingTime.Notify();

            Assert.IsTrue(slidingTime.TimeLastUsed >= now);
        }
        public void WillUpdateLastTouchedTimeWhenNotified()
        {
            DateTime    initialTimeStamp = DateTime.Now - TimeSpan.FromSeconds(5.0);
            TimeSpan    expirationWindow = TimeSpan.FromSeconds(5.0);
            SlidingTime slidingTime      = new SlidingTime(expirationWindow, initialTimeStamp);

            DateTime now = DateTime.Now;

            slidingTime.Notify();

            Assert.IsTrue(slidingTime.TimeLastUsed >= now);
        }
		public void ClassCanSerializeCorrectly()
		{
			SlidingTime slidingTime = new SlidingTime(new TimeSpan(0, 0, 2));
			
			BinaryFormatter formatter = new BinaryFormatter();
			MemoryStream stream = new MemoryStream();
			formatter.Serialize(stream, slidingTime);
			stream.Position = 0;
			SlidingTime slidingTime2 = (SlidingTime)formatter.Deserialize(stream);

			Assert.AreEqual(slidingTime.ItemSlidingExpiration, slidingTime2.ItemSlidingExpiration);
			Assert.AreEqual(slidingTime.TimeLastUsed, slidingTime2.TimeLastUsed);
		}
Example #15
0
        protected override T DoGetExpirationStrategy <T>()
        {
            if (!typeof(T).Equals(typeof(ICacheItemExpiration)))
            {
                throw new CacheException("类型 {0} 不对, 必须是 {1}",
                                         typeof(T).AssemblyQualifiedName,
                                         typeof(ICacheItemExpiration).AssemblyQualifiedName);
            }

            var slidingTime = new SlidingTime(ExpirationTime);

            return(slidingTime as T);
        }
        public void ClassCanSerializeCorrectly()
        {
            SlidingTime slidingTime = new SlidingTime(new TimeSpan(0, 0, 2));

            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream    stream    = new MemoryStream();

            formatter.Serialize(stream, slidingTime);
            stream.Position = 0;
            SlidingTime slidingTime2 = (SlidingTime)formatter.Deserialize(stream);

            Assert.AreEqual(slidingTime.ItemSlidingExpiration, slidingTime2.ItemSlidingExpiration);
            Assert.AreEqual(slidingTime.TimeLastUsed, slidingTime2.TimeLastUsed);
        }
        public void CanInitializeWithLastUpdatedTimeFromCacheItem()
        {
            CacheItem item = new CacheItem("key", "value", CacheItemPriority.Normal, null);
            DateTime timestampToSave = DateTime.Now + TimeSpan.FromDays(1.0);
            item.SetLastAccessedTime(timestampToSave);

            DateTime initialTimeStamp = DateTime.Now - TimeSpan.FromSeconds(5.0);
            TimeSpan expirationWindow = TimeSpan.FromSeconds(5.0);
            SlidingTime slidingTime = new SlidingTime(expirationWindow, initialTimeStamp);

            slidingTime.Initialize(item);

            Assert.AreEqual(timestampToSave, slidingTime.TimeLastUsed);
        }
Example #18
0
        public override IDataReader GetDataReader(
            IGxConnectionManager connManager,
            IGxConnection con,
            GxParameterCollection parameters,
            string stmt, ushort fetchSize,
            bool forFirst, int handle,
            bool cached, SlidingTime expiration,
            bool hasNested,
            bool dynStmt)
        {
            IDataReader idatareader;

            idatareader = new GxDataReader(connManager, this, con, parameters, stmt, fetchSize, forFirst, handle, cached, expiration, dynStmt);
            return(idatareader);
        }
        public void CanInitializeWithLastUpdatedTimeFromCacheItem()
        {
            CacheItem item            = new CacheItem("key", "value", CacheItemPriority.Normal, null);
            DateTime  timestampToSave = DateTime.Now + TimeSpan.FromDays(1.0);

            item.SetLastAccessedTime(timestampToSave);

            DateTime    initialTimeStamp = DateTime.Now - TimeSpan.FromSeconds(5.0);
            TimeSpan    expirationWindow = TimeSpan.FromSeconds(5.0);
            SlidingTime slidingTime      = new SlidingTime(expirationWindow, initialTimeStamp);

            slidingTime.Initialize(item);

            Assert.AreEqual(timestampToSave, slidingTime.TimeLastUsed);
        }
Example #20
0
 /// <summary>
 /// 将Cache的数据加到缓存manager中
 /// </summary>
 /// <param name="cacheData"></param>
 /// <param name="entityCfg"></param>
 private void addCacheDataToContainer(string key, CacheData cacheData, EntityCfg entityCfg)
 {
     if (entityCfg != null)
     {
         List <ICacheItemExpiration> cacheItemExpiration = new List <ICacheItemExpiration>();
         foreach (var cacheExpireCfg in entityCfg.Expirations)
         {
             if (cacheExpireCfg.ExpirationType == CacheExpirationType.AbsoluteTime)
             {
                 TimeSpan ts = TimeSpan.FromMilliseconds(cacheExpireCfg.ExpireTime);
                 if (ts.TotalMilliseconds > 0)
                 {
                     AbsoluteTime absoluteTime = new AbsoluteTime(ts);
                     cacheItemExpiration.Add(absoluteTime);
                 }
             }
             else if (cacheExpireCfg.ExpirationType == CacheExpirationType.SlidingTime)
             {
                 TimeSpan ts = TimeSpan.FromMilliseconds(cacheExpireCfg.ExpireTime);
                 if (ts.TotalMilliseconds > 0)
                 {
                     SlidingTime slidingTime = new SlidingTime(ts);
                     cacheItemExpiration.Add(slidingTime);
                 }
             }
             else if (cacheExpireCfg.ExpirationType == CacheExpirationType.FileDependency)
             {
                 if (System.IO.File.Exists(cacheExpireCfg.FilePath))
                 {
                     FileDependency fileDependency = new FileDependency(cacheExpireCfg.FilePath);
                     cacheItemExpiration.Add(fileDependency);
                 }
             }
         }
         if (entityCfg.IsCacheItemRefreshed)
         {
             _EntitySetCache.Add(key, cacheData, entityCfg.CacheItemPriority, new CacheItemRefreshAction(entityCfg, key), cacheItemExpiration.ToArray());
         }
         else
         {
             _EntitySetCache.Add(key, cacheData, entityCfg.CacheItemPriority, null, cacheItemExpiration.ToArray());
         }
     }
     else
     {
         _EntitySetCache.Add(key, cacheData);
     }
 }
        public override IDataReader GetDataReader(
            IGxConnectionManager connManager,
            IGxConnection con,
            GxParameterCollection parameters,
            string stmt, ushort fetchSize,
            bool forFirst, int handle,
            bool cached, SlidingTime expiration,
            bool hasNested,
            bool dynStmt)
        {
            IDataReader idatareader;

            GXLogging.Debug(log, "ExecuteReader: client cursor=", () => hasNested + ", handle '" + handle + "'" + ", hashcode " + this.GetHashCode());
            idatareader = new GxDataReader(connManager, this, con, parameters, stmt, fetchSize, forFirst, handle, cached, expiration, dynStmt);
            return(idatareader);
        }
Example #22
0
        public MemoryDataReader(IDataReader reader, IGxConnection connection, GxParameterCollection parameters,
                                string stmt, ushort fetchSize, bool isForFirst, bool withCached, SlidingTime expiration)
            : this()
        {
            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }
            if (reader.IsClosed)
            {
                throw new ArgumentException("Reader is closed");
            }

            DataTable schemaTab = reader.GetSchemaTable();

            if (schemaTab != null)
            {
                this._schemaDataTable = schemaTab.Clone();
            }


            string[] colnames = null;

            while (reader.Read())
            {
                if (colnames == null)
                {
                    colnames = new string[reader.FieldCount];
                    for (int fi = 0; fi < colnames.Length; fi++)
                    {
                        colnames[fi] = reader.GetName(fi);
                    }
                }

                this.AddRecord(reader, colnames);
            }
            this.cached = withCached;
            this.con    = connection;
            block       = new GxArrayList(fetchSize);
            if (cached)
            {
                this.key        = SqlUtil.GetKeyStmtValues(parameters, stmt, isForFirst);
                this.expiration = expiration;
            }
        }
Example #23
0
        public override IDataReader GetDataReader(
            IGxConnectionManager connManager,
            IGxConnection con,
            GxParameterCollection parameters,
            string stmt, ushort fetchSize,
            bool forFirst, int handle,
            bool cached, SlidingTime expiration,
            bool hasNested,
            bool dynStmt)
        {
            IDataReader idatareader;

#if !NETCORE
            GXLogging.Debug(log, "ExecuteReader: client cursor=" + hasNested + ", handle '" + handle + "'" + ", hashcode " + this.GetHashCode() + " PreparedStmt " + preparedStmts);
            if (preparedStmts)
            {
                idatareader = new GxMySQLCursorDataReader(connManager, this, con, parameters, stmt, fetchSize, forFirst, handle, cached, expiration, hasNested, dynStmt);
            }
            else
            {
                idatareader = new GxMySQLDataReader(connManager, this, con, parameters, stmt, fetchSize, forFirst, handle, cached, expiration, dynStmt, preparedStmts);
            }
#else
            if (!hasNested)//Client Cursor
            {
                GXLogging.Debug(log, "ExecuteReader: client cursor=" + hasNested + ", handle '" + handle + "'" + ", hashcode " + this.GetHashCode() + " PreparedStmt " + preparedStmts);
                if (preparedStmts)
                {
                    idatareader = new GxMySQLCursorDataReader(connManager, this, con, parameters, stmt, fetchSize, forFirst, handle, cached, expiration, hasNested, dynStmt);
                }
                else
                {
                    idatareader = new GxMySQLDataReader(connManager, this, con, parameters, stmt, fetchSize, forFirst, handle, cached, expiration, dynStmt, preparedStmts);
                }
            }
            else //Server Cursor
            {
                GXLogging.Debug(log, "ExecuteReader: server cursor=" + hasNested + ", handle '" + handle + "'" + ", hashcode " + this.GetHashCode());
                idatareader = new GxMySqlMemoryDataReader(connManager, this, con, parameters, stmt, fetchSize, forFirst, handle, cached, expiration, dynStmt);
            }
#endif
            return(idatareader);
        }
        /// <summary>
        /// 获得菜单授权验证数据
        /// </summary>
        /// <returns></returns>
        public override Dictionary <string, string> GetAllMenuRoleMaps()
        {
            string key     = _cacheKeyPrefix + "_MenuRoleMaps";
            string apppath = System.Web.HttpContext.Current.Request.ApplicationPath;

            if (!apppath.EndsWith("/"))
            {
                apppath += "/";
            }

            ICacheManager cache = CacheFactory.GetCacheManager();
            Dictionary <string, string> maps = (Dictionary <string, string>)cache.GetData(key);

            if (maps == null)
            {
                maps = new Dictionary <string, string>();

                DataTable table = GetMenusForValidate();
                if (table.Rows.Count > 0)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        string baseurl = row["baseurl"].ToString().Trim().ToLower();
                        if (!_isAppRootPath)
                        {
                            baseurl = baseurl.Replace("~/", apppath);
                        }
                        maps.Add(baseurl, row["roles"].ToString());
                    }
                }
                SlidingTime            slidingExpired = new SlidingTime(new TimeSpan(0, 2, 0, 0, 0));
                ICacheItemExpiration[] expiredList    = { slidingExpired };
                if (!cachekeys.Contains(key))
                {
                    cachekeys.Add(key);
                }
                cache.Add(key, maps, CacheItemPriority.Normal, null, expiredList);
            }
            return(maps);
        }
Example #25
0
        public void InitFeeds(int UserId, string[] feeds)
        {
            string CACHE_KEY = GetKey_Feeds(UserId);

            if (_cache.Contains(CACHE_KEY))
            {
                string[] oldfeeds = (string[])_cache[CACHE_KEY];

                if (!ArraysEqual <string>(feeds, oldfeeds))
                {
                    //Feeeds have been changed
                    ICacheItemExpiration exp = new SlidingTime(TimeSpan.FromMinutes(LIVE_IN_CACHE_MINUTES * 2));
                    _cache.Add(CACHE_KEY, feeds, CacheItemPriority.Normal, null, exp);

                    DeleteWpiHelper(UserId);
                }
            }
            else
            {
                //add to cache
                ICacheItemExpiration exp = new SlidingTime(TimeSpan.FromMinutes(LIVE_IN_CACHE_MINUTES * 2));
                _cache.Add(CACHE_KEY, feeds, CacheItemPriority.Normal, null, exp);
            }
        }
        public GxMySQLDriverCSCursorDataReader(IGxConnectionManager connManager, GxDataRecord dr, IGxConnection connection, GxParameterCollection parameters,
                                               string stmt, int fetchSize, bool forFirst, int handle, bool cached, SlidingTime expiration, bool hasNested, bool dynStmt)
        {
            this.parameters = parameters;
            this.stmt       = stmt;
            this.fetchSize  = fetchSize;
            this.cache      = connection.ConnectionCache;
            this.cached     = cached;
            this.handle     = handle;
            this.isForFirst = forFirst;
            _connManager    = connManager;
            this.m_dr       = dr;
            this.readBytes  = 0;
            this.dynStmt    = dynStmt;
            con             = _connManager.IncOpenHandles(handle, m_dr.DataSource);
            con.CurrentStmt = stmt;
            con.MonitorEnter();
            GXLogging.Debug(log, "Open GxMySQLCursorDataReader handle:'" + handle);
            MySQLCommand cmd = (MySQLCommand)dr.GetCommand(con, stmt, parameters);

            cmd.ServerCursor = hasNested;
            cmd.FetchSize    = (uint)fetchSize;
            reader           = cmd.ExecuteReader();
            cache.SetAvailableCommand(stmt, false, dynStmt);
            open  = true;
            block = new GxArrayList(fetchSize);
            pos   = -1;
            if (cached)
            {
                key             = SqlUtil.GetKeyStmtValues(parameters, stmt, isForFirst);
                this.expiration = expiration;
            }
        }
Example #27
0
        public string RegisterEMail(string toAddress)
        {
            string userid = Guid.NewGuid().ToString();

            try
            {
                string from = "*****@*****.**"; // Replace with your "From" address. This address must be verified.
                string to   = toAddress;             // Replace with a "To" address. If your account is still in the
                                                     // sandbox, this address must be verified.

                string otp = GenerateOTP();

                //_objCacheManager.Add(userid, otp);

                SlidingTime _objSlidingTime = new SlidingTime(TimeSpan.FromMinutes(30));
                _objCacheManager.Add(userid, otp, CacheItemPriority.Normal, null, _objSlidingTime);

//                bool test = ValidateUser(cacheKey, otp);

                string subject = "OTP For Bulletin Registration";

                string body = "Your OTP to install the bulletin App is " + otp + ". This is valid for the next 30 mins.";

                // Supply your SMTP credentials below. Note that your SMTP credentials are different from your AWS credentials.
                const String SMTP_USERNAME = "******";                         // Replace with your SMTP username.
                const String SMTP_PASSWORD = "******"; // Replace with your SMTP password.

                // Amazon SES SMTP host name. This example uses the US West (Oregon) region.
                const String HOST = "email-smtp.us-west-2.amazonaws.com";

                // The port you will connect to on the Amazon SES SMTP endpoint. We are choosing port 587 because we will use
                // STARTTLS to encrypt the connection.
                const int PORT = 587;

                // Create an SMTP client with the specified host name and port.
                using (System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(HOST, PORT))
                {
                    // Create a network credential with your SMTP user name and password.
                    client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);

                    // Use SSL when accessing Amazon SES. The SMTP session will begin on an unencrypted connection, and then
                    // the client will issue a STARTTLS command to upgrade to an encrypted connection using SSL.
                    client.EnableSsl = true;

                    // Send the email.
                    try
                    {
                        Console.WriteLine("Attempting to send an email through the Amazon SES SMTP interface...");
                        client.Send(from, to, subject, body);
                        //Console.WriteLine("Email sent!");
                    }
                    catch (Exception ex)
                    {
                        //Console.WriteLine("The email was not sent.");
                        //Console.WriteLine("Error message: " + ex.Message);
                    }
                }

                //Console.Write("Press any key to continue...");
                //Console.ReadKey();
            }
            catch (Exception ex) { }


            return(userid);
        }
 public void ConstructingWithATimeSpaceLessThanASecondThrowsException()
 {
     TimeSpan t = new TimeSpan(1);
     //Assert.IsFalse(t.TotalSeconds >= 1);
     SlidingTime slidingTime = new SlidingTime(t);
 }
Example #29
0
        public GxMySQLDataReader(IGxConnectionManager connManager, GxDataRecord dr, IGxConnection connection, GxParameterCollection parameters,
                                 string stmt, int fetchSize, bool forFirst, int handle, bool cached, SlidingTime expiration, bool dynStmt, bool preparedStmts)
        {
            this.parameters = parameters;
            this.stmt       = stmt;
            this.fetchSize  = fetchSize;
            this.cache      = connection.ConnectionCache;
            this.cached     = cached;
            this.handle     = handle;
            this.isForFirst = forFirst;
            _connManager    = connManager;
            this.m_dr       = dr;
            this.readBytes  = 0;
            this.dynStmt    = dynStmt;
            con             = _connManager.IncOpenHandles(handle, m_dr.DataSource);
            con.CurrentStmt = stmt;
            con.MonitorEnter();
            MySQLCommand cmd = (MySQLCommand)dr.GetCommand(con, stmt, parameters);

#if !NETCORE
            cmd.UsePreparedStatement = preparedStmts;
#endif
            reader = cmd.ExecuteReader();
            cache.SetAvailableCommand(stmt, false, dynStmt);
            open  = true;
            block = new GxArrayList(fetchSize);
            pos   = -1;
            if (cached)
            {
                key             = SqlUtil.GetKeyStmtValues(parameters, stmt, isForFirst);
                this.expiration = expiration;
            }
        }
        public GxPostgresqlMemoryDataReader(IGxConnectionManager connManager, GxDataRecord dr, IGxConnection connection, GxParameterCollection parameters,
                                            string stmt, ushort fetchSize, bool forFirst, int handle, bool cached, SlidingTime expiration, bool dynStmt) : base(connManager, dr, connection, parameters,
                                                                                                                                                                stmt, fetchSize, forFirst, handle, cached, expiration, dynStmt)
        {
            MemoryDataReader memoryDataReader = new MemoryDataReader(reader, connection, parameters, stmt, fetchSize, forFirst, cached, expiration);

            Close();
            reader = memoryDataReader;
        }
 public void WillExpireOnSchedule()
 {
     SlidingTime expiration = new SlidingTime(TimeSpan.FromSeconds(1.5));
     Thread.Sleep(2000);
     Assert.IsTrue(expiration.HasExpired(), "Should have expired after enough time elapsed");
 }
Example #32
0
        public void Cache(string alias, object obj, TimeSpan duration)
        {
            SlidingTime objSlidingTime = new SlidingTime(duration);

            cache.Add(alias, obj, CacheItemPriority.Normal, null, objSlidingTime);
        }
Example #33
0
        public void Add(string key, object value, TimeSpan relative)
        {
            ICacheItemExpiration expiration = new SlidingTime(relative);

            _cache.Add(key, value, CacheItemPriority.Normal, null, expiration);
        }
		public void ConstructingWithATimeSpaceLessThanASecondThrowsException()
		{
			TimeSpan t = new TimeSpan(1);
			//Assert.IsFalse(t.TotalSeconds >= 1);
			SlidingTime slidingTime = new SlidingTime(t);
		}
Example #35
0
 public GxInformixDataReader(IGxConnectionManager connManager, GxDataRecord dr, IGxConnection connection, GxParameterCollection parameters,
                             string stmt, int fetchSize, bool forFirst, int handle, bool cached, SlidingTime expiration, bool dynStmt)
     : base(connManager, dr, connection, parameters, stmt, fetchSize, forFirst, handle, cached, expiration, dynStmt)
 {
 }