ARTICLE

Save User Data to Local Application Storage in Windows Store App Using C#

Posted by Gaurav Gupta Articles | Windows Store Apps August 27, 2012
Today we will learn how to store and retreive user details from local application data storage.
Reader Level:

Today we will learn how to store and retreive user details from local application data storage.

Sometimes we want to save user-related data in some application storage during his/her session. It is necessary to save user session data during navigation though various pages in an application. Anytime and for any page we need this user session data to do some processing taks. Normally we want to store user login information for his/her session, so that we can check whether he/she is authorized or not.

In Windows 8 Store apps, the developer has the ability to save user data so it can be retrieved any time during running the application or even again in running mode after being closed by the user. The data stored in Application local storage is saved even when an application is not in running mode and you can also fetch data from it when running the app again. The data in Application local storage is never lost untill the application is removed or uninstalled from the computer system.

In this article we are trying to save user data to Local Application data storage and also retrieve from it. So, now we proceed to create a Windows 8 Store blank application and save user details to Local Application data storage.

First create a Blank Application using C# and XAML.

I've created a simple blank XAML page:

<Page

    x:Class="savinguserdataonsuspended.MainPage"

    IsTabStop="false"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:local="using:savinguserdataonsuspended"

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

        <Canvas>

            <TextBox Canvas.Left="249.977" TextWrapping="Wrap" Canvas.Top="67.89" x:Name="IdTextBox" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" Width="259.477" d:LayoutRounding="Auto"/>                      

            <TextBlock Canvas.Left="90" FontSize="30" TextWrapping="Wrap" Text="Email ID" Canvas.Top="75"/>

            <TextBox Canvas.Left="250" TextWrapping="Wrap" Canvas.Top="130" x:Name="NameTextBox" Width="261"/>

            <TextBlock Canvas.Left="85" TextWrapping="Wrap" Text="Name" FontSize="30" Canvas.Top="129"/>

            <Button x:Name="save" Content="Login" Click="save_Click_1" FontSize="25"  Canvas.Top="210" Canvas.Left="187" Height="62" Width="154"></Button>

        </Canvas>

    </Grid>

</Page>

Now, I need an entity for the values of these controls and then save the entire bucket to Local Application Storage. So, I'm going to create a UserDetails class.

public class UserDetail

{

    public int Id { get; set; }

    public string Name { get; set; }   

}

I use the Button's click events to keep the instance of UserDetails updated and call a SaveAsync() method and then, navigate to another page.

UserDetail Stats = new  UserDetail();

private async void login_Click_1(object sender, RoutedEventArgs e)

{ 

     Stats.Name = NameTextBox.Text;

     Stats.Id = int.Parse(IdTextBox.Text);

     await SaveAsync();

     this.Frame.Navigate(typeof(next));                
}

You all know that everything in Windows 8 Store apps is asynchronous, so we'll see the async and await keywords in these apps.

In the SaveAsync method we will serialize the data to be saved into Local Application Storage.
 

StorageFile userdetailsfile = await ApplicationData.Current.LocalFolder.CreateFileAsync("UserDetails",

 CreationCollisionOption.ReplaceExisting);            

IRandomAccessStream raStream = await userdetailsfile.OpenAsync(FileAccessMode.ReadWrite);

using (IOutputStream outStream = raStream.GetOutputStreamAt(0))

{

    // Serialize the Session State.

    DataContractSerializer serializer = new DataContractSerializer(typeof(UserDetail));

    serializer.WriteObject(outStream.AsStreamForWrite(), Stats);

    await outStream.FlushAsync();

}


In the preceding code first we get the local folder of local storage and then create a file using the CreateFileAsync() method also user the parameter ReplaceExisting if the file already exists. Then we open it using OpenAsync in the read/write mode. Then I serialize the object using the DataContractSerializer class and write this serializer obect to a file using the WriteObject method.

In the Next Page where we naviagte after login we call the ReterieveAsync() method to restore the value back to a bucket at the OnNavigatedTo event of the page.

protected async override void OnNavigatedTo(NavigationEventArgs e)

{

await RestoreAsync();
}

Here is the code of the ReterieveAsync() method where I read the file from the Local Folder, deserialize it's contents and then set the instance of UserDetails with the values that were saved earlier.

StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync("UserDetails");    

if (file == null) return;

IRandomAccessStream inStream = await file.OpenReadAsync();                      

    // Deserialize the Session State.

DataContractSerializer serializer = new DataContractSerializer(typeof(UserDetail));

var StatsDetails = (UserDetail)serializer.ReadObject(inStream.AsStreamForRead());

inStream.Dispose();          

UserName.Text ="Welcome "+ StatsDetails  .Name;

UserProfileId =  StatsDetails.Id;
 

This is what my app looks like before I close  or navigate it myself.

Local-Storage-Location-In-Windows8-Apps (1).jpg

Login to add your contents and source code to this article
Article Extensions
Contents added by Giancarlo Marin on Mar 28, 2013
:) good!
post comment
     

:) good!

Posted by Giancarlo Marin Mar 28, 2013

can u pls tell me where the whole code can be downloaded

Posted by surya syamala Feb 06, 2013

Please update your article, praveen vr is right!

Posted by naren dran Feb 01, 2013

Hey thx for the code but I'm trying to compile project like an hour but it doesn't work :(There are some missing arguments like UserProfileId what is that and why it doesn't work?So if you could just upload your full project here and we can analyze that it would be great..

Posted by berhan cem Jan 23, 2013

I created a public async void SaveAsync() and put it right after public MainPage(), but I get an error: 'savinguserdataonsuspended.MainPage.SaveAsync()' does not return a Task and cannot be awaited. Consider changing it to return Task.Also it says that UserName and UserProfileId do not exist in current context but I guess they have to be created on the next page.Could you please post a fully working project solution, like you have on your other articles, so that we could fully understand it? Thank you for your work

Posted by tak v Jan 03, 2013
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Get Career Advice from Experts