Windows Phone 7 (WP 7) – Download, Store and Play Media files from Isolated Storage

Posted by: Mahesh Sabnis , on 10/6/2010, in Category Windows Phone
Views: 77105
Abstract: In this article, I will be explaining how to do HTTP downloads using WP7 application. Once the content is downloaded, it can be stored in the isolated storage to be used later.
In this article, I will be explaining how to do HTTP downloads using WP7 application. Once the content is downloaded, it can be stored in the isolated storage to be used later.
Isolated storage is a data storage mechanism that provides isolation and safety by defining standardized ways of associating code with saved data. As far as programming with it is concerned, the following classes are provided to be used in WP7:
·         IsolatedStorageFileStream: Exposes file within isolated storage.
·         IsolatedStorageFile: Represents area containing files and dictionaries.
To accommodate the downloaded resources for the example we will just see, I have programmatically increased the isolated storage file space. In this article, I have used VS2010 (the only IDE used for WP 7 programming) and a Web Service targeted to .NET Framework 3.5.
Update: VB.NET developers take note that there is a Visual Basic CTP for Windows Phone Developer Tools now available. Read the annoucement here.
Task 1: Creating Web Service
 
Step 1: Open Vs2010 and create blank solution, name it as ‘WP7_DownloadMediaFile’. In this solution, add a Web Service project and name it as ‘MediaWebService’.
Step 2: In the web service project, add a new folder and name it as ‘Videos’. In this folder add some ‘.wmv’ files. (You can add any .wmv files of the size not more than 18-19 MB. The size is a limitation here because of the isolated storage space provided on WP7. We will talk about it in Task 2).
Step 3: Publish the Web Service on IIS (recommended).
 
Task 2: Creating WP 7 application
 
Step 1: In the solution created in the Task 1, add a new WP7 application project and name it as ‘WP7_DownloadMediaFile’.
Step 2: Open MainPage.Xaml and write the following code in ‘TitlePanel’ StackPanel element:
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="Play Media" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="Media Library" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>
In the ‘ContentPanel’ Grid element, write the following XAML (you can also do Drag-Drop from the Toolbox)
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <Button Content="Download" Height="72" HorizontalAlignment="Left" Margin="6,6,0,0" Name="btnDownload" VerticalAlignment="Top" Width="427" Click="btnDownload_Click" />
    <MediaElement Height="421" HorizontalAlignment="Left" Margin="12,100,0,0" Name="mediaFile" VerticalAlignment="Top" Width="421" MediaEnded="mediaFile_MediaEnded" />
    <ProgressBar Height="41" HorizontalAlignment="Left" Margin="13,537,0,0" Name="progressMedia" VerticalAlignment="Top" Width="423" />
</Grid>
 
Note: Ignore the events attached to the controls here. We will see them shortly.
The UI Design will be as below:
WP7Emulator
Step 3: Open MainPage.Xaml.cs and declare following objects at class level:
C#
IsolatedStorageFileStream isolatedStorageFileStream;
IsolatedStorageFile isolatedStorageFile;
 
VB.NET (Converted Code)
Dim isolatedStorageFileStream_Renamed As IsolatedStorageFileStream
Dim isolatedStorageFile_Renamed As IsolatedStorageFile
 
In the ‘Download’ button click event, write the following code:
C#
private void btnDownload_Click(object sender, RoutedEventArgs e)
{
    WebClient webClient = new WebClient();
    webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
    webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
    webClient.OpenReadAsync(new Uri("http://localhost:8001/WP7_MediaVd/Videos/Lookout.wmv"));
}
 
 
VB.NET (Converted Code)
Private Sub btnDownload_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      Dim webClient As New WebClient()
      AddHandler webClient.DownloadProgressChanged, AddressOf webClient_DownloadProgressChanged
      AddHandler webClient.OpenReadCompleted, AddressOf webClient_OpenReadCompleted
      webClient.OpenReadAsync(New Uri("http://localhost:8001/WP7_MediaVd/Videos/Lookout.wmv"))
