Exemplo n.º 1
0
        /// <summary>
        /// Adds an entry to the barrel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Unique identifier for the entry</param>
        /// <param name="data">Data object to store</param>
        /// <param name="expireIn">Time from UtcNow to expire entry in</param>
        /// <param name="eTag">Optional eTag information</param>
        /// <param name="jsonSerializationSettings">Custom json serialization settings to use</param>
        public void Add <T>(string key, T data, TimeSpan expireIn, string eTag = null, JsonSerializerSettings jsonSerializationSettings = null)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentException("Key can not be null or empty.", nameof(key));
            }


            if (data == null)
            {
                throw new ArgumentNullException("Data can not be null.", nameof(data));
            }

            var dataJson = string.Empty;

            if (BarrelUtils.IsString(data))
            {
                dataJson = data as string;
            }
            else
            {
                dataJson = JsonConvert.SerializeObject(data, jsonSerializationSettings ?? jsonSettings);
            }

            Add(key, dataJson, expireIn, eTag);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Gets the data entry for the specified key.
        /// </summary>
        /// <param name="key">Unique identifier for the entry to get</param>
        /// <param name="jsonSerializationSettings">Custom json serialization settings to use</param>
        /// <returns>The data object that was stored if found, else default(T)</returns>
        public T Get <T>(string key, JsonSerializerSettings jsonSerializationSettings = null)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentException("Key can not be null or empty.", nameof(key));
            }

            Banana ent;

            lock (dblock)
            {
                ent = db.Query <Banana>($"SELECT {nameof(ent.Contents)} FROM {nameof(Banana)} WHERE {nameof(ent.Id)} = ?", key).FirstOrDefault();
            }

            var result = default(T);

            if (ent == null || (AutoExpire && IsExpired(key)))
            {
                return(result);
            }

            if (BarrelUtils.IsString(result))
            {
                object final = ent.Contents;
                return((T)final);
            }


            return(JsonConvert.DeserializeObject <T>(ent.Contents, jsonSerializationSettings ?? jsonSettings));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Adds an entry to the barrel
        /// </summary>
        /// <param name="key">Unique identifier for the entry</param>
        /// <param name="data">Data object to store</param>
        /// <param name="expireIn">Time from UtcNow to expire entry in</param>
        /// <param name="eTag">Optional eTag information</param>
        void Add(string key, string data, TimeSpan expireIn, string eTag = null)
        {
            indexLocker.EnterWriteLock();

            try
            {
                var hash = Hash(key);
                var path = Path.Combine(baseDirectory.Value, hash);

                if (!Directory.Exists(baseDirectory.Value))
                {
                    Directory.CreateDirectory(baseDirectory.Value);
                }

                File.WriteAllText(path, data);

                index[key] = new Tuple <string, DateTime>(eTag ?? string.Empty, BarrelUtils.GetExpiration(expireIn));

                WriteIndex();
            }
            finally
            {
                indexLocker.ExitWriteLock();
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// FileStore Barrel constructor
        /// </summary>
        /// <param name="cacheDirectory">Optionally specify directory where cache will live</param>
        /// <param name="hash">Optionally specify hash algorithm</param>
        Barrel(string cacheDirectory = null, HashAlgorithm hash = null)
        {
            baseDirectory = new Lazy <string>(() =>
            {
                return(string.IsNullOrEmpty(cacheDirectory) ?
                       Path.Combine(BarrelUtils.GetBasePath(ApplicationId), "MonkeyCacheFS")
                                        : cacheDirectory);
            });

            hashAlgorithm = hash;
            if (hashAlgorithm == null)
            {
                hashAlgorithm = MD5.Create();
            }

            indexLocker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);

            jsonSettings = new JsonSerializerSettings
            {
                ObjectCreationHandling = ObjectCreationHandling.Replace,
                ReferenceLoopHandling  = ReferenceLoopHandling.Ignore,
                TypeNameHandling       = TypeNameHandling.All,
            };

            index = new Dictionary <string, Tuple <string, DateTime> >();

            LoadIndex();
            WriteIndex();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Gets the data entry for the specified key.
        /// </summary>
        /// <param name="key">Unique identifier for the entry to get</param>
        /// <param name="jsonSerializationSettings">Custom json serialization settings to use</param>
        /// <returns>The data object that was stored if found, else default(T)</returns>
        public T Get <T>(string key, JsonSerializerSettings jsonSerializationSettings = null)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentException("Key can not be null or empty.", nameof(key));
            }

            var result = default(T);

            indexLocker.EnterReadLock();

            try
            {
                var hash = Hash(key);
                var path = Path.Combine(baseDirectory.Value, hash);

                if (index.ContainsKey(key) && File.Exists(path) && (!AutoExpire || (AutoExpire && !IsExpired(key))))
                {
                    var contents = File.ReadAllText(path);
                    if (BarrelUtils.IsString(result))
                    {
                        object final = contents;
                        return((T)final);
                    }

                    result = JsonConvert.DeserializeObject <T>(contents, jsonSerializationSettings ?? jsonSettings);
                }
            }
            finally
            {
                indexLocker.ExitReadLock();
            }

            return(result);
        }
