Introduction
This code extension allows for a BitmapImage
to use a remote image as source which requires NetworkCredentials
in WinRT.
Background
When I started writing an app which uses files on a remote computer which uses Basic network authentication I had to find a way of databind to these images. This is what I came up with.
Using the code
Basic Usage
The basic use of this extension is simple,. Create your
BitmapImage
and you will find two new overloads of the SetSourceAsync
method.
var thumbnailSoure = new BitmapImage();
thumbnailSoure.SetSourceAsync("http://example.url/Images/NoAccess.jpg",
"Username", "Password");
Databinding
A basic way of implementing databinding to a source which requires NetworkCredentials
:
<Image Source="{Binding ThumbnailSource}" />
private BitmapImage thumbnailSoure;
public BitmapImage ThumbnailSource
{
get
{
if (thumbnailSoure == null)
{
thumbnailSoure = new BitmapImage();
thumbnailSoure.SetSourceAsync("http://example.url/Images/NoAccess.jpg",
"Username", "Password");
}
return thumbnailSoure;
}
}
The Extension
Just add this class into your project
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Windows.Storage.Streams;
namespace Windows.UI.Xaml.Media.Imaging
{
public static class BitmapImageExtensions
{
public static async Task<bool> SetSourceAsync(this BitmapImage image,
string url, string username, string password)
{
return await image.SetSourceAsync(new Uri(url), username, password);
}
public static async Task<bool> SetSourceAsync(this BitmapImage image,
Uri uri, string username, string password)
{
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = new NetworkCredential(username, password);
request.Method = "GET";
request.Accept = "image/gif;q=0.3, image/x-xbitmap;q=0.3, " +
"image/jpeg;q=0.3, image/pjpe;q=0.3g, image/png;q=0.3";
try
{
var response = await request.GetResponseAsync();
if (response != null)
{
Stream stream = response.GetResponseStream();
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
var randomAccessStream = await ConvertToRandomAccessStream(ms);
await image.SetSourceAsync(randomAccessStream);
return true;
}
}
catch
{
return false;
}
return false;
}
private static async Task<IRandomAccessStream> ConvertToRandomAccessStream(MemoryStream memoryStream)
{
var randomAccessStream = new InMemoryRandomAccessStream();
var outputStream = randomAccessStream.GetOutputStreamAt(0);
var dw = new DataWriter(outputStream);
var task = Task.Factory.StartNew(() => dw.WriteBytes(memoryStream.ToArray()));
await task;
await dw.StoreAsync();
await outputStream.FlushAsync();
return randomAccessStream;
}
}
}