End Sub
The above code makes use of ‘WebClient’ class which is present under ‘System.Net’ namespace. This class is used to perform Asynchronous Upload and Download operations.
Implement the ‘webClient_DownloadProgressChanged’ method. This method will be used to indicate the download progress (UX) to the end user using ProgressBar control.
C#
void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    try
    {
        if (progressMedia.Value <= progressMedia.Maximum)
        {
            progressMedia.Value = (double)e.ProgressPercentage;
        }
 
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
 
VB.NET (Converted Code)
Private Sub webClient_DownloadProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
      Try
            If progressMedia.Value <= progressMedia.Maximum Then
                  progressMedia.Value = CDbl(e.ProgressPercentage)
            End If
 
      Catch ex As Exception
            MessageBox.Show(ex.Message)
      End Try
End Sub
Now it is time to read the downloaded media file and play it using the ‘MediaElement’. However here I am using the Isolated Storage of WP7 for storing the downloaded file, so I must demand an increased space in the Isolated Storage to store the file. Thus here I have implemented the following method which will return a ‘Boolean’ value. The value will be ‘True’ is the quota can be increased.
C#
protected bool IncreaseIsolatedStorageSpace(long quotaSizeDemand)
{
    bool CanSizeIncrease = false;
    IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();
    //Get the Available space
    long maxAvailableSpace = isolatedStorageFile.AvailableFreeSpace;
    if (quotaSizeDemand > maxAvailableSpace)
    {
        if (!isolatedStorageFile.IncreaseQuotaTo(isolatedStorageFile.Quota + quotaSizeDemand))
        {
            CanSizeIncrease = false;
            return CanSizeIncrease;
        }
        CanSizeIncrease = true;
        return CanSizeIncrease;
    }
    return CanSizeIncrease;
}
 
VB.NET (Converted Code)
Protected Function IncreaseIsolatedStorageSpace(ByVal quotaSizeDemand As Long) As Boolean
      Dim CanSizeIncrease As Boolean = False
      Dim isolatedStorageFile As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
      'Get the Available space
      Dim maxAvailableSpace As Long = isolatedStorageFile.AvailableFreeSpace
      If quotaSizeDemand > maxAvailableSpace Then
            If Not isolatedStorageFile.IncreaseQuotaTo(isolatedStorageFile.Quota + quotaSizeDemand) Then
                  CanSizeIncrease = False
                  Return CanSizeIncrease
            End If
            CanSizeIncrease = True
            Return CanSizeIncrease
      End If
      Return CanSizeIncrease
End Function
This above method is very important. It accepts a ‘long’ as an input parameter which represents the downloaded file size and based upon this size, the isolated storage quota is demanded. The ‘AvailableFreeSpace’ property of the ‘IsolatedStorageFile’ class returns the available space for the isolated storage. If the demanded size is more than the available space, then the quota cannot be increased.
The code shown below writes the downloaded file into the Isolated Storage and then plays it using the ‘mediaFile’ MediaElement.  If the quota cannot be increased, then a message can be displayed to the user.
C#
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    try
    {
        if (e.Result != null)
        {
 
            #region Isolated Storage Copy Code
            isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();
 
            bool checkQuotaIncrease = IncreaseIsolatedStorageSpace(e.Result.Length);
 
            string VideoFile = "PlayFile.wmv";
            isolatedStorageFileStream = new IsolatedStorageFileStream(VideoFile, FileMode.Create, isolatedStorageFile);
            long VideoFileLength = (long)e.Result.Length;
            byte[] byteImage = new byte[VideoFileLength];
            e.Result.Read(byteImage, 0, byteImage.Length);
            isolatedStorageFileStream.Write(byteImage, 0, byteImage.Length);
 
            #endregion
 
            mediaFile.SetSource(isolatedStorageFileStream);
            mediaFile.Play();
            progressMedia.Visibility = Visibility.Collapsed;
 
 
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
 
VB.NET (Converted Code)
Imports Microsoft.VisualBasic
 
Private Sub webClient_OpenReadCompleted(ByVal sender As Object, ByVal e As OpenReadCompletedEventArgs)
      Try
            If e.Result IsNot Nothing Then
 
'                 #Region "Isolated Storage Copy Code"
                  isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
 
                  Dim checkQuotaIncrease As Boolean = IncreaseIsolatedStorageSpace(e.Result.Length)
 
                  Dim VideoFile As String = "PlayFile.wmv"
                  isolatedStorageFileStream = New IsolatedStorageFileStream(VideoFile, FileMode.Create, isolatedStorageFile)
                  Dim VideoFileLength As Long = CLng(Fix(e.Result.Length))
                  Dim byteImage(VideoFileLength - 1) As Byte
                  e.Result.Read(byteImage, 0, byteImage.Length)
                  isolatedStorageFileStream.Write(byteImage, 0, byteImage.Length)
 
'                 #End Region
 
                  mediaFile.SetSource(isolatedStorageFileStream)
                  mediaFile.Play()
                  progressMedia.Visibility = Visibility.Collapsed
 
 
            End If
      Catch ex As Exception
            MessageBox.Show(ex.Message)
      End Try
End Sub
 
Now it is the time to provide the end user the facility to decide whether the file is to be replayed or otherwise removed from the storage.
C#
private void mediaFile_MediaEnded(object sender, RoutedEventArgs e)
{
    MessageBoxResult res = MessageBox.Show("Do you want to Replay the file", "Decide", MessageBoxButton.OKCancel);
 
    if (res == MessageBoxResult.OK)
    {
        mediaFile.Play();
    }
    else
    {
        isolatedStorageFileStream.Close();
        isolatedStorageFile.Dispose();
        mediaFile.ClearValue(MediaElement.SourceProperty);
    }
}
 
VB.NET (Converted Code)
private void mediaFile_MediaEnded(object sender, RoutedEventArgs e)
{
    MessageBoxResult res = MessageBox.Show("Do you want to Replay the file", "Decide", MessageBoxButton.OKCancel);
 
    if (res == MessageBoxResult.OK)
    {
        mediaFile.Play();
    }
    else
    {
        isolatedStorageFileStream.Close();
        isolatedStorageFile.Dispose();
        mediaFile.ClearValue(MediaElement.SourceProperty);
    }
}
 
Step 4: Run the application and click on download
WP7_Emulator_Running_File
After the video has been played, the following Message box will be displayed
Emulator_Running_File_Demand
If the end user clicks on yes, the file will start running again, otherwise it will be flushed from the storage.
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Ranjan Deo on Friday, November 12, 2010 4:50 AM
How i can refer a file stored in isolated storage.
I mean what would be the absolute path of the stored file?

Is there any way to create some text file in my applciation?
Comment posted by Mahesh Sabnis on Tuesday, November 23, 2010 2:03 AM
The path in the isolated storage of WP7 is not known to me also, since the enulator is locked it is difficult.
Comment posted by Jason on Saturday, December 18, 2010 2:10 AM
nice article...  the last part of VB.NET (Converted Code)
code is showing as the c# code
Comment posted by Shawn Wildermuth on Sunday, January 30, 2011 7:14 PM
If the songs are on the Internet already, XNA's Song class makes this easier IMHO.
Comment posted by Phil Farrand on Saturday, March 5, 2011 8:44 AM
Excellent article! Very useful. Thanks for your work.
Comment posted by Ravi on Tuesday, March 22, 2011 12:59 AM
Hey Mahesh,  very good article
i am using same code for the same purpose
but i am facing a problem that video does not get started and progress changed completed
i am not getting why this is happening
kindly suggest me
Comment posted by MxMxM on Thursday, April 7, 2011 11:20 PM
Can I copy a video from Media library my app isolatedStorage?
Comment posted by Dario on Thursday, February 2, 2012 9:33 AM
Hello,
Could you please provide a sample project?
Thank you :)
Comment posted by Panda on Saturday, August 18, 2012 12:56 AM
Could you please provide a sample project?
Comment posted by Siva on Monday, May 20, 2013 7:47 AM
Nice Article,
Could you please provide a sample project?
Thank u,...
Comment posted by Nguyễn Hữu Tuấn on Tuesday, January 7, 2014 8:08 AM
Nice article,
But for details, I don't know that can I download any file video with this codes? For example, How I can download a large file .flv rapidly. Please, could you show me?
Comment posted by Rahul on Tuesday, April 29, 2014 1:44 AM
Sir,,  How to Use multiple url for download..one by one
Comment posted by LekshmiPriya R S on Monday, July 14, 2014 6:15 AM
hi sir

Could you please provide a project related windows phone 8 sdk

Thanks
Comment posted by Suprotim Agarwal on Monday, July 14, 2014 9:26 AM
@LekshmiPriya Check this http://www.dotnetcurry.com/ShowArticle.aspx?ID=1005
Comment posted by vinay on Wednesday, October 1, 2014 3:36 AM
Sir I am new in wp7 . I want to ask one question to you i made one application in wp7 in that application i want to upload a pdf file or text file or jpg image but browse control is not there in toolbo what control should be used to upload a these file i am very worry please tell me if any information is there regarding to my problem .

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel