Sterling DB on top of Isolated Storage – 2

Windows Phone From Scratch #39

 

In yesterday’s posting we looked at the Sterling Database. and how to set up and initialize tables, store an retrieve data.  Today we’ll build on that to set up the database in App.xaml so that we can handle tombstoning.

The key change to yesterday’s program is that rather than initializing the database in the main page, we’ll do so in App.xaml.  To see this at work, create a new Windows Phone application. 

We’ll use the exact same Xaml as we did yesterday, creating a text block and a button. This time, however, open App.xaml.cs to create the sret up code.  We’ll start by creating two static member variables, one private and one public,

private static ISterlingDatabaseInstance _database = null;
private static SterlingEngine _engine = null;

We need a public static property to obtain the underlying database:

public static ISterlingDatabaseInstance Database
{
   get
   {
      return _database;
   }
}

Create  private helper methods to activate and deactivate the database (yesterday we dispensed with deactivation to keep things simpler)

private void _ActivateEngine( )
{
   _engine = new SterlingEngine( );
   _engine.Activate( );
   _database = 
      _engine.SterlingDatabase.
      RegisterDatabase<TestDB>( );
}

private void _DeactivateEngine( )
{
   _engine.Dispose( ); 
   _database = null;
   _engine = null;
}

This references the same database definition (TestDB) that you created yesterday.  Note that Dispose (in _DeactiveEngine) also flushes to isolated storage.

Add a call to _ActivateEngine in both Application_Launching and Application_Activated, and a call to _DeactiveEngine in both Application_Deactivated and Application_Closing.

After re-creating the Customer class and TestDB, you can turn to MainPage.cs and remove all the initialization code, and change all the calls to the database itself to use the static property (e.g.,

 private void SaveCustomer( )
 {
    var key =
       App.Database.Save( cust );
    App.Database.Flush( );
 }

 

You end up with cleaner usage of the database, and the assurance that the database will be properly flushed on tombstoning and restored when the application resumes.

Nice.

About Jesse Liberty

Jesse Liberty has three decades of experience writing and delivering software projects and is the author of 2 dozen books and a couple dozen online courses. His latest book, Building APIs with .NET will be released early in 2025. Liberty is a Senior SW Engineer for CNH and he was a Senior Technical Evangelist for Microsoft, a Distinguished Software Engineer for AT&T, a VP for Information Services for Citibank and a Software Architect for PBS. He is a Microsoft MVP.
This entry was posted in Patterns & Skills and tagged , , . Bookmark the permalink.

2 Responses to Sterling DB on top of Isolated Storage – 2

Comments are closed.