XAML-Map-Control/SQLiteCache/UWP/SQLiteCache.UWP.cs

98 lines
2.9 KiB
C#
Raw Normal View History

2019-07-18 23:08:10 +02:00
// XAML Map Control - https://github.com/ClemensFischer/XAML-Map-Control
// © 2019 Clemens Fischer
// Licensed under the Microsoft Public License (Ms-PL)
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
namespace MapControl.Caching
{
/// <summary>
/// IImageCache implementation based on SqLite.
/// </summary>
2019-07-21 00:17:16 +02:00
public partial class SQLiteCache : IImageCache
2019-07-18 23:08:10 +02:00
{
public SQLiteCache(StorageFolder folder, string fileName = "TileCache.sqlite")
{
if (folder == null)
{
throw new ArgumentNullException("The parameter folder must not be null.");
}
if (string.IsNullOrEmpty(fileName))
{
throw new ArgumentNullException("The parameter fileName must not be null.");
}
2019-07-21 00:17:16 +02:00
connection = Open(Path.Combine(folder.Path, fileName));
2019-07-18 23:08:10 +02:00
2019-07-21 00:17:16 +02:00
Clean();
}
2019-07-18 23:08:10 +02:00
2019-07-21 00:17:16 +02:00
public async Task<ImageCacheItem> GetAsync(string key)
{
if (key == null)
2019-07-18 23:08:10 +02:00
{
2019-07-21 00:17:16 +02:00
throw new ArgumentNullException("The parameter key must not be null.");
2019-07-18 23:08:10 +02:00
}
2019-07-21 00:17:16 +02:00
ImageCacheItem imageCacheItem = null;
2019-07-18 23:08:10 +02:00
try
{
2019-07-21 00:17:16 +02:00
using (var command = GetItemCommand(key))
2019-07-18 23:08:10 +02:00
{
var reader = await command.ExecuteReaderAsync();
2019-07-21 00:17:16 +02:00
if (await reader.ReadAsync())
2019-07-18 23:08:10 +02:00
{
2019-07-21 00:17:16 +02:00
imageCacheItem = new ImageCacheItem
2019-07-18 23:08:10 +02:00
{
Expiration = new DateTime((long)reader["expiration"]),
Buffer = ((byte[])reader["buffer"]).AsBuffer()
};
}
}
}
catch (Exception ex)
{
2019-07-21 00:17:16 +02:00
Debug.WriteLine("SQLiteCache.GetAsync(\"{0}\"): {1}", key, ex.Message);
2019-07-18 23:08:10 +02:00
}
2019-07-21 00:17:16 +02:00
return imageCacheItem;
2019-07-18 23:08:10 +02:00
}
public async Task SetAsync(string key, IBuffer buffer, DateTime expiration)
{
2019-07-21 00:17:16 +02:00
if (key == null)
{
throw new ArgumentNullException("The parameter key must not be null.");
}
if (buffer == null)
{
throw new ArgumentNullException("The parameter buffer must not be null.");
}
2019-07-18 23:08:10 +02:00
try
{
2019-07-21 00:17:16 +02:00
using (var command = SetItemCommand(key, expiration, buffer.ToArray()))
2019-07-18 23:08:10 +02:00
{
await command.ExecuteNonQueryAsync();
}
2019-07-21 00:17:16 +02:00
//Debug.WriteLine("SQLiteCache.SetAsync(\"{0}\"): expires {1}", key, expiration.ToLocalTime());
2019-07-18 23:08:10 +02:00
}
catch (Exception ex)
{
2019-07-21 00:17:16 +02:00
Debug.WriteLine("SQLiteCache.SetAsync(\"{0}\"): {1}", key, ex.Message);
2019-07-18 23:08:10 +02:00
}
}
}
}