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.
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:
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
After the video has been played, the following Message box will be displayed
If the end user clicks on yes, the file will start running again, otherwise it will be flushed from the storage.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn