Store and Retrieve JSON data from Local storage in Windows Store App

In this tutorial step by step we will learn to save and Retrieve JSON data in Local folder of Windows Store App.

Follow following steps to save and retrieve JSON data in local storage.

Step 1

Right click on project and add Nuget package and add package of Json.NET.

image

Step 2

Let us assume that we need to store Student information in local storage. For that I have created a Student class.

 


public class Student
    {
        public string Name { get; set; }
        public string City { get; set; }
        public string Grade { get; set; }
    }


Step 3

Before saving data we need to serialize the class into JSON. We will serliaze that using JSON.net library. After serializing object into JSON we will save data in local folder of windows store application.

 


            string jsonContents = JsonConvert.SerializeObject(s);           
           StorageFolder localFolder = ApplicationData.Current.LocalFolder;
           StorageFile textFile = await localFolder.CreateFileAsync("a.txt",CreationCollisionOption.ReplaceExisting);
            using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite))
            {
        
                using (DataWriter textWriter = new DataWriter(textStream))
                {
                    textWriter.WriteString(jsonContents);
                    await textWriter.StoreAsync();
                }
            }

        }


S is object of class Student. We are reading student properties from various textboxes.

 


            Student s = new Student
            {
                Name =txtName.Text,
                City = txtCity.Text,
                Grade =txtGrade.Text
            };


In above code snippet,

  • We are saving file in application local folder
  • Data is saved in file a.txt
  • Opening file in asynchronous way for read write operation using IRandomAccessStream
  • Using DataWriter to write data in file

In these four steps data can be saved in local folder of Windows Store Application.

Step 4

To read JSON data back we need to first read data from local storage and then deserliaze that to object from JSON. Reading data is very simple.

  • Open local folder
  • Load file asynchronously
  • Open file asynchronously to read the streams
  • Using DataReader reading stream
  • Convert JSON to object
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
           StorageFile textFile = await localFolder.GetFileAsync("a.txt");
                using (IRandomAccessStream textStream = await textFile.OpenReadAsync())
                {
                       
                    using (DataReader textReader = new DataReader(textStream))
                    {                                            
                        uint textLength = (uint)textStream.Size;
                        await textReader.LoadAsync(textLength);
                        string jsonContents = textReader.ReadString(textLength);                      
                        Student s = JsonConvert.DeserializeObject<Student>(jsonContents);
                        txtName1.Text = s.Name;
                        txtCity1.Text = s.City;
                        txtGrade1.Text = s.Grade;
                       
                    }
                }

In above code snippet,

  • We are opening local folder
  • Opening file asynchronously
  • Reading stream in IRandonAccessStream
  • Reading data using DataReader
  • DeSeralizing JSON to object using JsonConver

By following above steps you can save and retrieve data in local folder of Windows Store application. I hope you find this article useful.

Solved: WWAHost.exe remote endpoint was not reachable error in JavaScript Windows Store App

I was working on my office machine. While working I opened a JavaScript based Windows Store Application. When I tried to run application I got following exception,

image

I was baffled due to this exception. After sort of research I found that I was on VPN. I have no idea why on VPN this exception occurred. But to get rid of this exception you need to follow these two steps

  1. Closed all connections to VPN
  2. Restart machine

After performing above two steps you should not get above exception. I hope this quick post is useful. Thanks for reading.

Solved Exception in Passing Relative URI to Windows Runtime

While working today on a Windows Store Application I had a requirement to work with URI. Business class was as follows,

 

image

And I created instance of Product class in usual way setting values for both properties. I had put all images in ProductImages folder.

 

image

 

On running application I got following exception that given System.Uri cannot be converted.

image

 

After small research I found that WinRT does not support Relative URI. It only supports Absolute URI.

 

image

 

Now I fixed above problem by converting Relative URI to Absolute URI.

 

image

 

Exception got fixed after changing URI as absolute URI. I hope you find this quick fix useful. Thanks for reading.

Binding Image with Picture Library Images in Windows Store Application using FileOpenPicker

In this post we will take a look on binding image with Picture Library Images in Windows Store. In this post we will follow following steps

  • User will click on a button
  • On button click user will be select an image from Picture Library
  • Selected image will be bind to image control on the page

Application will behave as following,

image

In XAML based Windows Store Application object of FileOpenPicker allows us to choose files from Picture Library and Document Library. Essentially we will create instance of FileOpenPicker on click event of button and then restrict user to select only images. Once user has selected image, we will bind that Image to image control on the page.

Let us start with designing the page. Page design is very simple with button, image control and two text blocks.


<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
 <Grid.RowDefinitions>
 <RowDefinition Height="100" />
 <RowDefinition Height="*" />
 </Grid.RowDefinitions>
 <TextBlock Text="Select Photo from Picture Library" Margin="15,20,0,0" FontSize="40"/>
 <StackPanel Orientation="Horizontal" Grid.Row="1">
 <Button x:Name="btnFilePickerOpen" Click="btnFilePickerOpen_Click_1" Content="Select Image" Width="303" Height="97" Margin="50,50,0,403"/>
 <StackPanel Orientation="Vertical" Margin="50,50,0,0">
 <Image x:Name="imgSelected" />
 <TextBlock x:Name="txtSelectedImagePath" Margin="30,30,0,0" FontSize="30" />
 </StackPanel>
 </StackPanel>
 </Grid>

On click event of button we will create object of FileOpenPicker and allow user to select an image. We need to follow following steps

  • Create object of FileOpenPicker
  • Select ViewMode. There are two ViewModes available Thumbnail and List. Let us choose Thumbnail for our demo.
  • Provide SuggestedStartLocation. Let us select PicturerLibrary since we want to choose an image. Other options are VideosLibrary, DocumetsLibrary etc.
  • Apply filter. We can apply filters on type of files we will allow user to choose. We are adding file types jpg,jpeg and png.
  • In last step asynchronously we are calling PickSingleFileAsync function and taking reference of selected file in StorageFile.
FileOpenPicker openPicker = new FileOpenPicker();
 openPicker.ViewMode = PickerViewMode.Thumbnail;
 openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
 openPicker.FileTypeFilter.Add(".jpg");
 openPicker.FileTypeFilter.Add(".jpeg");
 openPicker.FileTypeFilter.Add(".png");
 StorageFile file = await openPicker.PickSingleFileAsync();
 if (file != null)
 {

 }
 else
 {

 }

On successful selection of file we need to convert that in image stream and bind that to image control. We are creating instance of BitmapImage and reading file stream in that. After successful reading setting bitmap image as source of image control.


if (file != null)
 {
 txtSelectedImagePath.Text = file.Name;
 var filestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
 BitmapImage imagetobind = new BitmapImage();
 imagetobind.SetSource(filestream);
 imgSelected.Source = imagetobind;

 }
 else
 {
 txtSelectedImagePath.Text = "Some problem fetching file ";
 }

&nbsp;

This is what all we need to do to fetch an image from picture library and bind it to image control. Full source code of button click is given below,


private async void btnFilePickerOpen_Click_1(object sender, RoutedEventArgs e)
 {
 FileOpenPicker openPicker = new FileOpenPicker();
 openPicker.ViewMode = PickerViewMode.Thumbnail;
 openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
 openPicker.FileTypeFilter.Add(".jpg");
 openPicker.FileTypeFilter.Add(".jpeg");
 openPicker.FileTypeFilter.Add(".png");
 StorageFile file = await openPicker.PickSingleFileAsync();
 if (file != null)
 {
 txtSelectedImagePath.Text = file.Name;
 var filestream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
 BitmapImage imagetobind = new BitmapImage();
 imagetobind.SetSource(filestream);
 imgSelected.Source = imagetobind;

 }
 else
 {
 txtSelectedImagePath.Text = "Some problem fetching file ";
 }
 }

Now when you run application you will able to choose an image from Picture Library and bind it to image control.

image

I hope you find this post useful. Thanks for reading.

Create Flickr Photo Search Windows Store App in XAML

In this post we will create application shown in below video. Essentially we will see how we can work with

  • GridView and ListView in Windows 8 Application
  • Consuming REST Service in Windows 8 Application
  • Share Contract in Windows 8 Application

To create on Flickr based application you need API Key from Flickr. You can apply for API key here . You need to fill the required information and click on Submit button to create API key. We need this API key in application. You need to submit App information in order to generate key. After submitting app information you will be navigated to App Garden and there you will find APP key and secret key as given in below image.

image

Very first create a Windows Store Application by choosing blank App template. Let us start with initializing variable. To search photos Flickr provides us REST end point. Globally we are initializing Flickr app key we created in previous step and constructing an URL to search on Flickr with search parameter. We are appending app key and search text in URL.


private HttpClient httpClient;
 private string key = "51fc5b3802c6ed36924ed3d6a8cc085a";
 private string flickrSearchUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={0}&text={1}";

Now switch to MainPage.xaml to design application. Very first let us divide content Grid in three rows. In second row we will put text box and button to search Flickr and in third row images returned will be displayed. First row contains header message of application.

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

<Grid.RowDefinitions>
 <RowDefinition Height="100" />
 <RowDefinition Height="100" />
 <RowDefinition Height="700" />
 </Grid.RowDefinitions>

 </Grid>

Next let us put header message and controls. In below XAML we are creating following controls

  • Creating TextBlock in first to display application header message.
  • Creating StackPanel in second row with orientation horizontal.
  • In StackPanel creating TextBlock to get user input to search Flickr.
  • Creating a Button in StackPanel to get user input to search on Flickr.
<TextBlock Text="Flickr Search Application"
 Margin="30"
 FontSize="36" />
 <StackPanel Grid.Row="1" Orientation="Horizontal">
 <TextBox x:Name="txtSearch" Width="200"
 VerticalAlignment="Center"
 HorizontalAlignment="Center"
 Margin="30"/>
 <Button x:Name="btnSearch"
 Content="Search on Flickr"
 Height="40" />
 </StackPanel>

Now let us create output GridView in third row. In this GridView we will display returned images from Flickr. In GridView we are creating ItemTamplate and putting an Image control in that. Image control is been bind to ImageUrl property. We will create class containing this property in later steps.

 <GridView x:Name="grdFlickrImageOutput" Grid.Row="2" Margin="30,0,0,0" >
 <GridView.ItemTemplate>
 <DataTemplate>
 <Image Width="300" Height="300" Source="{Binding ImageUrl}"></Image>
 </DataTemplate>
 </GridView.ItemTemplate>
 </GridView>

We have created design for the application. Now let us go ahead and create a class representing Flickr photo. This class will contain all the properties required to fetch an image from Flickr. Last property ImageUrl is of type URI and we are constructing it using other properties of Flickr Image


using System;

namespace debugmodeflickrsearch
{
 public class FlickrPhoto
 {
 public string ImageId { get; set; }
 public string FarmId { get; set; }
 public string ServerId { get; set; }
 public string Secret { get; set; }
 public string Title { get; set; }

public Uri ImageUrl
 {
 get
 {
 return new Uri(string.Format("http://farm{0}.static.flickr.com/{1}/{2}_{3}.jpg", FarmId, ServerId, ImageId, Secret));
 }
 }
 }
}

On click event of button we need to make a call to Flickr and get the response. To call Flickr REST API we are using HttpClient. We are making async call to get the response from Flickr. After getting reponse ParseIamges function is called to parse the response.


async void btnSearch_Click(object sender, RoutedEventArgs e)
 {
 httpClient = new HttpClient();
 HttpResponseMessage response = await httpClient.GetAsync(String.Format(flickrSearchUrl, key,txtSearch.Text));
 ParseImages(response);
 }

We will parse response using LINQ to XML. After parsing response is set as ItemSource of output GridView.


private async void ParseImages(HttpResponseMessage response)
 {
 XDocument xml = XDocument.Parse(await response.Content.ReadAsStringAsync());
 var returnedphotos = from results in xml.Descendants("photo")
 select new FlickrPhoto
 {
 ImageId = results.Attribute("id").Value.ToString(),
 FarmId = results.Attribute("farm").Value.ToString(),
 ServerId = results.Attribute("server").Value.ToString(),
 Secret = results.Attribute("secret").Value.ToString(),
 Title = results.Attribute("title").Value.ToString()
 };

grdFlickrImageOutput.ItemsSource = returnedphotos;
 }

Now let us go ahead and run application. We should able to search Flickr for images.

clip_image002

Now we want to share photo we like on social media or in a mail. We can achieve that using Windows 8 Share Contract. Very first let us go ahead and add itemclick event to output GridView. After adding event output GridView will get modified as following


<GridView x:Name="grdFlickrImageOutput" Grid.Row="2" Margin="30,0,0,0"
 IsItemClickEnabled="True" ItemClick="grdFlickrImageOutput_ItemClick_1"
 >
 <GridView.ItemTemplate>
 <DataTemplate>
 <Image Width="300" Height="300" Source="{Binding ImageUrl}"></Image>
 </DataTemplate>
 </GridView.ItemTemplate>
 </GridView>

