Universal Windows Platform – Compression App

Compression App demonstrates how to Compress with Compressor and Decompress with Decompressor Text with a given CompressAlgorithm.

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in a Name and select a Location and then select Ok to create the Project
vs2017-new-project-window

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 6

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as Library.cs before selecting Add to add the file to the Project

vs2017-add-new-item-library

Step 7

Once in the Code View for Library.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.Compression;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;

public class Library
{
    private const string app_title = "Compression App";
    private const string text_file_extension = ".txt";
    private const string compressed_file_extension = ".compressed";
    private readonly CompressAlgorithm compression_algorithm = CompressAlgorithm.Lzms;

    public void Show(string content, string title)
    {
        IAsyncOperation<IUICommand> command = new MessageDialog(content, title).ShowAsync();
    }

    public async Task<bool> ConfirmAsync(string content, string title, string ok, string cancel)
    {
        bool result = false;
        MessageDialog dialog = new MessageDialog(content, title);
        dialog.Commands.Add(new UICommand(ok, new UICommandInvokedHandler((cmd) => result = true)));
        dialog.Commands.Add(new UICommand(cancel, new UICommandInvokedHandler((cmd) => result = false)));
        await dialog.ShowAsync();
        return result;
    }

    public async void NewAsync(TextBox display)
    {
        if (await ConfirmAsync("Create New?", app_title, "Yes", "No"))
        {
            display.Text = string.Empty;
        }
    }

    public async void OpenAsync(TextBox display)
    {
        try
        {
            FileOpenPicker picker = new FileOpenPicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeFilter.Add(text_file_extension);
            picker.FileTypeFilter.Add(compressed_file_extension);
            StorageFile file = await picker.PickSingleFileAsync();
            switch (file.FileType)
            {
                case text_file_extension:
                    display.Text = await FileIO.ReadTextAsync(file);
                    break;
                case compressed_file_extension:
                    using (MemoryStream stream = new MemoryStream())
                    using (IInputStream input = await file.OpenSequentialReadAsync())
                    using (Decompressor decompressor = new Decompressor(input))
                    using (IRandomAccessStream output = stream.AsRandomAccessStream())
                    {
                        long inputSize = input.AsStreamForRead().Length;
                        ulong outputSize = await RandomAccessStream.CopyAsync(decompressor, output);
                        output.Seek(0);
                        display.Text = await new StreamReader(output.AsStream()).ReadToEndAsync();
                        Show($"Decompressed {inputSize} bytes to {outputSize} bytes", app_title);
                    }
                    break;
                default:
                    break;
            }
        }
        catch
        {

        }
    }

    public async void SaveAsync(TextBox display)
    {
        try
        {
            FileSavePicker picker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary
            };
            picker.FileTypeChoices.Add("Text File", new List<string>() { text_file_extension });
            picker.FileTypeChoices.Add("Compressed File", new List<string>() { compressed_file_extension });
            picker.DefaultFileExtension = text_file_extension;
            StorageFile file = await picker.PickSaveFileAsync();
            switch (file.FileType)
            {
                case text_file_extension:
                    await FileIO.WriteTextAsync(file, display.Text);
                    break;
                case compressed_file_extension:
                    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(display.Text)))
                    using (IRandomAccessStream input = stream.AsRandomAccessStream())
                    using (IRandomAccessStream output = await file.OpenAsync(FileAccessMode.ReadWrite))
                    using (Compressor compressor = new Compressor(output.GetOutputStreamAt(0), compression_algorithm, 0))
                    {
                        ulong inputSize = await RandomAccessStream.CopyAsync(input, compressor);
                        bool finished = await compressor.FinishAsync();
                        ulong outputSize = output.Size;
                        Show($"Compressed {inputSize} bytes to {outputSize} bytes", app_title);
                    }
                    break;
                default:
                    break;
            }
        }
        catch
        {

        }
    }

    public void Sample(ref TextBox display)
    {
        StringBuilder text = new StringBuilder();
        for (int i = 0; i < 10; i++)
        {
            text.AppendLine("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris non massa diam. " +
            "Nunc luctus non lorem id imperdiet. Nunc quis mi nec enim malesuada commodo mollis eget nisl. " +
            "Sed vulputate in purus eu vulputate. Quisque commodo eu odio et malesuada. Duis porttitor, " +
            "lectus ut egestas placerat, purus nisi elementum diam, congue lacinia erat lectus sit amet felis. " +
            "Proin suscipit lobortis bibendum. Aliquam erat volutpat. Nunc vitae nulla nunc.\n");
        }
        display.Text = text.ToString();
    }
}

In the Library.cs there are using statements to include the necessary functionality. The Show Method is used to display a MessageDialog and the ConfirmAsync Method is used to create a dialog with two buttons, this is used by the NewAsync method to confirm if a new document is to be created, if the answer is “Yes” then the TextBox will have it’s contents set to an empty string. OpenAsync is used to set the TextBox contents to the contents of a file – this is opened with a FileOpenPicker using ReadTextAsync and can also Decompress a compressed File with Decompressor. SaveAsync is used to get the contents of the TextBox and then this is saved to a file, using the FileSavePicker and WriteTextAsync and can also Compress a File with Compressor. Then there is a Sample Method which will set the TextBox to some example text.

Step 8

In the Solution Explorer select MainPage.xaml

vs2017-mainpage-library

Step 9

From the Menu choose View and then Designer

vs2017-view-designer

Step 10

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<TextBox Name="Display" AcceptsReturn="True" TextWrapping="Wrap" VerticalAlignment="Stretch"/>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Page2" Label="New" Click="New_Click"/>
	<AppBarButton Icon="OpenFile" Label="Open" Click="Open_Click"/>
	<AppBarButton Icon="Save" Label="Save" Click="Save_Click"/>
	<AppBarButton Icon="Document" Label="Sample" Click="Sample_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a TextBox where any text may be entered that can be compressed or decompressed. The second block of XAML is is the CommandBar which contain New which can set the TextBox to empty text, Open which will allow a file to be opened and Save will allow a file to be saved. Encrypt is used to perform encryption and Sample is used to insert some example text.

Step 11

From the Menu choose View and then Code

vs2017-view-code

Step 12

Once in the Code View, below the end of public MainPage() { … } the following Code should be entered:

Library library = new Library();

private void New_Click(object sender, RoutedEventArgs e)
{
	library.NewAsync(Display);
}

private void Open_Click(object sender, RoutedEventArgs e)
{
	library.OpenAsync(Display);
}

private void Save_Click(object sender, RoutedEventArgs e)
{
	library.SaveAsync(Display);
}

private void Sample_Click(object sender, RoutedEventArgs e)
{
	library.Sample(ref Display);
}

Below the MainPage() Method an instance of the Library Class is created, New_Click, Open_Click and Save_Click Methods call the related methods in the Library Class as does Sample_Click.

Step 13

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 14

After the Application has started running you can enter any text or insert some example text with Sample then use Save to store a Compressed version of the text or Open to decompress a stored file as text in the Application

ran-compression-app

Step 15

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s