mardi 6 janvier 2015

Windows Phone 8.1 : exception while creating sqlite database

I develop a Universal app that use a local SQLite database. As I need to know the database version, I store an additional information that contains this information.

At the application startup, I check if the database exists, and if the database version has changed.



public sealed partial class App : Application
{
// DB Name
public static string DBFileName = "myDb.sqlite";
public static string DBpath;

// DB Version
public static string DBVersionFilename = "myDb.version";
public static string DBVersionPath;
public static string DBVersion = "1.1.0";

public App()
{
this.InitializeComponent();
this.Suspending += this.OnSuspending;
ManageDB();
}

private async Task ManageDB()
{
if (!CheckDbExist().Result)
{
CreateDb();
}
else
{
if (CheckDbVersionUpdated().Result)
{
await DeleteDb();
CreateDb();
}
}
}

private async Task<bool> CheckDbExist()
{
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(DBFileName);
DBpath = storageFile.Path;
return true;
}
catch { }
return false;
}

private void CreateDb()
{
try
{
StorageFile storageFile = ApplicationData.Current.LocalFolder.CreateFileAsync(DBFileName, CreationCollisionOption.OpenIfExists).GetResults();
DBpath = storageFile.Path;
var dbconnection = new SQLiteAsyncConnection(DBpath, false);
dbconnection.CreateTableAsync<Article>();
//...

StorageFile file = ApplicationData.Current.LocalFolder.CreateFileAsync(DBVersionFilename, CreationCollisionOption.ReplaceExisting).GetResults();
FileIO.WriteTextAsync(file, DBVersion);
}
catch (Exception e)
{ }
}

private async Task<bool> DeleteDb()
{
try
{
StorageFile storageFile = ApplicationData.Current.LocalFolder.CreateFileAsync(DBFileName, CreationCollisionOption.OpenIfExists).GetResults();
await storageFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
return true;
}
catch { }
return false;
}

private async Task<bool> CheckDbVersionUpdated()
{
try
{
string userDBVersion;
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(DBVersionFilename);
userDBVersion = await FileIO.ReadTextAsync(file);
if (userDBVersion != DBVersion)
return true;
else
return false;
}
catch { }
return false;
}
}


There is a problem on "CreateDB()": - if I browse this code step by step, with breakpoint, there is no problem - but if I don't place breakpoint I meet an exception after calling "var dbconnection = new SQLiteAsyncConnection(DBpath, false);":


System.InvalidOperationException: A method was called at an unexpected time. A method was called at an unexpected time. at Windows.Foundation.IAsyncOperation`1.GetResults() at TestRating.App.CreateDb()}

=> Would you have an idea about the encountered problem?

=> Is there another way to do this?


Aucun commentaire:

Enregistrer un commentaire