friends caching

small improvements
This commit is contained in:
2011-04-09 01:47:50 +03:00
parent 9c59a73113
commit a297460f37
11 changed files with 323 additions and 122 deletions
+94 -17
View File
@@ -13,6 +13,7 @@ using System.Windows.Media.Imaging;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization;
using Microsoft.Phone;
namespace WPImageCaching
{
@@ -20,8 +21,66 @@ namespace WPImageCaching
{
private const string IMAGECACHEFILE = "imagecachefile.nfo";
internal static Dictionary<string, ImageCacheItem> imageCache;
internal static object _lock = new object();
public static BitmapImage GetImage(string url)
{
BitmapImage image = new BitmapImage();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
//Wenn im Designmodus von Blend oder Visual Studio
image.UriSource = new Uri(url);
return image;
}
if (imageCache == null)
{
LoadCachedImageInfo();
}
//Prüfen auf ein vorhandenes gespeichertes Bild
if (imageCache.ContainsKey(url))
{
//Prüfen auf Gültigkeit des Bildes
if (DateTime.Compare(DateTime.Now, imageCache[url].Expiration) >= 0)
{
ImageDownloadHelper.DownloadImage(url, image, imageCache[url]);
}
else
{
if (IsolatedStorageFile.GetUserStoreForApplication().FileExists(imageCache[url].LocalFilename))
{
//Bild ist noch gültig
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
lock (_lock)
{
using (
IsolatedStorageFileStream fs = isf.OpenFile(imageCache[url].LocalFilename,
FileMode.Open))
{
image.SetSource(fs);
return image;
}
}
}
}
else
{
ImageDownloadHelper.DownloadImage(url, image, imageCache[url]);
}
}
}
else
{
//Bild noch nicht gespeichert
ImageCacheItem item = new ImageCacheItem();
ImageDownloadHelper.DownloadImage(url, image, item);
}
return image;
}
public static BitmapImage GetImage(BitmapImage image)
{
string url = image.UriSource.ToString();
@@ -65,31 +124,49 @@ namespace WPImageCaching
//Laden der Bildinformationen
private static void LoadCachedImageInfo()
{
if (IsolatedStorageFile.GetUserStoreForApplication().FileExists(IMAGECACHEFILE))
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream fs =
IsolatedStorageFile.GetUserStoreForApplication().OpenFile(IMAGECACHEFILE,FileMode.Open);
lock (_lock)
{
if (isf.FileExists(IMAGECACHEFILE))
{
using (IsolatedStorageFileStream fs = isf.OpenFile(IMAGECACHEFILE, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs))
{
string serObj = sr.ReadToEnd();
imageCache = SerializationHelper.Deserialize<Dictionary<string, ImageCacheItem>>(serObj);
}
DataContractSerializer dcs = new DataContractSerializer(typeof(Dictionary<string, ImageCacheItem>));
imageCache = (Dictionary<string, ImageCacheItem>)dcs.ReadObject(fs);
fs.Close();
}
else
{
imageCache = new Dictionary<string, ImageCacheItem>();
}
}
}
if (imageCache == null)
{
imageCache = new Dictionary<string, ImageCacheItem>();
}
}
}
//Speichern der Bildinformationen
internal static void SaveCachedImageInfo()
{
IsolatedStorageFileStream fs =
IsolatedStorageFile.GetUserStoreForApplication().CreateFile(IMAGECACHEFILE);
DataContractSerializer dcs = new DataContractSerializer(typeof(Dictionary<string, ImageCacheItem>));
dcs.WriteObject(fs, imageCache);
fs.Flush();
fs.Close();
using (IsolatedStorageFile sf = IsolatedStorageFile.GetUserStoreForApplication())
{
lock (_lock)
{
if (sf.FileExists(IMAGECACHEFILE))
sf.DeleteFile(IMAGECACHEFILE);
using (IsolatedStorageFileStream fs = sf.CreateFile(IMAGECACHEFILE))
{
using (StreamWriter sw = new StreamWriter(fs))
{
string serObj = SerializationHelper.Serialize(imageCache);
sw.Write(serObj);
}
}
}
}
}
}
}
@@ -23,6 +23,10 @@ namespace WPImageCaching
{
return ImageCache.GetImage((BitmapImage)value);
}
if (value is string && !string.IsNullOrEmpty(value as string))
{
return ImageCache.GetImage((string)value);
}
else
{
return value;
+10 -1
View File
@@ -8,14 +8,23 @@ using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Runtime.Serialization;
namespace WPImageCaching
{
//Beinhaltet die Informationen eines Bildes
internal class ImageCacheItem
[DataContract]
public class ImageCacheItem
{
public ImageCacheItem()
{
}
[DataMember]
public string LocalFilename { get; set; }
[DataMember]
public string ImageID { get; set; }
[DataMember]
public DateTime Expiration { get; set; }
}
}
+90 -39
View File
@@ -15,6 +15,7 @@ using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Media.Imaging;
using System.Diagnostics;
namespace WPImageCaching
{
@@ -35,7 +36,7 @@ namespace WPImageCaching
//Erstellen der Abfrage
var wc = (HttpWebRequest)HttpWebRequest.Create(url);
if (item.ImageID!=null)
if (item.ImageID != null)
{
//Prüfen, ob das Bild im Web immer noch aktuell ist
wc.Headers["If-None-Match"] = item.ImageID;
@@ -62,53 +63,103 @@ namespace WPImageCaching
//Bild wurde nicht geändert seit dem letzten Aufruf
if (response.StatusCode == HttpStatusCode.NotModified)
{
Deployment.Current.Dispatcher.BeginInvoke(() => transfer.Image.SetSource(IsolatedStorageFile.GetUserStoreForApplication().OpenFile(transfer.Item.LocalFilename, FileMode.Open)));
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
lock (ImageCache._lock)
{
using (IsolatedStorageFileStream fs =isf.OpenFile(transfer.Item.LocalFilename,FileMode.Open))
{
transfer.Image.SetSource(fs);
}
}
}
});
return;
}
//Hat das Bild eine neue ID?
if (response.Headers["ETag"] != null)
lock (ImageCache._lock)
{
transfer.Item.ImageID = response.Headers["ETag"];
}
else
{
transfer.Item.ImageID = null;
}
//Gibt es ein Ablaufdatum?
if (response.Headers["Expires"] != null)
{
transfer.Item.Expiration = DateTime.Parse(response.Headers["Expires"]);
}
else
{
transfer.Item.Expiration = DateTime.Now.AddDays(EXPIRATIONDAYS);
}
var responseStream = response.GetResponseStream();
//Schreiben der Bilddatei
using (var bw = new BinaryWriter(IsolatedStorageFile.GetUserStoreForApplication().CreateFile(transfer.Item.LocalFilename)))
{
byte[] b = new byte[4096];
int read = 0;
while ((read = responseStream.Read(b, 0, b.Length)) > 0)
string newKey = transfer.WebRequest.RequestUri.ToString();
if (ImageCache.imageCache.ContainsKey(newKey))
{
bw.Write(b, 0, read);
//Setzen des Bildes
Deployment.Current.Dispatcher.BeginInvoke(
() =>
{
using (IsolatedStorageFile ifs = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fs = ifs.OpenFile(transfer.Item.LocalFilename, FileMode.Open))
{
transfer.Image.SetSource(fs);
}
}
});
return;
}
//Hat das Bild eine neue ID?
if (response.Headers["ETag"] != null)
{
transfer.Item.ImageID = response.Headers["ETag"];
}
else
{
transfer.Item.ImageID = null;
}
//Gibt es ein Ablaufdatum?
if (response.Headers["Expires"] != null)
{
transfer.Item.Expiration = DateTime.Parse(response.Headers["Expires"]);
}
else
{
transfer.Item.Expiration = DateTime.Now.AddDays(EXPIRATIONDAYS);
}
var responseStream = response.GetResponseStream();
//Schreiben der Bilddatei
using ( var bw = new BinaryWriter( IsolatedStorageFile.GetUserStoreForApplication().CreateFile(transfer.Item.LocalFilename)) )
{
byte[] b = new byte[4096];
int read = 0;
while ((read = responseStream.Read(b, 0, b.Length)) > 0)
{
bw.Write(b, 0, read);
}
bw.Flush();
bw.Close();
}
//Setzen des Bildes
Deployment.Current.Dispatcher.BeginInvoke(
() =>
{
using (IsolatedStorageFile ifs = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fs = ifs.OpenFile( transfer.Item.LocalFilename,FileMode.Open))
{
transfer.Image.SetSource(fs);
}
}
});
//Hinzufügen der Bildinformationen
if (!ImageCache.imageCache.ContainsKey(newKey))
{
ImageCache.imageCache.Add(newKey, transfer.Item);
//Speichern der Bildinformationen
ImageCache.SaveCachedImageInfo();
}
bw.Flush();
bw.Close();
}
//Setzen des Bildes
Deployment.Current.Dispatcher.BeginInvoke(() => transfer.Image.SetSource(IsolatedStorageFile.GetUserStoreForApplication().OpenFile(transfer.Item.LocalFilename, FileMode.Open)));
//Hinzufügen der Bildinformationen
ImageCache.imageCache.Add(transfer.WebRequest.RequestUri.ToString(), transfer.Item);
//Speichern der Bildinformationen
ImageCache.SaveCachedImageInfo();
}
catch
catch (WebException webException)
{
}
catch (Exception ex)
{
//Nichts machen, da Bild nicht heruntergeladen werden konnte
Debug.WriteLine(ex.ToString());
}
}
//Erstellt einen eindeutigen Namen für das zu ladende Bild
@@ -118,7 +169,7 @@ namespace WPImageCaching
byte[] textToHash = Encoding.UTF8.GetBytes(url);
SHA1Managed sa = new SHA1Managed();
byte[] hash = sa.ComputeHash(textToHash);
return BitConverter.ToString(hash)+extension;
return BitConverter.ToString(hash) + extension;
}
}
//Hilfsklasse für den asynchronen Aufruf
@@ -0,0 +1,21 @@
using Newtonsoft.Json;
namespace WPImageCaching
{
public static class SerializationHelper
{
public static T Deserialize<T>(string serialized)
{
if (string.IsNullOrEmpty(serialized))
return default(T);
return JsonConvert.DeserializeObject<T>(serialized);
}
public static string Serialize<T>(T obj)
{
return JsonConvert.SerializeObject(obj);
}
}
}
@@ -40,8 +40,29 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'GPS_EMULATOR|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\GPS_EMULATOR\</OutputPath>
<DefineConstants>DEBUG;TRACE;SILVERLIGHT;WINDOWS_PHONE</DefineConstants>
<NoStdLib>true</NoStdLib>
<DebugType>full</DebugType>
<PlatformTarget>AnyCPU</PlatformTarget>
<CodeAnalysisLogFile>Bin\Debug\WPImageCaching.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisRuleDirectories>;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
<CodeAnalysisFailOnMissingRules>false</CodeAnalysisFailOnMissingRules>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.Phone" />
<Reference Include="mscorlib" />
<Reference Include="Newtonsoft.Json.WindowsPhone">
<HintPath>..\Json40r1\WindowsPhone\Newtonsoft.Json.WindowsPhone.dll</HintPath>
</Reference>
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Windows" />
<Reference Include="system" />
@@ -55,6 +76,7 @@
<Compile Include="ImageCacheItem.cs" />
<Compile Include="ImageDownloadHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SerializationHelper.cs" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.$(TargetFrameworkProfile).Overrides.targets" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\Silverlight for Phone\$(TargetFrameworkVersion)\Microsoft.Silverlight.CSharp.targets" />