Universal Windows Platform – Jsonfile App

Jsonfile App demonstrates how to store JSON Data using DataContractJsonSerializer with an ObservableCollection of items being stored or retrieved

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 the Name as JsonfileApp 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.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Json;
using Windows.Storage;
using Windows.UI.Xaml.Controls;

namespace JsonfileApp
{
    public class Music
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private string _album;
        private string _artist;
        private string _genre;

        public Music() { Id = Guid.NewGuid().ToString(); }

        public string Id { get; set; }
        public string Album { get { return _album; } set { _album = value; NotifyPropertyChanged(); } }
        public string Artist { get { return _artist; } set { _artist = value; NotifyPropertyChanged(); } }
        public string Genre { get { return _genre; } set { _genre = value; NotifyPropertyChanged(); } }
    }

    public class Library
    {
        private const string file_name = "file.json";

        private StorageFile _file;

        public static ObservableCollection<Music> Collection { get; private set; } = new ObservableCollection<Music>();

        private async void Read()
        {
            try
            {
                _file = await ApplicationData.Current.LocalFolder.GetFileAsync(file_name);
                using (Stream stream = await _file.OpenStreamForReadAsync())
                {
                    Collection = (ObservableCollection<Music>)
                        new DataContractJsonSerializer(typeof(ObservableCollection<Music>))
                        .ReadObject(stream);
                }
            }
            catch
            {
            }
        }

        private async void Write()
        {
            try
            {
                _file = await ApplicationData.Current.LocalFolder.CreateFileAsync(file_name,
                    CreationCollisionOption.ReplaceExisting);
                using (Stream stream = await _file.OpenStreamForWriteAsync())
                {
                    new DataContractJsonSerializer(typeof(ObservableCollection<Music>))
                        .WriteObject(stream, Collection);
                }
            }
            catch
            {
            }
        }

        public Library()
        {
            Read();
        }

        public void Add(FlipView display)
        {

            Collection.Insert(0, new Music());
            display.SelectedIndex = 0;
        }

        public void Save()
        {
            Write();
        }

        public void Remove(FlipView display)
        {
            if (display.SelectedItem != null)
            {
                Collection.Remove(Collection.Where(w => w.Id ==
                ((Music)display.SelectedValue).Id).Single());
                Write();
            }
        }

        public async void Delete(FlipView display)
        {
            try
            {
                Collection = new ObservableCollection<Music>();
                display.ItemsSource = Collection;
                _file = await ApplicationData.Current.LocalFolder.GetFileAsync(file_name);
                await _file.DeleteAsync();
            }
            catch
            {

            }
        }
    }
}

In the Library.cs there are using statements to include the necessary functionality. There is a Class for Music which has a PropertyChangedEventHandler and NotifyPropertyChanged Event trigger. It also has string Properties for Album, Artist and Genre plus an Id which will be represented by a guid. The Library Class has an ObservableCollection of the Music Class, Read uses ApplicationData with GetFileAsync to get stored data with DataContractJsonSerializer and ReadObject to read the ObservableCollection and Write uses ApplicationData with OpenStreamForWriteAsync to write stored data with DataContractJsonSerializer and WriteObject. The Constructor will call the Read Method, Add will insert items into the ObservableCollection of Music, Save will call the Write Method, Remove will delete items from the ObservableCollection based on the SelectedValue of the FlipView and call the Write Method and Delete will delete the file used for storage.

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:

<FlipView Margin="50" Name="Display" HorizontalAlignment="Center" VerticalAlignment="Center" 
ItemsSource="{x:Bind Path=local:Library.Collection}">
	<FlipView.ItemTemplate>
		<DataTemplate>
			<Grid VerticalAlignment="Top" HorizontalAlignment="Center" Width="300">
				<Grid.RowDefinitions>
					<RowDefinition/>
					<RowDefinition/>
					<RowDefinition/>
					<RowDefinition/>
				</Grid.RowDefinitions>
				<Grid.ColumnDefinitions>
					<ColumnDefinition Width="Auto"/>
					<ColumnDefinition Width="*"/>
				</Grid.ColumnDefinitions>
				<TextBlock Grid.Row="0" Grid.Column="0" Margin="10">Id:</TextBlock>
				<TextBox Grid.Row="0" Grid.Column="1" Margin="10"
				   Text="{Binding Id}" IsReadOnly="True"/>
				<TextBlock Grid.Row="1" Grid.Column="0" Margin="10">Album:</TextBlock>
				<TextBox Grid.Row="1" Grid.Column="1" Margin="10"
				 Text="{Binding Album, Mode=TwoWay}"/>
				<TextBlock Grid.Row="2" Grid.Column="0" Margin="10">Artist:</TextBlock>
				<TextBox Grid.Row="2" Grid.Column="1" Margin="10"
				 Text="{Binding Artist, Mode=TwoWay}"/>
				<TextBlock Grid.Row="3" Grid.Column="0" Margin="10">Genre:</TextBlock>
				<TextBox Grid.Row="3" Grid.Column="1" Margin="10"
				 Text="{Binding Genre, Mode=TwoWay}"/>
			</Grid>
		</DataTemplate>
	</FlipView.ItemTemplate>
</FlipView>
<CommandBar VerticalAlignment="Bottom">
	<AppBarButton Icon="Add" Label="Add" Click="Add_Click"/>
	<AppBarButton Icon="Remove" Label="Remove" Click="Remove_Click"/>
	<AppBarButton Icon="Save" Label="Save" Click="Save_Click"/>
	<AppBarButton Icon="Delete" Label="Delete" Click="Delete_Click"/>
</CommandBar>

The first block of XAML the main user interface of the Application, this features a FlipView with a DataTemplate which contains a Grid which makes up the look-and-feel of a record made up of a Grid with rows of TextBlock Controls for Labels and TextBox for entry. The second block of XAML is is the CommandBar which contains Add – to create a new data item, Remove – to remove a data item, Save – to update the storage with the data and Delete to delete the data file.

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 Add_Click(object sender, RoutedEventArgs e)
{
	library.Add(Display);
}

private void Remove_Click(object sender, RoutedEventArgs e)
{
	library.Remove(Display);
}

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

private void Delete_Click(object sender, RoutedEventArgs e)
{
	library.Delete(Display);
}

Below the MainPage() Method an instance of the Library Class is created, in Add_Click it calls the Add Method in the Library Class and Remove_Click calls the Remove Method. Save_Click calls the Save Method and Delete_Click will call the Delete Method in the Library Class

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 tap the Add button, then enter Album, Artist and Genre then can use Save to store the data using JSON in the Application

ran-jsonfile-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