// ----------------------------------------------------------------------- // // Copyright (c) James South. // Licensed under the Apache License, Version 2.0. // // ----------------------------------------------------------------------- namespace ImageProcessor.Web.Caching { #region Using using System; using System.Collections.Generic; using System.Data.SQLite; using System.IO; using System.Threading.Tasks; using System.Web.Hosting; using ImageProcessor.Web.Config; using ImageProcessor.Web.Helpers; #endregion /// /// Provides a wrapper for the SQLite functionality. /// internal sealed class SQLContext { #region Fields /// /// The default path for cached folders on the server. /// private static readonly string VirtualCachePath = ImageProcessorConfig.Instance.VirtualCachePath; /// /// The cached index location. /// private static readonly string IndexLocation = Path.Combine(HostingEnvironment.MapPath(VirtualCachePath), "cache.db"); /// /// The connection string. /// private static readonly string ConnectionString = string.Format("Data Source={0};Version=3;", IndexLocation); #endregion #region Methods #region Internal /// /// Creates the database if it doesn't already exist. /// internal static void CreateDatabase() { if (!File.Exists(IndexLocation)) { string absolutePath = HostingEnvironment.MapPath(VirtualCachePath); if (absolutePath != null) { DirectoryInfo directoryInfo = new DirectoryInfo(absolutePath); if (!directoryInfo.Exists) { // Create the directory. Directory.CreateDirectory(absolutePath); } } SQLiteConnection.CreateFile(IndexLocation); using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) { connection.Open(); using (SQLiteTransaction transaction = connection.BeginTransaction()) { using (SQLiteCommand command = new SQLiteCommand(connection)) { command.CommandText = @"CREATE TABLE names (Key TEXT, Path TEXT, MaxAge INTEGER, LastWriteTimeUtc TEXT, ExpiresUtc TEXT, PRIMARY KEY (Key), UNIQUE (Path));"; command.ExecuteNonQuery(); } transaction.Commit(); } } } } /// /// Gets all the images from the database. /// /// /// The . /// internal static Dictionary GetImages() { Dictionary dictionary = new Dictionary(); try { using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) { connection.Open(); using (SQLiteCommand command = new SQLiteCommand(connection)) { command.CommandText = "SELECT * FROM names;"; SQLiteDataReader reader = command.ExecuteReader(); while (reader.Read()) { string key = reader["Key"].ToString(); CachedImage image = new CachedImage( reader["Path"].ToString(), int.Parse(reader["MaxAge"].ToString()), DateTime.Parse(reader["LastWriteTimeUtc"].ToString()).ToUniversalTime(), DateTime.Parse(reader["ExpiresUtc"].ToString()).ToUniversalTime()); dictionary.Add(key, image); } } } return dictionary; } catch { return new Dictionary(); } } /// /// Adds a cached image to the database. /// /// /// The key for the cached image. /// /// /// The cached image to add. /// /// /// The true if the addition of the cached image is added; otherwise, false. /// internal static async Task AddImageAsync(string key, CachedImage image) { // Create Action delegate for AddImage. return await TaskHelpers.Run(() => AddImage(key, image)); } /// /// Removes a cached image from the database. /// /// /// The key for the cached image. /// /// /// The true if the addition of the cached image is removed; otherwise, false. /// internal static async Task RemoveImageAsync(string key) { // Create Action delegate for RemoveImage. return await TaskHelpers.Run(() => RemoveImage(key)); } #endregion #region Private /// /// Adds a cached image to the database. /// /// /// The key for the cached image. /// /// /// The cached image to add. /// /// /// The true if the addition of the cached image is added; otherwise, false. /// private static bool AddImage(string key, CachedImage image) { try { using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) { connection.Open(); using (SQLiteTransaction transaction = connection.BeginTransaction()) { using (SQLiteCommand command = new SQLiteCommand(connection)) { command.CommandText = "INSERT INTO names VALUES(?, ?, ?, ?, ?)"; SQLiteParameter[] parameters = new[] { new SQLiteParameter("Key", key), new SQLiteParameter("Path", image.Path), new SQLiteParameter("MaxAge", image.MaxAge), new SQLiteParameter("LastWriteTimeUtc", image.LastWriteTimeUtc), new SQLiteParameter("ExpiresUtc", image.ExpiresUtc) }; command.Parameters.AddRange(parameters); command.ExecuteNonQuery(); } transaction.Commit(); } } return true; } catch { return false; } } /// /// Removes a cached image from the database. /// /// /// The key for the cached image. /// /// /// The true if the addition of the cached image is removed; otherwise, false. /// private static bool RemoveImage(string key) { try { using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) { connection.Open(); using (SQLiteTransaction transaction = connection.BeginTransaction()) { using (SQLiteCommand command = new SQLiteCommand(connection)) { command.CommandText = "DELETE FROM names WHERE key = @searchParam;"; command.Parameters.Add(new SQLiteParameter("searchParam", key)); command.ExecuteNonQuery(); } transaction.Commit(); } } return true; } catch { return false; } } #endregion #endregion } }