&nbsp;

Next go ahead and define following variable globally,

 private string strTitleToShare = "Debugmode Flickr Photo Search App";
 private string strDescriptionToShare = "Sharing from Debugmode Flickr Photo Search App";
 private string strsharedText = string.Empty;

In constructor of the page create instance of DataTransferManager and add event for DataRequested.


DataTransferManager manager = DataTransferManager.GetForCurrentView();
 manager.DataRequested += manager_DataRequested;

Now we need to write code in DataRequested event to share text from application. In below code we are creating instance of DataRequest and setting Title , Description and Data to share.

void manager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
 {
 DataRequest request = args.Request;
 request.Data.Properties.Title = strTitleToShare;
 request.Data.Properties.Description = strDescriptionToShare;
 request.Data.SetText(strsharedText);
 }

Now we need to handle item selection in GridView. When user will select a particular photo we will construct text to be shared with URL of photo. We can do this as following,


private void grdFlickrImageOutput_ItemClick_1(object sender, ItemClickEventArgs e)
 {
 FlickrPhoto selectedPhoto = e.ClickedItem as FlickrPhoto;
 var urt = selectedPhoto.ImageUrl;
 strsharedText= "Hey look at this photo "+urt+" I loved it #CSharpCornerMvpSummit #Demo" ;
 DataTransferManager.ShowShareUI();
 }

Now go ahead and run the application. You should able to search photo from Flickr and share them using the apps.

image

Below find full source code of above discussion.

Mainpage.xaml


<Page
 x:Class="debugmodeflickrsearch.MainPage"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:local="using:debugmodeflickrsearch"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 mc:Ignorable="d">

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

<Grid.RowDefinitions>
 <RowDefinition Height="100" />
 <RowDefinition Height="100" />
 <RowDefinition Height="700" />
 </Grid.RowDefinitions>
 <TextBlock Text="Flickr Search Application"
 Margin="30"
 FontSize="36" />
 <StackPanel Grid.Row="1" Orientation="Horizontal">
 <TextBox x:Name="txtSearch" Width="200"
 VerticalAlignment="Center"
 HorizontalAlignment="Center"
 Margin="30"/>
 <Button x:Name="btnSearch"
 Content="Search on Flickr"
 Height="40" />
 </StackPanel>
 <GridView x:Name="grdFlickrImageOutput" Grid.Row="2" Margin="30,0,0,0"
 IsItemClickEnabled="True" ItemClick="grdFlickrImageOutput_ItemClick_1"
 >
 <GridView.ItemTemplate>
 <DataTemplate>
 <Image Width="300" Height="300" Source="{Binding ImageUrl}"></Image>
 </DataTemplate>
 </GridView.ItemTemplate>
 </GridView>

 </Grid>
</Page>

Mainpage.xaml.cs


using System;
using System.Linq;
using System.Net.Http;
using System.Xml.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.ApplicationModel.DataTransfer;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace debugmodeflickrsearch
{
 /// <summary>
 /// An empty page that can be used on its own or navigated to within a Frame.
 /// </summary>
 public sealed partial class MainPage : Page
 {
 private string strTitleToShare = "Debugmode Flickr Photo Search App";
 private string strDescriptionToShare = "Sharing from Debugmode Flickr Photo Search App";
 private string strsharedText = string.Empty;
 private HttpClient httpClient;
 private string key = "51fc5b3802c6ed36924ed3d6a8cc085a";
 private string flickrSearchUrl = "http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key={0}&text={1}";

public MainPage()
 {
 this.InitializeComponent();
 DataTransferManager manager = DataTransferManager.GetForCurrentView();
 manager.DataRequested += manager_DataRequested;
 btnSearch.Click += btnSearch_Click;
 }

void manager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
 {
 DataRequest request = args.Request;
 request.Data.Properties.Title = strTitleToShare;
 request.Data.Properties.Description = strDescriptionToShare;
 request.Data.SetText(strsharedText);
 }

&nbsp;

async void btnSearch_Click(object sender, RoutedEventArgs e)
 {
 httpClient = new HttpClient();
 HttpResponseMessage response = await httpClient.GetAsync(String.Format(flickrSearchUrl, key,txtSearch.Text));
 ParseImages(response);
 }

private async void ParseImages(HttpResponseMessage response)
 {
 XDocument xml = XDocument.Parse(await response.Content.ReadAsStringAsync());
 var returnedphotos = from results in xml.Descendants("photo")
 select new FlickrPhoto
 {
 ImageId = results.Attribute("id").Value.ToString(),
 FarmId = results.Attribute("farm").Value.ToString(),
 ServerId = results.Attribute("server").Value.ToString(),
 Secret = results.Attribute("secret").Value.ToString(),
 Title = results.Attribute("title").Value.ToString()
 };

grdFlickrImageOutput.ItemsSource = returnedphotos;
 }

/// <summary>
 /// Invoked when this page is about to be displayed in a Frame.
 /// </summary>
 /// <param name="e">Event data that describes how this page was reached. The Parameter
 /// property is typically used to configure the page.</param>
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
 }

private void grdFlickrImageOutput_ItemClick_1(object sender, ItemClickEventArgs e)
 {
 FlickrPhoto selectedPhoto = e.ClickedItem as FlickrPhoto;
 var urt = selectedPhoto.ImageUrl;
 strsharedText= "Hey look at this photo "+urt+" I loved it #CSharpCornerMvpSummit #Demo" ;
 DataTransferManager.ShowShareUI();
 }
 }
}

