My name is Edward Tanguay. I'm an American software and web developer living and working in Berlin, Germany.

Code base for loading and caching external data into a silverlight app This code is a nice start if you need a one-page silverlight control or application which loads text asynchronously and then caches it in IsolatedStorage so that the next time the user visits, the data is there. There is a clear cache button so that the data gets loaded again. ![]() > > > Download Code XAML:
<UserControl x:Class="TestLoadCache.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"> <StackPanel Margin="10"> <TextBlock Text="{Binding Message}" Margin="0 0 0 10"/> <StackPanel HorizontalAlignment="Left" Orientation="Horizontal" Margin="0 0 0 10"> <Button Content="Load Text" Click="Button_LoadText_Click" Margin="0 0 5 0"/> <Button Content="Clear Isolated" Click="Button_ClearIsolatedStorage_Click" Margin="0 0 5 0"/> </StackPanel> <TextBlock Text="{Binding LoadedText}" Margin="0 0 0 10"/> </StackPanel> </UserControl> Code Behind:
using System;
using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.ComponentModel; using System.IO.IsolatedStorage; using System.IO; namespace TestLoadCache { public partial class MainPage : UserControl, INotifyPropertyChanged { #region ViewModelProperty: Message private string _message; public string Message { get { return _message; } set { _message = value; OnPropertyChanged("Message"); } } #endregion . #region ViewModelProperty: LoadedText private string _loadedText; public string LoadedText { get { return _loadedText; } set { _loadedText = value; OnPropertyChanged("LoadedText"); } } #endregion . public MainPage() { InitializeComponent(); DataContext = this; } private void Button_ClearIsolatedStorage_Click(object sender, RoutedEventArgs e) { FileHelpers.ClearIsolatedStorage(); Message = "IsolatedStorage cleared."; LoadedText = ""; } private void Button_LoadText_Click(object sender, RoutedEventArgs e) { string url = "http://test.development:1111/testdata/test.txt".EnsureNoncachingForUrl(); string isolatedStorageText = FileHelpers.LoadTextFromIsolatedStorageFile(url.ConvertUrlToFileName()); if (!String.IsNullOrEmpty(isolatedStorageText)) { LoadedText = isolatedStorageText; Message = "Text loaded from isolated storage."; } else { Message = "Loading from server..."; WebClient webClientTextLoader = new WebClient(); webClientTextLoader.DownloadStringAsync(new Uri(url), url); webClientTextLoader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClientTextLoader_DownloadStringCompleted); } } void webClientTextLoader_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { string url = e.UserState.ToString(); string loadedText = e.Result; FileHelpers.SaveTextToIsolatedStorageFile(loadedText, url.ConvertUrlToFileName()); LoadedText = loadedText; Message = "Text loaded from external site. "; } #region INotifiedProperty Block public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } #endregion . } public static class StringHelpers { public static string EnsureNoncachingForUrl(this string url) { int randomNumber = MathHelpers.GetRandomNumber(100000, 999999); if (!url.Contains("?")) return url + "?" + randomNumber; else return url + "&" + randomNumber; } /// <summary> /// converts e.g. http://test.development:11111/testdata/test.png?283748347 to httptestdevelopment22222testdatatestpng /// </summary> /// <param name="url"></param> /// <returns></returns> public static string ConvertUrlToFileName(this string url) { List<string> parts = url.BreakIntoParts("?"); string returnString = parts[0]; List<string> deletionCharacters = new List<string> { ":", "/", "." }; foreach (var deletionCharacter in deletionCharacters) { returnString = returnString.Replace(deletionCharacter, ""); } return returnString; } public static List<string> BreakIntoParts(this string line, string separator) { if (String.IsNullOrEmpty(line)) return null; else { return line.Split(new string[] { separator }, StringSplitOptions.None).Select(p => p.Trim()).ToList(); } } } public static class MathHelpers { private static Random random = new Random(); public static int GetRandomNumber(int min, int max) { return random.Next(min, max + 1); } } public static class FileHelpers { public static bool SaveTextToIsolatedStorageFile(string text, string fileName) { using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Create, isf)) { using (StreamWriter sw = new StreamWriter(isfs)) { try { sw.Write(text); } catch (IsolatedStorageException ex) { return false; } finally { sw.Close(); } } } return true; } } public static string LoadTextFromIsolatedStorageFile(string fileName) { string text = String.Empty; using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { if (!isf.FileExists(fileName)) return ""; using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(fileName, FileMode.Open, isf)) { using (StreamReader sr = new StreamReader(isfs)) { string lineOfData = String.Empty; while ((lineOfData = sr.ReadLine()) != null) text += lineOfData + Environment.NewLine; } } return text; } } public static void ClearIsolatedStorage() { using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication()) { string[] fileNames = isf.GetFileNames(); foreach (var fileName in fileNames) { isf.DeleteFile(fileName); } } } } } |
Most Recently Added Items:
- How to call an unknown function on an unknown class with unknown parameters - php code example - added on Sunday, November 28, 2010
- How to setup JQuery intellisense in Microsoft Visual Web Developer 2010 Express - jquery howto - added on Sunday, November 14, 2010
- Simple menu site with jQuery AJAX - jquery code example - added on Sunday, November 14, 2010
- A PHP function which returns the most frequently occuring item - php code example - added on Friday, October 29, 2010
- How to create a singleton in PHP - php code example - added on Sunday, October 03, 2010
- Extension method to sort a generic collection of objects - c# code example - added on Tuesday, September 07, 2010
- A simple class that represents a matching quiz item - c# code example - added on Tuesday, September 07, 2010
- Extension method for checking regex in one line - c# code example - added on Thursday, September 02, 2010
- How to use a Dictionary<> with struct key to save a dynamic matrix of objects - c# code example - added on Sunday, August 22, 2010
- A simple jquery search machine for a web page - jquery code example - added on Sunday, August 22, 2010
- Wrapper class to simplify the creation of Excel files in C# 4.0 - wpf code example - added on Tuesday, July 20, 2010
- How to make clickable flashcards in plain javascript for your mobile phone - javascript code example - added on Wednesday, July 07, 2010
- Simple example of javascript which loads jquery locally - jquery code example - added on Wednesday, July 07, 2010
- How to stop regular expression greediness - c# code example - added on Tuesday, July 06, 2010
- How to use a generic dictionary to total enum values - c# code example - added on Friday, July 02, 2010
- Generic method to case-insensitively convert a string to any enum - c# code example - added on Friday, July 02, 2010
- How to create a TextBlock that has various font formatting in code behind - silverlight code example - added on Wednesday, June 30, 2010
- How to encode binary files to text files and back to binary again - c# code example - added on Wednesday, June 30, 2010
- How to use a custom parameter struct to pass any number of variables to constructors of similar classes. - c# code example - added on Saturday, June 26, 2010
- How to make a class that renders an interactive FrameworkElement and interacts with the View - silverlight code example - added on Tuesday, June 15, 2010
- How to set a nullable type to null in a ternary operator - c# code example - added on Tuesday, June 15, 2010
- How to override events in inherited classes - c# code example - added on Friday, June 11, 2010
- How to strip off e.g. "note:" and "firstName: " from the left of a string using regex - c# code example - added on Tuesday, June 01, 2010
- How to create and subscribe to custom events using EventHandler - c# code example - added on Wednesday, May 12, 2010
- Code base for asynchronously loading and caching dependent data in a Silverlight app - silverlight code example - added on Wednesday, May 05, 2010
- Function to trim the preceding and trailing blank lines off an array - php code example - added on Sunday, May 02, 2010
- How to load and display the contents of a text file with AJAX/Jquery - jquery code example - added on Sunday, May 02, 2010
- How to use fopen() to create a proxy site to read any website content into AJAX - php code example - added on Sunday, May 02, 2010
- Code base for loading and caching external data into a silverlight app - silverlight code example - added on Friday, April 30, 2010
- An UpdateSourceTrigger workaround for Silverlight - wpf code example - added on Sunday, April 18, 2010
