Capture

Easily implement Data Storage Service in Xamarin.Forms using PCL Storage

It was kind of unfortunate that there is no built in Data Storage mechanism in Xamarin Forms. I was a hardcore Windows Phone developer before I moved into Xamarin Forms, whereas this was such an irritating factor for me and specially, few months back there weren’t any proper library or tutorials available for caching data in the app. The only suited option was to implement a dependency service, which I was quite bored of.

Few months back I needed to cache some data in an app, whereas this string array list will be downloaded from a web service, then saved it in the application cache and then reloaded whenever the app is opened by the user. I was developing a cross platform app based on Xamarin.Forms along with an attached PCL project.
After an extensive search I came across PCL Storage library, it was still in beta level at that time, but me being unable to find any other better option, decided to go ahead with it as it was very easy to implement.

Download PCL Storage on nuget – http://www.nuget.org/packages/pclstorage

Read about PCL on Xamarin Components Library, Capture

It was really easy and simple to implement that I used it for almost all the data caching tasks. Today PCL Storage has evolved very well along with some new features too. So I thought of sharing the implementation I used with PCL Storage back then with you all, in case if any of you came across my situation. You can easily, straightaway use the code I’m posting here in your Xamarin.Forms PCL projects and call the methods to get your job done without a hassle.

This includes Saving, Reading and Deleting data from your application cache.

public class DataStorageService
{
/// <summary>
/// Saving Values to the Storage...
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Key"></param>
/// <param name="ValueToSave"></param>
/// <returns></returns>
public async Task Save_Value<T>(String Key, T ValueToSave)
{
	XDocument doc = new XDocument();
	using (var writer = doc.CreateWriter())
	{
		var serializer = new XmlSerializer(typeof(T));
		serializer.Serialize(writer, ValueToSave);
	}

	IFolder rootFolder = FileSystem.Current.LocalStorage;
	IFolder folder = await rootFolder.CreateFolderAsync("Cache",
		CreationCollisionOption.OpenIfExists);
	IFile file = await folder.CreateFileAsync(Key + ".txt",
		CreationCollisionOption.ReplaceExisting);

	await file.WriteAllTextAsync(doc.ToString());
}

/// <summary>
/// Reading Values from the Storage...
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="Key"></param>
/// <returns></returns>
public async Task<T> Get_Value<T>(String Key)
{
	IFolder rootFolder = FileSystem.Current.LocalStorage;
	IFolder folder = await rootFolder.CreateFolderAsync("Cache",
		CreationCollisionOption.OpenIfExists);

	ExistenceCheckResult isFileExisting = await folder.CheckExistsAsync(Key + ".txt");

	if (!isFileExisting.ToString().Equals("NotFound"))
	{
		try
		{
			IFile file = await folder.CreateFileAsync(Key + ".txt",
			CreationCollisionOption.OpenIfExists);

			String languageString = await file.ReadAllTextAsync();

			XmlSerializer oXmlSerializer = new XmlSerializer(typeof(T));
			return (T)oXmlSerializer.Deserialize(new StringReader(languageString));
		}
		catch (Exception ex)
		{
			return default(T);
		}
	}

	return default(T);
}

/// <summary>
/// Delete any value from the Storage...
/// </summary>
/// <param name="Key"></param>
public async void Delete_Value(String Key)
{
	IFolder rootFolder = FileSystem.Current.LocalStorage;
	IFolder folder = await rootFolder.CreateFolderAsync("Cache",
		CreationCollisionOption.OpenIfExists);

	ExistenceCheckResult isFileExisting = await folder.CheckExistsAsync(Key + ".txt");

	if (!isFileExisting.ToString().Equals("NotFound"))
	{
		try
		{
			IFile file = await folder.CreateFileAsync(Key + ".txt",
			CreationCollisionOption.OpenIfExists);

			await file.DeleteAsync();
		}
		catch (Exception ex)
		{

		}
	}
}
}

 

This implementation has asynchronous method calls, therefore you can call these methods to get your job done and you won’t have anything to worry about UI lagging.

Here is how you could call this awesomely simple DataStorageService,

DataStorageService storageService = new DataStorageService();


Dictionary<string, object> TESTDATALIST = new Dictionary<string, object>();
TESTDATALIST.Add("KEY1", 123);
TESTDATALIST.Add("KEY2", "Hello");

await storageService.Save_Value<List<String>>("TESTKEY", TESTDATALIST);

MyCustomClass _obj = new MyCustomClass();
_obj.String1 = "Hello World";

await storageService.Save_Value<MyCustomClass>("MYOBJECTKEY", _obj);

 

Please be noted, I have created this DataStorageService class only for the purpose of saving primitive and custom data types, not for File types, which you could use for caching data lists, properties, app configurations and so on.

However PCL Storage does have great capability of creating files and folders in your cache and letting you very easily manage them. 😀

Now you may go Rock your apps with Xamarin.Forms ! 😉

9 thoughts on “Easily implement Data Storage Service in Xamarin.Forms using PCL Storage

  1. I am getting error like ystem.NotImplementedException: This functionality is not implemented in the portable version of this assembly. You should reference the PCLStorage NuGet package from your main application project in order to reference the platform-specific implementation. what all the dependency in xamarin form?

  2. can you mail me sample source? I want to look why at FileSystem.Current.LocalStorage its throwing exception. FYI i already added reference in all platform before asking question?

    1. I wrote the above code based on one of my previous enterprise level app implementation. So its not possible to send the whole project. Given your exception, looks like you may have made a mistake when calling the methods, but can’t say exactly what the cause without seeing the whole exception.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s