In this way we can create a Flickr Photo Search App for Windows Store. I hope you find this post useful. Thanks for reading.

How to work with Navigation App Template in Windows Store App with JavaScript

Recently I was attending a user group event and one young developer came to me with question, could you help me in finding out how to work with Navigation App Template in Windows Store App? So in this post I am trying to explain step by step working with Navigation App Template.

Very first start with creating a new project and select Navigation App from project template.

image

If you navigate to solution explorer you will find that there is one folder pages. Ideally all pages of the application should be (not must be) in this folder. By default there is one page called home page is there .

image

Let us stop at this point to explore default.html. In default.html you will find there is a PageControlNavigator. This control will host all the pages. Essentially Navigation Application Template follows singe page navigation mechanism. You will notice in data-win-option that there is home parameter and it is set to a page.

image

In this case home page or first page to be loaded in PageControlNavigator is home.html. Let us go ahead and design home.html. We will change title of the page and put a button. On touch of the button user will be navigated to another page.

image

Let us go ahead and run the application. You will get home.html loaded as home page with the title and button. You will notice that template has taken care of margin.

image

Let us say you want to navigate to Page2.html on click or touch of button. For that very first task you need to do is to add Page2.html in the project. For that right click on the pages folder and add a new subfolder called page2. Then right click on the newly added subfolder page2 and add a new item. Choose Page Control to add as new item.

image

After adding new page control solution explorer should look like following image. In the pages folder you can see that there is one more subfolder page2 with page2 page control.

image

Now we need to write code to navigate to page2.html on the click event of the button. Open home.js and type this code to navigate. You can navigate from one page to another page using WinJS.Navigation.navigate function. This function takes two parameters. First parameter is address of the page to navigate and second parameter is data to be passed while navigating.


element.querySelector("#btnnavigate").onclick = function (args) {
 WinJS.Navigation.navigate("/pages/page2/page2.html",
 { data: "data to other page" }
 );
 };

At this point you should able to navigate to page2 from home page. You can find that template has taken care of back button and margin in page2.

image

Above we are passing “data” while navigating. Now we need to write some code on page2.js to consume data being passed. Let us replace the title of the page2 with the data being passed. We will write this code in ready function of page2.js.


ready: function (element, options) {
 // TODO: Initialize the page here.
 var datapassedhere = options.data;
 element.querySelector(".pagetitle").innerText = datapassedhere;

Now on running application you will see page2 title has been replaced with the data being passed from home page.

image

In this way you can work with Navigation App template. I hope you find this post useful. Thanks for reading.

OSMinVersion must have value 6.2.1 or higher in Windows Store Application

I was busy working with other stuff and after long time today I resumed my working with Windows 8 development. I opened an old project and directly press F5 to run the application on local machine.

While I tried to run the application, I encountered with following run time error. Error message was as following,

In the app manifest, the value of element OSMinVersion(6.2.0) must have a value of ‘6.2.1’ or higher

 

image

Although I found solution of this bug very easy, I got puzzled with this exception. You can solve this problem

By making sure you have REBUILD the project before running it

Make sure you are cleaning and rebuilding the project to avoid this run time error. I hope you find this post useful. Thanks for reading.