Click here to Skip to main content
11,437,397 members (33,364 online)
Click here to Skip to main content

Tagged as

BitmapImageExtension with NetworkCredentials

, 14 Feb 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
BitmapImageExtension with NetworkCredentials.

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;
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Fredrik Zetterlund
Software Developer (Senior) Empir AB
Sweden Sweden
c# coder with a burning interest of both industrial enviroments and XAML based applications.
Author of several apps for Windows Phone and Win8 such as SqueezeRemote and XBMC Remote and XBMC RT Remote.
Follow on   Twitter

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150428.2 | Last Updated 14 Feb 2013
Article Copyright 2013 by Fredrik Zetterlund
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid