// ----------------------------------------------------------------------- // // 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.IO; using System.Threading.Tasks; using System.Web.Hosting; using ImageProcessor.Web.Config; using ImageProcessor.Web.Helpers; using SQLite; #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 = IndexLocation; #endregion #region Methods #region Internal /// /// Creates the database if it doesn't already exist. /// internal static void CreateDatabase() { try { 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); } } using (SQLiteConnection connection = new SQLiteConnection(IndexLocation)) { connection.CreateTable(); } } } catch (Exception ex) { throw ex; } } /// /// Gets all the images from the database. /// /// /// The . /// internal static Dictionary GetImages() { Dictionary dictionary = new Dictionary(); try { using (SQLiteConnection connection = new SQLiteConnection(ConnectionString)) { List images = connection.Query("SELECT * FROM CachedImage"); foreach (CachedImage cachedImage in images) { dictionary.Add(cachedImage.Key, cachedImage); } } return dictionary; } catch { return new Dictionary(); } } /// /// Adds a cached image to the database. /// /// /// The cached image to add. /// /// /// The true if the addition of the cached image is added; otherwise, false. /// internal static async Task AddImageAsync(CachedImage image) { try { SQLiteAsyncConnection connection = new SQLiteAsyncConnection(ConnectionString); return await connection.InsertAsync(image); } catch { return 0; } } /// /// 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(CachedImage cachedImage) { try { SQLiteAsyncConnection connection = new SQLiteAsyncConnection(ConnectionString); return await connection.DeleteAsync(cachedImage); } catch { return 0; } } #endregion #endregion } }