Friday, September 29, 2017

UWP Tip #7 - UWP Community Toolkit - Part 5, Using the Streams Code Helper

Welcome back to the UWP Community Toolkit series. Previous Tips in the UWP Community Toolkit series:

Introduction

This tip will continue exploring the Code Helpers that we started looking at in Part 3. There are three types of helpers remaining, and today we will examine the StreamHelper class.

Purpose

The StreamHelper class contains methods to read files from a stream via local files or via a network stream. There is also a helper method to read data from an http source and write it directly to a local file. There are also some helper methods to check if files and folders exist for a given name and path.

Let's look at a few of the method signatures:

  • GetHttpStreamAsync(System.Uri uri) - Gets a stream from an HTTP request.
  • IsLocalFileExistsAsync(System.String fileName) - Checks if a local files exists in the application's folder.
  • IsLocalCacheFileExistsAsync(System.String fileName) - Checks if a local file exists in the cache folder.
  • ReadTextAsync(Windows.Storage.Streams.IRandomAccessStream stream,System.Text.Encoding encoding) - Takes a stream and reads it to a returned string.

Example

In this short example, we are going to create a StreamService for our project that implements an IStreamService interface for testability. Although the lack of an interface for the toolkit's StreamHelper makes it a little tricky to mock this for our tests. We'll leave this for another day or perhaps an issue to be filed on their GitHub.

The StreamService has two methods, one for getting a string back from and HTTP call and another to get one from reading a file in the local cache.

public class StreamService : IStreamService
{
    public async Task<string> GetStringFromUrlAsync(Uri source)
    {
        using (var stream = await StreamHelper.GetHttpStreamAsync(source))
        {
            return await stream.ReadTextAsync();
        }
    }
     public async Task<string> GetStringFromLocalCacheAsync(string fileName)
    {
        using (var stream = await StreamHelper.GetLocalCacheFileStreamAsync(fileName, Windows.Storage.FileAccessMode.Read))
        {
            return await stream.ReadTextAsync();
         }
    }
}

Everything is wrapped up with only strings and a Uri in and out, keeping the external dependency out of our ViewModels. To check out all of the available helper methods in the StreamHelper class, you can visit the API documentation here.

Wrap-Up

Only two helper types to go. Next time we will continue with the VisualTreeExtensions code helper in the UWP Community Toolkit.

Happy coding!

 

del.icio.us Tags: ,

2 comments: