martedì 19 febbraio 2013

PeriodicTask bug in Windows Phone 8

After almost two months, WPDev Team has confirmed a bug for PeriodicTask in Windows Phone 8:

PeriodicTask fails to trigger if there is no network connectivity in WP8 (enable Airplane mode,  or disable both cellular and wifi.

Here my discussion:

mercoledì 6 febbraio 2013

Easy SQL CE on Windows Phone

In Windows Phone is very simple to add and use SQL CE database.
What you need? Nothing... it's built in the Windows Phone Runtime.

Let's start...

If not exists, add the reference System.Data.Linq in your project.

Create the class to map the entity to the table:
public class Utente
    [Column(IsPrimaryKey = true, IsDbGenerated = true)]
    public int Id { get; set; }

    [Column(CanBeNull = false)]
    public string Name { get; set; }
You can see the attributes for the table and columns: table name, primary key, etc..

Now add a class for DataContext with the reference to the table Utenti. The DataContext wraps all operations you can do with database:
public class MyDataContext: DataContext
    public const string ConnectionString = "isostore:/mydatabase.sdf";

    public Table<Utente> Utenti { get; set; }

    public MyDataContext(string connectionString)
        : base(connectionString)
        this.Utenti = this.GetTable<Utente>();
ConnectionString has the special path to locate the database file in the isolated storage.

The classes for SQL CE are ready.
The last thing is create the physical .sdf file when the application start.
private void Application_Launching(object sender, LaunchingEventArgs e)
    using (var context = new MyDataContext(MyDataContext.ConnectionString))
        if (!context.DatabaseExists())

And now enjoy with your LinqToSql queries!
using (var context = new MyDataContext(MyDataContext.ConnectionString))
    var utenti = context.Utenti.OrderByDescending(u => u.Name).ToList();

Remember the "using" statement, because you need to dispose your DataContext to prevent high memory usage. The cost to create a new istance is very small.

NOTE: if you want to build an application for Windows 8/RT, maybe SQL CE is not your way. Why? Unfortunately Windows 8/RT don't support it. In this case you can use SQLITE.