Exemplo n.º 6
0
        public void SetCacheDirectoryTwice()
        {
            BarrelUtils.basePath = string.Empty;
            var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            BarrelUtils.SetBaseCachePath(folder);
            BarrelUtils.SetBaseCachePath(folder);
        }
Exemplo n.º 7
0
        public static void SetupCache()
        {
            Log.Information("Initializing MonkeyCache");
            var cachePath = Path.Combine("Storage", "MonkeyCache").EnsureDir();

            Barrel.ApplicationId = "WinTenApi-Cache";
            BarrelUtils.SetBaseCachePath(cachePath);

            Log.Debug("MonkeyCache initialized.");
        }
Exemplo n.º 8
0
        public void SetCacheDirectoryAfterInitialize()
        {
            IBarrel barrel = null;
            var     folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            SetupBarrel(ref barrel);
            barrel.EmptyAll();

            BarrelUtils.SetBaseCachePath(folder);
        }
Exemplo n.º 9
0
    public static void SetupCache()
    {
        Log.Information("Initializing MonkeyCache");
        var cachePath = Path.Combine("Storage", "MonkeyCache").SanitizeSlash().EnsureDirectory(true);

        Barrel.ApplicationId = "ZiziBot-Cache";
        BarrelUtils.SetBaseCachePath(cachePath);

        Log.Debug("Deleting old MonkeyCache");
        DeleteKeys();

        Log.Information("MonkeyCache is ready.");
    }
Exemplo n.º 10
0
        /// <summary>
        /// Adds a string netry to the barrel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Unique identifier for the entry</param>
        /// <param name="data">Data string to store</param>
        /// <param name="expireIn">Time from UtcNow to expire entry in</param>
        /// <param name="eTag">Optional eTag information</param>
        void Add(string key, string data, TimeSpan expireIn, string eTag = null)
        {
            var ent = new Banana
            {
                Id             = key,
                ExpirationDate = BarrelUtils.GetExpiration(expireIn),
                ETag           = eTag,
                Contents       = data
            };

            lock (dblock)
            {
                db.InsertOrReplace(ent);
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Adds a string netry to the barrel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">Unique identifier for the entry</param>
        /// <param name="data">Data string to store</param>
        /// <param name="expireIn">Time from UtcNow to expire entry in</param>
        /// <param name="eTag">Optional eTag information</param>
        void Add(string key, string data, TimeSpan expireIn, string eTag = null)
        {
            if (data == null)
            {
                return;
            }

            var ent = new Banana
            {
                Id             = key,
                ExpirationDate = BarrelUtils.GetExpiration(expireIn),
                ETag           = eTag,
                Contents       = data
            };

            col.Upsert(ent);
        }
Exemplo n.º 12
0
        public void SetBaseCacheDirectory()
        {
            var path = BarrelUtils.basePath;

            try
            {
                BarrelUtils.basePath = string.Empty;
                var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                BarrelUtils.SetBaseCachePath(folder);

                Assert.AreEqual(folder, BarrelUtils.basePath);
            }
            finally
            {
                BarrelUtils.basePath = path;
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Gets the data entry for the specified key.
        /// </summary>
        /// <param name="key">Unique identifier for the entry to get</param>
        /// <param name="jsonSerializationSettings">Custom json serialization settings to use</param>
        /// <returns>The data object that was stored if found, else default(T)</returns>
        public T Get <T>(string key, JsonSerializerSettings jsonSerializationSettings = null)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentException("Key can not be null or empty.", nameof(key));
            }

            var result = default(T);

            var ent = col.FindById(key);

            if (ent == null || (AutoExpire && IsExpired(key)))
            {
                return(result);
            }

            if (BarrelUtils.IsString(result))
            {
                object final = ent.Contents;
                return((T)final);
            }

            return(JsonConvert.DeserializeObject <T>(ent.Contents, jsonSerializationSettings ?? jsonSettings));
        }
Exemplo n.º 14
0
        public override void SetupBarrel()
        {
            var dir = BarrelUtils.GetBasePath("com.refractored.monkeylite.customdir");

            this.barrel = Barrel.Create(dir, true);
        }