|
|
Demonstrated issues:
Prerequisities:
Steps:
<UserControl
x:Class="IsolatedStorage.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
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"
>
<UserControl.Resources>
<Style x:Name="GridSplitterStyle" TargetType="controls:GridSplitter">
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="Width" Value="3"/>
<Setter Property="Background" Value="Black"/>
</Style>
<Style x:Name="ButtonStyle" TargetType="Button">
<Setter Property="Margin" Value="2"/>
</Style>
</UserControl.Resources>
<Border
Background="AntiqueWhite"
BorderBrush="Black"
BorderThickness="1"
CornerRadius="5"
Margin="5"
Padding="5"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<controls:GridSplitter
Grid.Column="1"
Style="{StaticResource GridSplitterStyle}"
/>
<controls:GridSplitter
Grid.Column="3"
Style="{StaticResource GridSplitterStyle}"
/>
</Grid>
</Border>
</UserControl>
<StackPanel
Grid.Row="1"
Grid.ColumnSpan="5"
Orientation="Horizontal"
>
<TextBox
x:Name="DirectoryNameTextBox"
Width="100"
Margin="2,2,0,2"
/>
<Button
x:Name="CreateDirectoryButton"
Style="{StaticResource ButtonStyle}"
Content="Create directory"
Click="CreateDirectoryButton_Click"
/>
<Button
x:Name="AddFileButton"
Style="{StaticResource ButtonStyle}"
Content="Add file"
Click="AddFileButton_Click"
/>
<Button
x:Name="GetFileButton"
Style="{StaticResource ButtonStyle}"
Content="Get file"
IsEnabled="False"
Click="GetFileButton_Click"
/>
<Button
x:Name="DeleteFileButton"
Style="{StaticResource ButtonStyle}"
Content="Delete file"
IsEnabled="False"
Click="DeleteFileButton_Click"
/>
</StackPanel>
<controls:TreeView
x:Name="DirectoriesTreeView"
>
<controls:TreeViewItem
x:Name="RootDirectoriesTreeViewItem"
Header="[root]"
Tag=""
IsSelected="True"
/>
</controls:TreeView>
private TreeViewItem CreateTreeViewItem(string name, string path, TreeViewItem parentItem)
{
var item = new TreeViewItem {Header = name, Tag = path};
parentItem.Items.Add(item);
parentItem.IsExpanded = true;
return item;
}
private void CreateDirectoryButton_Click(object sender, RoutedEventArgs e)
{
TreeViewItem selectedItem = (TreeViewItem)DirectoriesTreeView.SelectedItem;
if (selectedItem == null)
{
MessageBox.Show("The parent directory must be selected");
}
else
{
string parentPath = (string) selectedItem.Tag;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
string path = Path.Combine(parentPath, DirectoryNameTextBox.Text);
store.CreateDirectory(path);
CreateTreeViewItem(DirectoryNameTextBox.Text, path, selectedItem);
}
}
}
public MainPage()
{
InitializeComponent();
PrepareTreeForIsolatedStorage();
}
private void PrepareTreeForIsolatedStorage()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
PrepareTreeForDirectory(store, RootDirectoriesTreeViewItem, "");
}
}
private void PrepareTreeForDirectory(IsolatedStorageFile store, TreeViewItem item, string path)
{
string[] dirs = store.GetDirectoryNames(Path.Combine(path, "*"));
foreach (string dir in dirs)
{
string dirPath = Path.Combine(path, dir);
TreeViewItem dirItem = CreateTreeViewItem(dir, dirPath, item);
PrepareTreeForDirectory(store, dirItem, dirPath);
}
}
<ListBox
x:Name="FilesListBox"
Grid.Column="2"
SelectionChanged="FilesListBox_SelectionChanged"
/>
private void DirectoriesTreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
if (DirectoriesTreeView != null && DirectoriesTreeView.SelectedItem != null)
{
string path = (string)((TreeViewItem)DirectoriesTreeView.SelectedItem).Tag;
ListFiles(path);
}
}
private void ListFiles(string path)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] files = store.GetFileNames(Path.Combine(path, "*.*"));
FilesListBox.ItemsSource = files;
}
}
private void AddFileButton_Click(object sender, RoutedEventArgs e)
{
if (DirectoriesTreeView.SelectedItem == null)
{
MessageBox.Show("The target directory must be selected");
}
else
{
string dirPath = (string)((TreeViewItem)DirectoriesTreeView.SelectedItem).Tag;
var openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
FileInfo fileInfo = openFileDialog.File;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
Stream loadStream = fileInfo.OpenRead();
string filePath = Path.Combine(dirPath, fileInfo.Name);
IsolatedStorageFileStream saveStream = store.CreateFile(filePath);
CopyStream(loadStream, saveStream);
saveStream.Close();
loadStream.Close();
}
ListFiles(dirPath);
}
}
}
private void CopyStream(Stream loadStream, Stream saveStream)
{
const int bufferSize = 1024 * 1024;
byte[] buffer = new byte[bufferSize];
int count = 0;
while ((count = loadStream.Read(buffer, 0, bufferSize)) > 0)
{
saveStream.Write(buffer, 0, count);
}
}
var openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == false)
{
FileInfo fileInfo = openFileDialog.File;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (fileInfo.Length > store.AvailableFreeSpace)
{
if (!store.IncreaseQuotaTo(store.Quota + fileInfo.Length - store.AvailableFreeSpace))
{
MessageBox.Show("Increasing quota rejected");
return;
}
}
Stream loadStream = fileInfo.OpenRead();
string filePath = Path.Combine(dirPath, fileInfo.Name);
IsolatedStorageFileStream saveStream = store.CreateFile(filePath);
CopyStream(loadStream, saveStream);
saveStream.Close();
loadStream.Close();
}
ListFiles(dirPath);
}
private void IncreaseIsolatedStorageButton_Click(object sender, RoutedEventArgs e)
{
const int requiredFreeSpace = 10 * 1024 * 1024;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.AvailableFreeSpace < requiredFreeSpace)
{
store.IncreaseQuotaTo(store.Quota + requiredFreeSpace - store.AvailableFreeSpace);
}
}
}
<ScrollViewer
Grid.Column="4"
HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Auto"
>
<Image
x:Name="PreviewImage"
Stretch="None"
/>
</ScrollViewer>
private string GetSelectedFilePath()
{
string path = null;
if (FilesListBox.SelectedItem != null || DirectoriesTreeView.SelectedItem != null)
{
path = Path.Combine(
(string) ((TreeViewItem) (DirectoriesTreeView.SelectedItem)).Tag,
(string) FilesListBox.SelectedItem);
}
return path;
}
private void FilesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string path = GetSelectedFilePath();
if (path != null)
{
DeleteFileButton.IsEnabled = true;
GetFileButton.IsEnabled = true;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
var stream = store.OpenFile(path, FileMode.Open);
try
{
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(stream);
PreviewImage.Source = bitmapImage;
}
catch (Exception)
{
PreviewImage.Source = null;
}
stream.Close();
}
}
else
{
DeleteFileButton.IsEnabled = false;
GetFileButton.IsEnabled = false;
}
}
private void DeleteFileButton_Click(object sender, RoutedEventArgs e)
{
string path = GetSelectedFilePath();
if (path != null)
{
if (MessageBox.Show(
string.Format("Confirm deleting the file:\n {0}", path),
"Deleting Confirmation",
MessageBoxButton.OKCancel) == MessageBoxResult.OK)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
store.DeleteFile(path);
}
string dirPath = (string) ((TreeViewItem) DirectoriesTreeView.SelectedItem).Tag;
ListFiles(dirPath);
}
}
}
private void GetFileButton_Click(object sender, RoutedEventArgs e)
{
string path = GetSelectedFilePath();
if (path != null)
{
var saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog().Value)
{
Stream saveStream = saveFileDialog.OpenFile();
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
var loadStream = store.OpenFile(path, FileMode.Open, FileAccess.Read);
CopyStream(loadStream, saveStream);
loadStream.Close();
}
saveStream.Close();
}
}
}
public App()
{
this.Startup += this.Application_Startup;
this.Exit += this.Application_Exit;
this.UnhandledException += this.Application_UnhandledException;
InitializeComponent();
}
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
// If the app is running outside of the debugger then report the exception using
// the browser's exception mechanism. On IE this will display it a yellow alert
// icon in the status bar and Firefox will display a script error.
if (!System.Diagnostics.Debugger.IsAttached)
{
// NOTE: This will allow the application to continue running after an exception has been thrown
// but not handled.
// For production applications this error handling should be replaced with something that will
// report the error to the website and stop the application.
e.Handled = true;
Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
}
}
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
{
try
{
string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");
System.Windows.Browser.HtmlPage.Window.Eval(
"throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
}
catch (Exception)
{
}
}