Tuesday, February 5, 2013

Windows Phone Downloading Image to ISOLATED-STORE

I was working on a demo application for downloading an image to isolated store for this purpose we need to follow just few steps. We just need to make a project with name IsolatedStorageStoreImageDemo and copy the below given code to

MainPage.xaml


<phone:PhoneApplicationPage 
    x:Class="IsolatedStorageStoreImageDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <Grid x:Name="LayoutRoot" Background="{StaticResource PhoneBackgroundBrush}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <!--TitleGrid is the name of the application and page title-->
        <Grid x:Name="TitleGrid" Grid.Row="0">
            <TextBlock Text="IsolatedStorageStoreImageDemo"
x:Name="textBlockPageTitle"
Style="{StaticResource PhoneTextTitle1Style}"
FontSize="28" />
        </Grid>
        <!--ContentGrid is empty. Place new content here-->
        <Grid x:Name="ContentGrid" Grid.Row="1">

            <Image Height="458" HorizontalAlignment="Left"
Margin="20,134,0,0" Name="image1" Stretch="Uniform"
VerticalAlignment="Top" Width="423" />
            <Button Content="Get Image" Height="70"
HorizontalAlignment="Left" Margin="0,598,0,0"
Name="btnGetImage" VerticalAlignment="Top"
Width="443" Click="btnGetImage_Click" />
            <TextBox Height="72" HorizontalAlignment="Left"
Margin="12,29,0,0" Name="txtImageUrl"
Text="http://res1.newagesolution.net/Portals/0/twitter2_icon.jpg"
VerticalAlignment="Top" Width="460" />
        </Grid>
    </Grid>
</phone:PhoneApplicationPage>

MainPage.xaml.cs code is given below


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 Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;


namespace IsolatedStorageStoreImageDemo
{
    public partial class MainPage : PhoneApplicationPage
    {
        private string ImageFileName = null;
        WebClient _webClient;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
           
            SupportedOrientations = SupportedPageOrientation.Portrait |
            SupportedPageOrientation.Landscape;
            _webClient = new WebClient();
            // Handles when the image download is completed
            _webClient.OpenReadCompleted += (s1, e1) =>
            {
                if (e1.Error == null)
                {
                    try
                    {
                        bool isSpaceAvailable =
                        IsSpaceIsAvailable(e1.Result.Length);
                        if (isSpaceAvailable)
                        {
                            // Save Image file to Isolated Storage
                            using (IsolatedStorageFileStream isfs =
                            new IsolatedStorageFileStream(ImageFileName,
                            FileMode.Create,
                            IsolatedStorageFile.GetUserStoreForApplication()))
                            {

                            
                                long imgLen = e1.Result.Length;
                                byte[] b = new byte[imgLen];
                                e1.Result.Read(b, 0, b.Length);
                                isfs.Write(b, 0, b.Length);
                                isfs.Flush();
                            }
                            LoadImageFromIsolatedStorage(ImageFileName);
                        }
                        else
                        {
                            BitmapImage bmpImg = new BitmapImage();
                            bmpImg.SetSource(e1.Result);
                            image1.Source = bmpImg;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            };
        }
        private bool IsSpaceIsAvailable(long spaceReq)
        {
            using (IsolatedStorageFile store =
            IsolatedStorageFile.GetUserStoreForApplication())
            {
                long spaceAvail = store.AvailableFreeSpace;
                if (spaceReq > spaceAvail)
                {
                    return false;
                }
                return true;
            }
        }
        private void btnGetImage_Click(object sender, RoutedEventArgs e)
        {
            using (IsolatedStorageFile isf =
            IsolatedStorageFile.GetUserStoreForApplication())
            {
                bool fileExist = isf.FileExists(ImageFileName);
                if (fileExist)
                {
                    LoadImageFromIsolatedStorage(ImageFileName);
                }
                else
                {
                    if (!string.IsNullOrEmpty(txtImageUrl.Text))
                    {
                        // Use Uri as image file name
                        Uri uri = new Uri(txtImageUrl.Text);
                        ImageFileName = "jitesh.jpg";
                        _webClient.OpenReadAsync(new Uri(txtImageUrl.Text));
                    }
                }
            }
        }
        private void LoadImageFromIsolatedStorage(string imageFileName)
        {
            // Load Image from Isolated storage
            using (IsolatedStorageFile isf =
            IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream isoStream =
                isf.OpenFile(imageFileName, FileMode.Open))
                {
                    BitmapImage bmpImg = new BitmapImage();
                    bmpImg.SetSource(isoStream);
                    image1.Source = bmpImg;
                }
            }
        }
    }
}


you can observe the result on clicking the "Get Image" button


you can download the source code from the given below link IsolatedStorageStoreImageDemo




No comments:

Post a Comment