Market Numbers in the Mobile Industry#

The other day at Web Not War DevCamp I did a TED Style talk on “State of Mobile imageIndustry for Developers” and talked about some of the market share numbers and what tools are available for users not just on Windows Phone but on all platforms. These numbers are also for smartphones and feature phones (or non-smartphones) combined.

Now I’m just going to talk about the numbers, as I think they are pretty interesting.  But numbers are what they are and numbers can be skewed in any way. Bad numbers can be ‘tweaked’ to look good, and good numbers can be skewed to look bad.  Although the only time you would want to do that is when you are comparing yourself against your competition and they have good numbers Winking smile

All the numbers I got from the latest comScore Mobilens report for August 2011 released in October 2011.  Note, that these numbers are only for US and are not reflect worldwide market share.  These reports are free and I recommend you keep an eye out for them when they come out if you are in the mobile space.

The Hardware Numbers

So up first up is Original Equipment Manufacturers (OEM for short) market share numbers.  What is an OEM? An OEM is a company that produces or manufactures physical phone hardware. 

So who is the leader of end of August 2011

image

And here are the numbersimage

As you can see from the list above, Samsung is up on top and gained 0.5% share of the market in three months, with LG and Motorola rounding out the top three.  If you are surprised that Apple is #4 remember that this is hardware not the Platform/Operating System (we get into that below) but Apple did gain 1.1% points in the three months while Motorola lost 1.1% in share.  RIM also lost 1.0% and unfortunately1 I only expect them to lose more as these numbers are before their October 2011 email outage and the recent class action law suit against RIM because of the issues.

What am I expecting? Apple will go up next month because of the launch of the iPhone 4s but the rankings will essentially stay the same.  I don’t expect Samsung to lose the top spot for a very long time.  Very few people know that they actually manufacture some hardware for some of the companies on the list, so even if the go down, they still generate revenue.

The Software Numbers

In my opinion, hardware is just a paperweight without the right software on it, and that is what this next list of companies are on the list for, their software.  Now don’t get me wrong, you still need some nice sexy hardware to appeal to the consumer, but the hardware won’t do anything without software Smile

So who is on top here?

imageimage

And here are the numbers showing the top 5.

image

Google is on top with 43.7% market share and they are just killing the competition and I think there are a couple of reasons. First, it’s ‘somewhat’ open source so companies are allowed to take the software modify it, customize it and change the experience to something unique for their device. In my opinion, this could lead to fragmentation of the software and challenging to provide an update path for end users. Now carriers love this because to get the latest and greatest features you have to buy a new phone. Google has noticed this and is taking steps to contain this but it’s already happening.  Carriers also love Android because there is less of a ‘fee’ associated with it to sell the device in retail stores which means more profit for them. 

So what about the rest?  Well it’s not surprising that Apple is in the number two spot in the US and gained 0.7% share at 27.3%.  RIM rounds out the top three but they lost a huge 5% down to 19.7%.  Probably to everyone’s surprise in the number 4 spot is Microsoft’s Windows Phone at 5.7% down 0.1%.  Rounding out the top 5 is Symbian at 1.8% down 0.3%

What am I expecting here?  I think Google will gain 1 or 2 points and continue their market domination for the next little while.  Unfortunately, patent infringement troubles with Oracle dealing with Java and Android will cause some issues and depending on the turnout, could possibly stop Android devices from being sold.  There is also all the licensing deals Microsoft is making with hardware manufacturers like HTC that leverage Android which may affect future growth.  I expect Apple will also go up a few points as well as Microsoft.  RIM and Symbian, I expect them to continue their downward spiral in the next report but the rankings overall should stay the same.

Conclusion

Remember, numbers are numbers but if you are building mobile apps you should pay attention to them and see which way the consumers are going and if you should abandon or start adopting certain platforms.  Also remember that these numbers are only US but I think including the rest of the world would produce different results.

Do you keep up with the numbers?  Agree or disagree with what I’m saying? Let me know! Feel free to contact me here or via twitter @MarkArteaga!

1I say unfortunate because RIM is a great Canadian success story and sad to see them go down they way they are.


Friday, October 28, 2011 3:05:00 AM (Eastern Daylight Time, UTC-04:00) #    Comments [2]  |  Trackback

 

The Share Icon on Windows Phone#

I recently wrote about the different ‘share icons’ that are being used on various mobile platform but one that really stands out (and not in a good way) is the Windows Phone icon.  The Windows Phone icon looks like this

appbar.share.rest

A gift or present image.  Now I guess it could mean ‘share’ or ‘give something to someone’ and in our case would mean ‘giving them a link to some content’ but using a ‘gift’ as a share icon didn’t make sense to me but because I believe in using what is provided in the platform, I went with the standard icon, until now.

With Windows 8 developer preview recently being available for download, I of course installed it and played with it. I did notice they did have the functionality to share things but they did not use the standard share icon (the gift) as in Windows Phone.  Considering Windows Phone uses the Metro Design Language and Windows 8 also uses the Metro Design Language, I found it strange that a new icon was used.

image_thumb107_thumb[3]

This icon is the Open Share Icon by Shareaholic or at least looks very similar to it.

Share1_thumb[4]

So what is a developer to do again?  Well, since I did not like the ‘gift’ share icon I decided to start using this icon in our Windows Phone apps instead of the ‘gift’ icon.  Yes, this does go against my previous advice of being consistent on the platform but rules are meant to be broken!  I’m pretty confident that changing the ‘share icon’ on Windows Phone will not cause any confusion with users but I’ll have to wait and see.  I’m also assuming since Windows 8 uses Metro and Windows Phone uses Metro, I think they will align everything properly in terms of the Metro Design Language (let’s hope they also bring the OSes together since Win8 will support ARM!)

Now if you want to use this icon you can download it at the Open Share Icon website.  If you want to include it in your Windows Phone app, here is a share icon you can use in the Application Bar. If you read my article on ‘Theme Aware Icons’ you can also use this piece of XAML within a page which essentially renders a Path

<Path Data="M23.8306,18.3706C21.1596,18.3706,18.9946,20.5296,18.9946,23.1906C18.9946,25.8526,21.1596,28.0126,23.8306,28.0126C26.5006,28.0126,
28.6666,25.8526,28.6666,23.1906C28.6666,20.5296,26.5006,18.3706,23.8306,18.3706 M34.0216,23.5926L34.0276,23.5936C33.0816,23.5936,32.3126,
24.2496,32.0976,25.0006C32.0856,25.0556,32.0736,25.1096,32.0606,25.1626C32.0566,25.1776,32.0546,25.1916,32.0526,25.2066L32.0506,
25.1986C31.1486,28.8886,27.8106,31.6266,23.8306,31.6266C22.1136,31.6266,20.5166,31.1176,19.1826,30.2406C18.8596,30.0216,18.4696,29.8926,
18.0486,29.8926C16.9356,29.8926,16.0346,30.7916,16.0346,31.9026C16.0346,32.5976,16.3896,33.2126,16.9306,33.5726L16.9296,33.5726C18.9066,
34.8826,21.2786,35.6446,23.8306,35.6446C29.1686,35.6446,33.7236,32.3066,35.5116,27.6106L40.7556,27.6106L40.7556,23.5926z M23.8306,
14.7536C25.5816,14.7536,27.2096,15.2846,28.5596,16.1936L28.5606,16.1916C28.8806,16.4046,29.2646,16.5286,29.6786,16.5286C30.7906,16.5286,
31.6926,15.6286,31.6926,14.5196C31.6926,13.7886,31.2996,13.1486,30.7156,12.7976C28.7406,11.4956,26.3746,10.7366,23.8306,10.7366C18.4916,
10.7366,13.9376,14.0756,12.1486,18.7706L6.9056,18.7706L6.9056,22.7896L13.6686,22.7896C14.5856,22.7736,15.3316,22.1426,15.5566,21.4136C15.5736,
21.3356,15.5916,21.2576,15.6096,21.1806C15.6106,21.1796,15.6106,21.1786,15.6106,21.1776C16.5166,17.4906,19.8526,14.7536,23.8306,14.7536"
Fill="{StaticResource PhoneForegroundBrush}" Height="24.908" Stretch="Fill" Width="33.85" UseLayoutRounding="False"> <Path.Clip> <RectangleGeometry RadiusY="0" RadiusX="0" Rect="0,-1,48,48"> <RectangleGeometry.Transform> <MatrixTransform Matrix="1,0,0,1,-6.90560007095337,-10.7365999221802"/> RectangleGeometry.Transform> RectangleGeometry> Path.Clip> Path>

So what do you think, is it a good idea to deviate from the standard platform share icon?  Share your thoughts via comments here or via twitter @MarkArteaga!


UI | UX | Windows Phone
Thursday, October 27, 2011 1:28:00 PM (Eastern Daylight Time, UTC-04:00) #    Comments [2]  |  Trackback

 

The Share Icon#

I have been working on a couple of mobile projects on different platforms that deal with sharing content with social networks.  Unfortunately every platform has a different icon and there are two standard ones that are used on the web.  Here is a list of all the icons I feel are standard out there both on the web and on mobile platforms

Platform Icon Description
Web Share_ShareIconProject Share Icon Project which seems to be the one most everyone uses.  I’m sure most are already familiar with this icon and is pretty standard.
Web Share1 Share icon which was created by Shareaholic which is called the Open Share Icon.  I was not very familiar with this icon until I noticed it on Windows 8.image_thumb107
iPhone Share_ShareIconProject On the iOS platform (iPhone and iPad) seems developers have gravitated towards the Share Icon Project icon.
Android AndroidShare_ShareIconProject On Android, seems there is a mix of icons used and uses both the Share Icon Project icon and it’s own icon with a ‘circle with two arrows pointing up’. 
Windows Phone appbar.share.rest_thumb[2] On Windows Phone, well they don’t use any of the ‘standard’ icons and went their own way also.  This never really made sense to me as to why they did this but it is what it is.
     

 

So what is a developer to do?

Well here is my advice, use whatever is standard on the platform, that is what most users will be familiar with and comfortable using.  I think you want to keep users comfortable with your application and not deviate from the norm on the platform.  You want to keep that user experience consistent and make your application feel as though it’s a part of the platform and not something that has just been shoved into the platform from a port.

What do you think?  Agree? Disagree? Let me know! Feel free to contact me here or via twitter @MarkArteaga!


General | UX
Thursday, October 27, 2011 1:25:00 PM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

Windows Phone and Database Support Part 2#

Back in June, I did a few blog posts on Windows Phone 7.1 SDK and some new features for developers.   I also did one specifically on Windows Phone and database support as this was a huge pain point for developers including myself.  Well with Windows Phone 7.5, things are a lot better.  I’ll quickly go through how to get a database up and running, access the data and update the data.

For this sample, we’ll be creating a quick application to track kilometers for a car. We are basically going to have a Car class, and a car will have a collection of Kilometer Entry Items.

Creating our Model

Creating your via code is a manual process, unlike the desktop devs, we don’t have a designer, although I would imagine you could generate the code with the desktop tools and then modify the generated code.  I’ll take the long way as you have more control and see what is going on and so you learn more IMO. First we have to create our model and will essentially look like this (NOTE: This is not an extensive Kilometer tracking application, just a sample, feel free to extend, make better and sell on marketplaceSmile)

image

Because we are using LINQ to SQL we will be creating ‘mostly’ some plain old CLR objects (POCOs) and decorating our class and properties with some attributes.  Specifically we will be using the System.Data.Linq.Mapping.TableAttribute for our class which will represent our tables and System.Data.Linq.Mapping.ColumnAttribute for our properties which will represent our table columns. 

Since a Car will have a collection of KilometerItems we will also have to use System.Data.Linq.AssociationAttribute which will allow us to associate a collection of records to a Car record.

As for the POCOs, you will noticed I said ‘mostly’ POCO.  The reason for this is because of our Association requires a little bit of code to make LINQ to SQL work.  We’ll start with the Car class

[Table]
public class Car
{
    private EntitySet<KilometerItem> m_KilometerItems;
    public Car()
    {
        this.m_KilometerItems = new EntitySet<KilometerItem>(
            ((item) => item.Car = this),
            ((item) => item.Car = null));
    }

    [Column(IsPrimaryKey = true, 
        IsDbGenerated = true, 
        DbType = "INT NOT NULL Identity", 
        CanBeNull = false, 
        AutoSync = AutoSync.OnInsert)]
    public int Id { get; set; }

    [Column]
    public int CurrentKilometers { get; set; }

    [Column]
    public string DisplayName { get; set; }

    [Association(Name = "FK_Car_KMItems", 
        Storage = "m_KilometerItems", 
        ThisKey = "Id", 
        OtherKey = "CarId")]
    public EntitySet<KilometerItem> KilometerItems
    {
        get { return m_KilometerItems; }
    }
}

Few things to notice

  1. EntitySet – we have a an EntitySet<KilometerItem> which holds a reference to our collection of KilometerItems for the associated car
  2. Constructor – when a KilometerItem is added or removed, we want to set or remove the reference to the Car object, so we pass in a Delegate to the EntitySet.Removed and EntitySet.Added parameters.

Now here is our KilometerItem class

[Table]
public class KilometerItem
{
    [Column(IsPrimaryKey = true,
        IsDbGenerated = true,
        DbType = "INT NOT NULL Identity",
        CanBeNull = false,
        AutoSync = AutoSync.OnInsert)]
    public int Id { get; set; }

    [Column(CanBeNull=false)]
    public DateTime Date { get; set; }

    [Column]
    public int StartKilometers { get; set; }

    [Column]
    public int EndKilometers { get; set; }

    [Column]
    public int TotalKilometersForEntry { get; set; }

    [Column]
    public TripType TripType { get; set; }

    [Column(CanBeNull = false)]
    public string DisplayName { get; set; }

    [Column(DbType = "Int")]
    public int? CarId { get; set; }

    private EntityRef<Car> m_CarRef = new EntityRef<Car>();
    [Association(Name = "FK_Car_KMItems",
        Storage = "m_CarRef",
        ThisKey = "CarId",
        OtherKey = "Id",
        IsForeignKey = true)]
    public Car Car
    {
        get
        {
            return this.m_CarRef.Entity;
        }
        set
        {
            var previousRef = this.m_CarRef.Entity;
            if (previousRef != value || !this.m_CarRef.HasLoadedOrAssignedValue)
            {
                if (previousRef != null)
                    this.m_CarRef.Entity = null;
                this.m_CarRef.Entity = value;
                if (value != null)
                    this.CarId = value.Id;
                else
                    this.CarId = default(int?);
            }
        }
    }
}

The main thing here is the Car property.  If you remember from the Car class, we set this KilometerItem.Car property when an item is added or removed from the Car.KilometerItems EntitySet.  This allows us to have a reference to the Car object that ‘owns’ this KilometerItem.  Other than that it’s a standard POCO with a bunch of attributes.

In both classes you will also want to notice the Id Property.  You will require this because we are making a 1 to many association from Car to KilometerItem.  You will notice our Column attribute also specifies some parameters to auto generated the property, that it’s a primary key etc.

[Column(IsPrimaryKey = true,
    IsDbGenerated = true,
    DbType = "INT NOT NULL Identity",
    CanBeNull = false,
    AutoSync = AutoSync.OnInsert)]

 

Creating the Database

There are two ways to create the database, either via code or you can embed a database prepopulated with data in your application. To Create a database manually do the following

  1. In Visual Studio, open Server Explorer
  2. Click on the Add Connection button image
  3. You’ll be presented with a dialog, should be self explanatory from there Smile

I don’t think you learn much from Wizards, so we’ll create one using code.  First thing we have to create is a class that inherits from System.Data.Linq.DataContext.  Here is our CarTrackerContext class

public class CarTrackerContext : DataContext
{
    private static string CONNECTION_STRING
        = "Data Source=isostore:/CarTracker.sdf";
    public CarTrackerContext()
        : base(CONNECTION_STRING)
    {
    }

    /// <summary>
    /// Represents the car table
    /// </summary>
    public Table<Car> CarTable;

    public Table<KilometerItem> KilometerItems;

    public void Initialize()
    {
        if (!this.DatabaseExists())
            this.CreateDatabase();

    }
}

Couple things to cover

  • Connection strings: to get all the details on Connection String and Local Database on Windows Phone see MSDN.  But one key thing to notice is isostore which is unique to Windows Phone
    • isostore: this essentially means your database was created in code, is read/write and located in isolated storage for your app
    • appdata: this essentially means your database was included in your application, is in the installation folder and is read only.  You can copy this file into Isolated Storage to make it read/write.
  • Initialize – we call this so we can check to see if the database exists and if it does not create it. 
  • Updating Database – I don’t go through this as it’s another post on it’s own.  Read this on MSDN on updating a local database on Windows Phone, it’s a must read!

And that is essentially it!  The DataContext class will take care of a lot of the heavy lifting to create the database and make lookups into tables using LINQ to SQL work.

Hooking It All Up

Usually you would want some sort of MVVM pattern to make things all connect.  But again this is a sample and not best practices, so although your code will work, it’s really not a best practice so be warned.  I’m also not going through every details such as creating a new page etc as I’m assuming you already know how to do that.

First thing we do is create our DataContext CarTrackerContext.  You can add the following code to your App.Xaml.cs

private static CarTrackerContext m_context;
public static CarTrackerContext Context
{
    get
    {
        if (m_context == null)
        {
            m_context = new CarTrackerContext();
            m_context.Initialize();
        }
        return m_context;
    }
}

Next, we need to bind the collection of cars to a list in the MainPage.xaml.  Our page will look like the following

image

To bind the list, we will have to create an observable collection so the list can automatically update when something is added.  MainPage.xaml will have to implement INotifyPropertyChanged as follows

public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged

In your MainPage.Xaml, the ListBox should have the ItemSource property set as follows (again see source for a complete set)

<ListBox ItemsSource="{Binding CarItems}"

In your MainPage constructor add the following which will set the DataContext for your page

this.DataContext = this;

Then add the following code to allow us to bind a collection to the UI.

private ObservableCollection<Car> m_CarItems;
public ObservableCollection<Car> CarItems
{
    get { return m_CarItems; }
    set
    {
        if (value != m_CarItems)
        {
            m_CarItems = value;
            NotifyPropertyChanged("CarItems");
        }
    }
}
And of course, because we implement INotifyPropertyChanged we need the following
public event PropertyChangedEventHandler PropertyChanged;
void NotifyPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

Our Add button at the bottom will allow us to add a new Car record so in the button click handler we add the following

NavigationService.Navigate(new Uri("/NewCar.xaml", UriKind.Relative));

Now we create a NewCar.xaml page to allow us to create a new car as follows

image

On the button click event for the done button (the checkmark image) we add the following

try
{
    App.Context.CarTable.InsertOnSubmit(
        new Model.Car() { 
            CurrentKilometers = Int32.Parse(txtKMs.Text), 
            DisplayName = txtName.Text });
    App.Context.SubmitChanges();
    if (NavigationService.CanGoBack) NavigationService.GoBack();
}
catch (Exception ex)
{
    MessageBox.Show(string.Format("Unable to save record.  Error: {0}", ex.Message));
}

Key things to note here is how we save the data.  We essentially create a new Car object, add it to the CarTrackerContext.CarTable and call CarTrackerContext.SubmitChanges and it will be added to the database.  Yes, it’s as easy as that to create a record!

When we navigate back to the main page we still won’t see any data in the list because it’s not bound to the CarItems property.  First we need to set this property and we do this in the OnNavigatedTo method of the MainPage.xaml.cs as follows

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    if (e.NavigationMode == NavigationMode.Back)
    {
        var tCarItems = from t in App.Context.CarTable
                        select t;

        if (CarItems == null)
            CarItems = new ObservableCollection<Car>();

        foreach (var car in tCarItems)
        {
            var existingCar = from t in CarItems
                                where t.Id.Equals(car.Id)
                                select t;

            if (existingCar.Count() == 0)
            {
                //nothing found so add it to the bottom
                CarItems.Add(car);
                NotifyPropertyChanged("CarItems");
            }
        }
    }
    else if (e.NavigationMode == NavigationMode.New)
    {
        if (CarItems == null)
            CarItems = new ObservableCollection<Car>();
                
        var tCarItems = from t in App.Context.CarTable
                        select t;
                
        CarItems = new ObservableCollection<Car>(tCarItems);
    }
    base.OnNavigatedTo(e);
}
A few things I do here, first, we check to see if the NavigationMode (which is new in Windows Phone 7.1 SDK) tells us if this is a New or a Back navigation.  We can assume if it’s new, the app is just launching, and if it’s back we are coming back from a different page.

If we are launching for the first time, we just go ahead and fill up our ObservableCollection that is bound to the UI using a LINQ Query.  If it’s coming back from a different page, we want to only add new items to the list.  This way if an item is selected that item will stay selected and if the listbox is scrolled to a different position other than the top, that position won’t reset.  Remember it’s small things like this that make users happy but they don’t know it until it happens and they get irritated Smile

What About Tracking Kilometers

Adding the functionality to add a kilometer record for a car record is essentially the same as adding a new card record. So I’m not going to go through all the code just some of the important points.

On the MainPage.xaml.cs we want to handle the ListBox.SelectionChanged event as follows

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var lb = sender as ListBox;
    if (lb != null)
        NavigationService.Navigate(new Uri(
            string.Format("/CarKilometerItemsPage.xaml?carId={0}", 
            (lb.SelectedItem as Car).Id), UriKind.Relative));
}

You will notice we are adding a query string to the URI, this way we know what KilometerItems we need to open on the new page which will look as follow

image

On the CarKilometerItemsPage.xaml we again have a ListBox so we have an ObservableCollection that is bound to a list of KilometerItems associated with a Car object in our database.  On the OnNavigatedTo we again have some code to update our list as follows

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    //grab the query string
    if (NavigationContext.QueryString.ContainsKey("carId"))
        CarId = Int32.Parse(NavigationContext.QueryString["carId"]);

    if (CarId.HasValue)
    {
        if (e.NavigationMode == NavigationMode.Back)
        {
            var tCarItem = (from t in App.Context.CarTable
                            where t.Id.Equals(CarId.Value)
                            select t).FirstOrDefault();

            if (KMItems == null)
                KMItems = new ObservableCollection<KilometerItem>();

            foreach (var item in tCarItem.KilometerItems)
            {
                var existingItem = from t in KMItems
                                    where t.Id.Equals(item.Id)
                                    select t;

                if (existingItem.Count() == 0)
                {
                    //nothing found so add it to the bottom
                    KMItems.Add(item);
                    NotifyPropertyChanged("CarItems");
                }
            }
        }
        else if (e.NavigationMode == NavigationMode.New)
        {
            if (KMItems == null)
                KMItems = new ObservableCollection<KilometerItem>();

            var tCarItem = (from t in App.Context.CarTable
                            where t.Id.Equals(CarId.Value)
                            select t).FirstOrDefault();

            KMItems = new ObservableCollection<KilometerItem>(tCarItem.KilometerItems);
        }
    }
    else
    {
        ThreadPool.QueueUserWorkItem((o) =>
            {
                Thread.Sleep(250);
                Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Unable to get the car id sorry :(");
                        NavigationService.GoBack();
                    });
            });
    }
    base.OnNavigatedTo(e);
}

Things to note

  1. We get the querystring to get a CarId.  If one is not sent, we show a message and navigate back as we can’t do anything without a Car.Id value
  2. If it’s a New Navigation, we are finding the Car record using a LINQ query, then we go and get all KilometerItems and fill our observable collection which is bound to our UI
  3. If it’s a Back Navigation, we only want to add new items to the observable collection
  4. Nothing else, pretty easy Smile

Adding a KilometerItem Record

Adding a KilometerItem is pretty straight forward also and is pretty much the same process as adding a new Car Record.  To start our page will look as follows

image

First thing we do is add some code to our list of KilometerItem page to navigate to our new page as follows

private void NewEntry_Click(object sender, System.EventArgs e)
{
    NavigationService.Navigate(new Uri(string.Format("/NewKMEntry.xaml?carId={0}", CarId.Value), UriKind.Relative));
}

You will notice we are again passing the Car.Id value to our new page, this way we know what Car record the new KilometerItem record should be assigned to.  When the user is ready, they can click the checkmark and we can run the following code to save the new record

var Car = App.Context.CarTable.Where(t =>
    t.Id.Equals(
    Int32.Parse(NavigationContext.QueryString["carId"]))).FirstOrDefault();
if (Car != null)
{
    Car.KilometerItems.Add(new Model.KilometerItem()
        {
            StartKilometers = Int32.Parse(txtKMs.Text),
            EndKilometers = Int32.Parse(txtEndKm.Text),
            DisplayName = txtDescription.Text,
            Date = DateTime.Now,
        });
    App.Context.SubmitChanges();
}
else
{
    MessageBox.Show("Can't find the car, something went wrong.  We will navigate back and try it again");
}
Dispatcher.BeginInvoke(() =>
{
    if (NavigationService.CanGoBack) NavigationService.GoBack();
});

Few things to note

  • We first want to find the Car record in the database and we use a Lambda expression to get the object returned to us.
  • To create the record, we use the Car.KilometerItems.Add method and add a new record to the collection.
  • Then we call the Context.SubmitChanges() and we are good to go!

Conclusion

A couple of points that you should probably be aware of

  1. Be careful using NText as you may get some issues when trying to update those column types.  Try to use NVarChar(4000) instead.  If you must use it, set your column attribute to the following [Column(UpdateCheck=UpdateCheck.Never)], this way you will not get the ‘SQL Server does not handle comparison of NText, Text, Xml, or Image data types’ error
  2. If you are used to creating your own SQL Statements or using things like Table Direct to optimize table access, your out of luck on for Windows Phone.  Although I have not done in performance testing, I’m pretty confident applications like the Kilometer Tracking example will not suffer at all from a performance bottle neck
  3. If you are writing to the table from separate threads, you may want to create different dataContexts as you need them.  The DataContext is not guaranteed to be thread safe
  4. DataContext implements IDisposable but if you want to pass around an object and then try and get a collection associated with that object, it will through an ObjectDisposedException if you call Dispose or use a using statement.

And that’s it, pretty straight forward to Local Database support in Windows Phone now that the tools have been updated. Here is the download to the source.  Comments or feedback feel free to contact me here or via twitter @MarkArteaga!


Monday, October 24, 2011 1:30:00 PM (Eastern Daylight Time, UTC-04:00) #    Comments [3]  |  Trackback

 

Nokia, Windows Phone and the Smartphone Battles#

8f336_windowsphone_logoBack in August, Google announced that they are buying Motorola for $12.5billion.  Great buy on Google’s part because it will somewhat help defend them in the patent issues they are currently facing with Android and OEMs using Android. Will this help $GOOG win the smart phone battle? Don’t know, but they are sure taking a large chunk of the market!

What does this mean for Windows Phone?  Don’t know either, but they do have Nokia; which used to have the largest marketshare, on board to deliver Windows Phone based hardware.  Unfortunately they have been steadily losing a very large chunk of their marketshare.  Over a year ago I did write an article on whether Windows Phone will succeed, and over all I think it is doing pretty well considering it started from scratch again (Yes I’m optimistic Smile) but don’t think it has been fully successful yet. 

Nokia-800-BlueNow will Nokia hardware help $MSFT get marketshare for Windows Phone?  I think it will as it has a history of making some pretty sexy devices.  The image here is supposedly of the Nokia 800 when it’s going to release this year (image courtesy of PocketNow)

Interestingly enough, Barranger (or @4MKMobile) talks about his experience with Nokia X7 and N8 during an event he attended and summarizes his reason Why Nokia coming to Windows Phone is a huge deal.

Visual-Studio-2010-Express-for-Windows-PhoneMicrosoft definitely has developers on board, but now it’s time to get consumers on board.  Without consumers, developers have no customers and the ‘eco-system’ falls apart.  Let’s hope Microsoft has something up their sleeves for Windows Phone in terms of marketing it to the consumer.  Seeing things like the Windows Phone Klout Perk promotion is a step in the right direction.  Get 500 phones in the hands of influential people, I’m pretty confident unless they are hardcore power users that want to be able to control every aspect of their phone, they will have something good to say about Windows Phone.

Let’s see what the next year brings. The battles are definitely heating up, the wallets are opening up and it’s time to win the consumers.  It’s definitely game time for all major players involved including Apple, Microsoft, RIM and Google!

Comments or feedback feel free to share your thoughts via the comments or via twitter @MarkArteaga!


Sunday, October 23, 2011 9:40:20 PM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

TechDays 2011 & Windows Phone#
TECH DAYS 2011 CANADA

TechDays is fast approaching and is next week in Toronto.  Similar to past years (2008, 2009, 2010) I’ll be presenting on Windows Phone.  This year is great because I finally think Windows Phone is in a state where consumers will finally start paying attention and the competition is actually starting to copy features in Windows Phone (who would have ever thought that!)

This year TechDays will be taking place in the following cities so make sure to register

  1. Toronto – October 25-26
  2. Vancouver – November 15-16
  3. Montreal – November 29-30

If you do register for TechDays 2011, make sure you use this promo code TDSPKR11CAN to get 50% off the conference admission!

Here is a summary of my session that I put together. I’ll be presenting the first day @ 10:30am.  I have merged things from Mix11 and tried to condense as much as I could into 75mins.

Windows Phone 7.5: An Overview and Architecture Deep Dive

Windows Phone is a different kind of phone, architected to put the focus on end users while enabling developers to build compelling, connected experiences that enhance the phone. Peer under the covers to see how the architecture evolved to deliver powerful functionality

I’ll also be hanging around all day so if you want to chat about the phone, the competition, development options or anything else, find me, I’m always willing to chat!

Hope to see you there and remember to register!


Thursday, October 20, 2011 11:21:50 AM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

Windows Phone 7.5 App Challenge#

Calling all Canadian Developers, win a brand new Windows Phone 7.5 phone if you build 2 quality apps

If you’re one of the first 300 to build or upgrade 2 quality apps in the Mango App Challenge, and Microsoft will give you a free Windows Phone 7.5 phone, plus showcase your apps to over 40,000 developers in newsletters and other Microsoft properties.

Make sure you read the Windows Phone quality check list for the app challenge as it will be some of the criteria. 

  1. Design
  2. Usability
  3. Stability
  4. Engagement
  5. Sociability
  6. Cloud Integration

RedBit’s own Where’s Timmy is featured in the ‘apps to inspire you’ section and hopefully it brings some inspiration. My advice is make your application fun to user, easy to use and don’t just make it black and white but use Metro as your base inspiration and bring some color into your app.  And use some animations, not a lot but some as users love seeing things move.

So go out upgrade or build a new app for Windows Phone 7.5 and download the tools at App Hub and build build build!!!


Tuesday, September 27, 2011 9:08:20 PM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

Summary of Windows Phone Mango Posts#

mangoI’ve been spending the last few days reading and testing some of the new features in Windows Phone Mango and also writing a bunch of articles sharing some details.  Here is a summary of the articles I have written so far.  With over 1500 new APIs in Mango, I’m sure I will have some more articles so I will continue updating this list as I write more. 

  1. Windows Phone 7 And Multitasking Revisited
  2. Windows Phone Multitasking - Fast Application Switching
  3. Windows Phone Multitasking - Scheduled Notifications
  4. Windows Phone And Database Support
  5. New Windows Phone Device Status APIs
  6. Windows Phone Launchers & Choosers
  7. Augmented Reality And Windows Phone 7 Part 2

Comments or feedback on any of the articles, feel free to contact me here or via twitter @MarkArteaga!


Thursday, June 30, 2011 4:56:49 AM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

Windows Phone - Launchers & Choosers#

Launchers and Choosers have been around since the first version of Windows Phone and basically allow the developer to integrate into the operating system.  For example, there is a ‘Task’ to make a phone call or to compose an email.  I like to define Launchers & Choosers as follows

  1. Launchers – ‘Just Launch it and Forget it’ – Basically, you launch something out the the OS, possibly passing some parameters and hand control over to the operating system.  Don’t expect the user to always come to your application and at this point you will be tombstoned or go into dormant state.  For example, you launch a phone call, the user might hit the start button, and go to another application and never return to your app until it’s needed again
  2. Choosers – this lets you pull information from the operating system in a way that keeps the users data secure and private.  For example, you can ask the user to select a contact and it will return contact information.

With Windows Phone Mango tools out, there are some new Launchers and Choosers that can be of use to developers.  You will find all of them un der the Microsoft.Phone.Tasks namespace on MSDN.  I’ll just go through a summary of the new ones for Mango.

The Launcher Tasks

As developers we did not really get that many new launchers but the ones we got I think will be useful if you are creating mapping applications.

image

The class names are pretty self explanatory but essentially the three do the following

  1. BingMapsDirectionsTask – Will show directions for using the Maps application  
  2. BingMapsTask – will start the Maps application at the defined center point and if a search term is passed in it will add pins on the map that match the search term.

There is also a LabeledMapLocation class that is used with the BingMapsDirectionsTask that is basically a latitude/longitude with a string label

image

And using these are straight forward.  To use the BingMapsDirectionsTask you can use the following code

BingMapsDirectionsTask task = new BingMapsDirectionsTask()
{
    Start = new LabeledMapLocation("Current Position", new System.Device.Location.GeoCoordinate(43.65365522976227, -79.39292348921275)),
    End = new LabeledMapLocation("CN Tower", new System.Device.Location.GeoCoordinate(43.642600285590795, -79.38728012144566)),
};
task.Show();

which will result in the following in the Maps application using the emulator

image

BingMapsTask is just as easy

BingMapsTask task = new BingMapsTask()
{
     Center = new System.Device.Location.GeoCoordinate( 43, -79),
     SearchTerm = "CN Tower",
     ZoomLevel = 15
};
task.Show();

And results in

image

 

The Chooser Tasks

In Windows Phone Mango, we have four new chooser tasks.  Remember, choosers will return something back to us via a Completed event.

  1. AddressChooserTask – allows you to get the address of a contact chosen by the user
  2. SaveContactTask – allows you to initiate a save contact for the user to complete
  3. GameInviteTask – allows you to show the game invite screen to allow user to invite someone else to a multiplayer game session
  4. SaveRingtoneTask – allows you to initiate a save ring tone for the user to complete

I’ll do a quick example on saving a contact.  Essentially you have to create a new SaveContactTask, fill in some properties and call the show event.  The possible properties are

image

and the sample code to save is as follows

SaveContactTask task = new SaveContactTask()
{
    Company = "RedBit",
    FirstName = "Mark",
    HomeAddressCity = "Toronto",
    HomeAddressCountry = "Canada",
    HomeAddressState = "Ontario",
    HomeAddressStreet = "123 Any Street",
    HomeAddressZipCode = "75038",
    HomePhone = "416-123-4567",
    JobTitle = "Not Sure :)",
    LastName = "Arteaga",
};
task.Completed += new EventHandler<SaveContactResult>(task_Completed);
task.Show();

and our completed event handler is as follows

void task_Completed(object sender, SaveContactResult e)
{
    if (e.TaskResult != TaskResult.OK)
        MessageBox.Show("Is there a reason you didn’t save!");
    else
        MessageBox.Show("Done!");
}

which results in

image

and when the user is done, because we wired up the Completed event we will get the appropriate message if the user saved the contact or not.

The Share Tasks

You are probably wondering what the heck is a ‘Share Task’.  Well this is essentially a Launcher but it’s new to Mango and allows you to share the user’s status (ie Facebook status updates) or share a link.

  1. ShareStatusTask – allows user to share a status message on social network of choice
  2. ShareLinkTask – essentially same as status but will share a link on social network of choice

and the object model looks like this

image

Unfortunately this doesn’t work in the emulator but basically what happens on a device is a “Post Message” page pops up, user can select which social network they want to post to and click send.  They do have to option of modifying the post. 

So there you have it, some of the new Launchers & Choosers available in Mango.  I think they are useful and already have plans to integrate into some of our apps and customer apps.

Enjoy!


Thursday, June 30, 2011 4:34:33 AM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

Windows Phone Multitasking–Fast Application Switching#

I recently wrote about the updated story on Windows Phone and Multitasking.  Yes, Windows Phone does multitask and gives developers a few options to get things done which are

  1. Background Audio
  2. Background File Transfers
  3. Fast Application Switching
  4. Scheduled Notifications
  5. Scheduled Tasks

I have already covered Scheduled Notifications on Windows Phone.  In this article, I’ll cover Fast Application Switching or FAS. FAS essentially allows a user to quickly switch applications and not see a delay in switching apps or the ‘resuming …’ screen. When a user navigates away from your application, it will be put in a ‘dormant’ state but the application will still be held in memory. Be aware that even though you are in a dormant state, your threads, timers, web connections will stop running so essentially you can’t run any background threads while dormant.  This image gives a good visual indication of what is happening

image

 

Now, the great thing is you really don’t have to do anything to implement this, as it’s automatically there if you are compiling for Mango.  If your application is compiled for Windows Phone RTM or Nodo and is in Marketplace, you will have to re-compile to get Fast Application Switching.  ‘Legacy’ apps will not get the ‘dormant’ state and will go straight to tombstoned as seen in this image

image

With FAS, as a develoepr you have to be aware that you may still get tombstoned if the device is running low on memory and the OS will tombstone the oldest app. When coming back into the Activated state, you might want to know if you have been tombstoned or not.  This is pretty easy to find out using the ActivatedEventArgs.IsApplicaitonInstancePreserved as follows

private void Application_Activated(object sender, ActivatedEventArgs e)
{
    if (e.IsApplicationInstancePreserved)
    {
        //We were dormant
    }
    else
    {
        //we were tombstoned
    }
}

As usual not overly complex, and that’s a good thing!  If you want more details on getting ready for Fast Application Switching make sure you spend the time to watch the MIX11 session.  If you are still unsure or unfamiliar with Tombstoning, read over the Execution Model Overview for Windows Phone on MSDN and play around with Visual Studio writing code.

Make sure you are prepared for this, as it will make a far better user experience for your app than the ‘resuming …’ screen!


Thursday, June 30, 2011 2:42:24 AM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

Augmented Reality and Windows Phone 7 Part 2#

A few months ago I wrote about augmented reality on Windows Phone 7 and how the possibilities are there as the platform supports it but it’s all hidden away to third party developers. 

Now that blog post was back on August 24 2010 less than 12 months ago.  Now with Windows Phone Mango, Augmented Reality scenario on Windows Phone is now a “reality”.  Kudos goes out to the Windows Phone team for getting this out in less than 12month! It was already there but my guess is it wasn’t tested enough for general use!

How Do I Use It!

Pre-Mango, we only had access to the CameraCaptureTask which would go ‘outside’ of our application and return us a back picture stream that the user took.  Not the most ideal scenario from a developers point of view but got the job done.

With Mango APIs we now have direct access to the camera and able to stream directly onto a page. You also have the ability take pictures and have various events to tell you what the user is doing, for example CameraButtons.ShutterKeyPressed which tells you when the camera hardware button was pressed.

Now I’m not going to go through how to implement augmented reality on Windows Phone as there is a good sample on MSDN on creating an Augmented Reality app on Windows Phone in combination using the Motion Sensor APIs and camera stream.  I will go through the APIs that allow you to use the camera stream.

First thing, create a new standard Windows Phone Application project

image

To add a video camera stream to your page is quite easy.  First thing add a VideoBrush as the Background to the Grid named ContentPanel in MainPage.xaml.  It should look something like this.

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <Grid.Background>
        <VideoBrush x:Name="video" />
    </Grid.Background>
</Grid>

Be aware that the VideoBrush is new to Mango so you won’t be able to use this pre-Mango.  Here is the object model for video brush. 

image

Note, that there is a CameraVideoBrushExtensions class.  Again this is Mango only, and this has a single method called SetSource() which allows you to add a video stream to the VideoBrush. 

Now, to add the stream you create a PhotoCamera  object and call the VideoBrush.SetSource method with the PhotoCamera object as the parameter.  Here is the object model for the PhotoCamera

image

To set the source we create a new global PhotoCamera object  in our MainPage.xaml.cs as follows

Microsoft.Devices.PhotoCamera m_camera;

Then in the constructor of MainPage we add the following

Loaded += (s, e) =>
    {
        m_camera = new Microsoft.Devices.PhotoCamera();
        video.SetSource(m_camera);
    };

Your MainPage.xaml.cs should like like the following

Microsoft.Devices.PhotoCamera m_camera;

// Constructor
public MainPage()
{
    InitializeComponent();

    Loaded += (s, e) =>
        {
            m_camera = new Microsoft.Devices.PhotoCamera();
            video.SetSource(m_camera);
        };
}

Now, when you run the project you will get a stream in the ContentPanel.  You can try this on a real device or on the emulator.  In the emulator you will get a black box moving around a white box.

 

image

Also, the Windows Phone project when first created will automatically add ID_CAP_ISV_CAMERA to your WMAppManifest.xml.  This capability is required if you are using the camera.

And that’s it.  Three lines of XAML and four lines of C#, pretty straight forward to get a camera stream to your app.  Don’t think iPhone or Android devs have it this easy Smile

Feedback, let me know here or via twitter.


Thursday, June 30, 2011 12:46:58 AM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

Windows Phone Multitasking–Scheduled Notifications#

In my previous post I talked about some of the new multitasking features available in Windows Phone Mango.  In this article, I’ll go over Scheduled Notifications in a bit more detail.

You will find all API details in the Microsoft.Phone.Scheduler namespace and the main items we will look at are

A Scheduled Notification is fairly straight forward and essentially will popup a dialog box similar to the calendar reminder in the OS.

There are two types of Scheduled Notifications you can use and these are Alarm and Reminder. This is a good way to integrate with the native OS and not have to build basic pop ups but leverage what is already there.

I’m not going to go through an entire code walk through as there is a good example on MSDN on how to create reminders for Windows Phone. Here is a quick sample on creating a reminder

//Create a reminder
Reminder myReminder = new Reminder("buy milk");
myReminder.Title = "Buy Milk";
myReminder.Content = "Don't forget to buy milk!";
myReminder.BeginTime = DateTime.Now.AddSeconds(10);
myReminder.ExpirationTime = DateTime.Now.AddSeconds(15);
myReminder.RecurrenceType = RecurrenceInterval.None;
myReminder.NavigationUri = new Uri("/MainPage.xaml?fromReminder=1", UriKind.Relative);

//Add the reminder to the ScheduledActionService
ScheduledActionService.Add(myReminder);

Running this code on the emulator will result in the following

image_thumb[2]

Not overly complex but a few key things to note

  • You can specify a NavigationUri which will be used if the user launches your app from the reminder. This way you know if you came from the reminder and can show the specific reminder that was clicked
  • Don’t try to add a reminder with the same name, you will get an exception saying that the reminder already exists

Creating an Alarm is almost the same as creating a Reminder with a few slight differences.

//Create an alarm Alarm alarm = new Alarm("Test Alarm"); alarm.Title = "My Alarm Title"; alarm.Content = "My Test alarm"; alarm.BeginTime = DateTime.Now.AddSeconds(10); alarm.ExpirationTime = DateTime.Now.AddSeconds(15); alarm.RecurrenceType = RecurrenceInterval.None; alarm.Sound = new Uri("");

//Add the reminder to the ScheduledActionService
ScheduledActionService.Add(myReminder);

Again, pretty straight forward but a few key things to note with alarms are

  • A user cannot click from the alarm to your application so you have no NavigationUri property
  • You can specify a custom sound to play using the Sound property but the sound file must be included in your XAP and cannot be played from isolated storage.

Scheduled notifications I think will be useful in some application scenarios and it’s great that we as developers can offset some of the ‘reminder code’ to the API/OS to handle for us.  This is just one of the ways Windows Phone now multitasks and I’ll follow up with the others in upcoming posts.


Tuesday, June 28, 2011 3:26:44 AM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

Windows Phone 7 and Multitasking Revisited#

When Windows Phone first launched I spoke about Windows Phone and multitasking and how at the core of it, Windows Phone was a full blown multitasking and real-time operating system. 

Unfortunately for developers, this was not full exposed to us and the reason for this was to maintain a good user experience which included performance and battery power.

Looking back, the concept of ‘Tombstoning’ was added to allow developers to write their applications to give the user of ‘true multitasking’.  Not the best scenario as is does take some time to get your head wrapped around the Tombstoning concept.  I’m not going to go through Tombstoning here as it has been extensively covered.  Here are a few links from MSDN to help you out in case youa re not familiar with it

Multitasking Pre-Mango

In Pre-Mango devices, you again have the concept of Tombstoning to give the user the illusion of multitasking.  Another option made to developers is UserIdleDetectionMode and ApplicationIdleDetectionMode.  What exactly are they?

UserIdleDetectionMode mode allows you to force the screen to stay on.  So if you are create an application that will track a user as they drive and show their location on a Bing Map control, this is the property you will want to use. But be cautious when using it as it could drain the battery life extremely fast depending on your scenario. To use it is fairly simple and can be achieved with the following code.

Microsoft.Phone.Shell.PhoneApplicationService.Current.UserIdleDetectionMode = 
    Microsoft.Phone.Shell.IdleDetectionMode.Disabled;

The other option is ApplicationIdleDectionMode.  This API allows you to run your application under the lock screen.  So essentially, if your application is running and the device locks or the user locks the screen, your code will still be executing.  So if you are running a background thread, when the device locks the code will still be running.  To achieve this is again relatively simple and can be achieved with one line of code

Microsoft.Phone.Shell.PhoneApplicationService.Current.ApplicationIdleDetectionMode 
    = Microsoft.Phone.Shell.IdleDetectionMode.Disabled;

Now, a couple of caveats to ApplicationIdleDetectionMode and UserIdleDetectionMode.

  1. If the user navigates away from your application, your application will be tombstoned and ApplicationIdleDetectionMode and UserIdleDetectionMode will not work.
  2. Part of the Marketplace Certification requirements are to notify the user that you will be running code in the background.  This way the user is aware of what is happening and has the option to turn these features on or off.  If you do not do this you will fail certification.

NOTE: UserIdleDetectionMode I would not say is “multitasking” but something a lot of developers are not aware of so figure I would cover it.

Multitasking Mango

With the announcement of Windows Phone 7.1 Mango , there were a few announcements about multitasking on Windows Phone that will address some of the challenges with the platform. 

Now, as a developer you have to keep in mind that the core goal of the product team is to maintain a great end user experience.  Although developers are not first in line, the product team is paying attention to developer pains and fixing it, as long as it doesn’t deteriorate the end user experiences on Windows Phone.  With Windows Phone 7.1 as developers we get a bit more power in terms of running our code when our application is not running and there are a few options to accomplish this.

  1. Background Audio – essentially, this will allow you to play any audio while another application is running.  Essentially, your application will be running, then you can continue playing the audio while the user goes off and uses another application.  The key class to use here is AudioPlayerAgent
  2. Background File Transfers – here you essentially can queue up HTTP file transfer requests for uploading or downloading and which will be run even if your application is not running.  In some scenarios this can be useful for example when uploading a large image.  The main class you want to look at here is BackgroundTransferRequest
  3. Fast Application Switching – here the short story is users will not see as long of a delay when switching apps as they did in pre mango.  Reason is because your application will be dormant but still in memory and not tombstoned.  I’ll follow up with more details on FAS in an upcoming article.
  4. Scheduled Notifications – this allows you to create reminders or alarms that will be handled by the system.  You essentially create your items, pass it to the OS, and the OS will handle showing them to the user. 
  5. Scheduled Tasks – this is essentially a task that will run in the background and probably the one that will be used in most scenarios.  Scheduled tasks will run in the background even when your application is not running.  There are two types you can create and these are PeriodicTasks and ResourceIntensiveTasks.

As you can see, as developers we now have a little more of the platform exposed to us in ways that will not entirely affect the user experience.  From playing around with the beta tools future for Windows Phone 7 from a developer’s perspective looks great!  And best of all, the end user experience is not degraded and they continue to use the phone and our apps. 

I’ll do some follow up posts on the items above and give more details on the different ways developers can implement multitasking on Windows Phone 7.1.


Tuesday, June 28, 2011 3:10:40 AM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

New Windows Phone Device Status APIs#

Windows Phone Mango introduces some new APIs to help get device status.  In pre-Mango APIs, we would have to use the Microsoft.Phone.Info.DeviceExtendedProperties to get different status such as device total memory, device manufacturer and the code was a bit messy. 

One of the key ones is DeviceTotalMemory which allows you to see how much memory your application is currently consuming. This is especially useful since one of the Marketplace Certification Requirements says that you cannot consume more the 90MB of memory on devices with 256MB of memory or less.

For example, to get the DeviceManufacturer details you would use something like the following

private string m_DeviceManufacturer;
       
public string DeviceManufacturer
{
    get
    {
        if (m_DeviceManufacturer == null)
        {
            object val;
            if (DeviceExtendedProperties.TryGetValue("DeviceManufacturer", out val))
                m_DeviceManufacturer = val.ToString();
        }
        return m_DeviceManufacturer;
    }
}

In our case, we wrote a wrapper to all the Device Extended Properties calling it RedBit.WindowsPhone.DeviceInfo so it’s more easily accessible via an object modelimage

New to Mango
With Windows Phone Mango the above is no longer required since there is a new Microsoft Microsoft.Phone.Info.DeviceStatus Class which wraps a lot of these properties but also adds a few interesting ones.

 image

You will notice comparing the two, everything looks essentially the same, so the Windows Phone API team decided to make developers lives easier and create this class so you don’t have to use DeviceExtendedProperties anymore.  Of course, in some instances you still may have to, for example when wanting to get the DeviceUniqueId.

So what’s of Interest?  
A few properties that jump out at me are

  • IsKeyboardDeployed – Tells you if the user has has exposed the physical hardware keyboard to start typing instead of using the onscreen software keyboard
  • IsKeyboardPresent – Tells you if the device even has a physical hardware keyboard
  • PowerSource – Tells you if the device is on battery power or is plugged in

And some events that jump out are

One possible use for the IsKeyboardPresent property is for games.  If the keyboard is available, you can use physical keys to move players around instead of taking up screen real estate with your fingers. (Thanks to Barranger Ridler for that idea Smile)

For PowerSource and PowerSourceChanged, you can use this to adjust something in your app to minimize battery usage.  For example, if you are not plugged in, request for updates from a backend service every 30mins, but if the device is plugged in, request for updates every 1min.  This will significantly help conserve battery which gives a better end use experience.

Moving Onward
My hope is this is the first of many new APIs in the DeviceStatus class and we get back in line with the State and Notification Broker we had in Windows Mobile were you can do things such as intercept incoming text messages and phone calls.  For Mango, I think this is the right level of exposure that is required for now. But of course as developers we’ll always want more Smile


Tuesday, June 28, 2011 1:48:41 AM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

Quick Tip: Theme Aware Icons#

In a previous post I talked about how sometimes when selecting text when cutting and pasting on Windows Phone, the text might not be visible because the brushes where changed potentially leading to unreadable text.

Another issue I have encountered is when dealing with images.  Sometimes your design calls for adding metro style icons to your page instead of using the Application Bar which is fine, but as developers, we have to be aware that Windows Phone provides both Light and Dark backgrounds when a user customizes their Theme.  This can lead to some undesirable experiences for the user.

The Wrong Way
The first way most will go about and do it is by using an image on a button.  For example, lets say you have a button with an email icon on it as follows.

image

All looks good, but what happens when the user switches to the Light Background?  Using the Device Tab in Expression Blend, we can easily switch the background color and see that the icon is no longer visible.

image

Switching to Light results in the following

image

You’ll notice the button border is still visible, but our icon is not anymore.

How to fix?
The easiest way I find to fix this is by using paths.  With Expression Blend you can either create your own paths or import Adobe Illustrator or Photoshop files into your page.  If you like you can create the paths manually, but that can be a little of tedious process so the importing feature comes in handy!

image

So if we select the ‘email icon’ available, we will get the following path in XAML which essential translates to the email icon

<Path Data="F1M372.2549,480.7969L372.2549,470.1369L380.8289,476.8239C381.0519,476.9959,
381.3179,477.0819,381.5829,477.0819C381.8469,477.0819,382.1109,476.9959,382.3329,
476.8259L391.2659,469.9019L391.2659,480.7969z M390.6919,467.2499L381.5849,474.3089L372.5359,
467.2499z M392.4859,464.8029L371.0289,464.8029C370.3559,464.8029,369.8089,465.3499,
369.8089,466.0259L369.8089,482.0199C369.8089,482.6949,370.3559,483.2439,371.0289,
483.2439L392.4859,483.2439C393.1629,483.2439,393.7119,482.6949,393.7119,
482.0199L393.7119,466.0259C393.7119,465.3499,393.1629,464.8029,392.4859,464.8029"
Fill="Black" Height="18.441" Stretch="Fill" Width="23.903" HorizontalAlignment="Right"
Grid.Row="1" UseLayoutRounding="False" VerticalAlignment="Top"/>

So now to make the path visible in either theme, you will have to set the Fill Property of the path to PhoneForegroundBrush.

image

Add this path as the ‘Content’ of your button instead of the image, and when switching themes, the path will visible in either Light or Dark background color as follows

image

image

Why Bother?
For me there are two reasons to bother.  First one being user experience.  If your images disappear because of user settings, it’s not the best experience and doesn’t make for a professional looking app.  The second reason, your app may fail certification if this happens.  The Windows Phone Marketplace ingestion team does look at theme awareness making sure apps adhere to themes on the device.  We did fail one app once because of images disappearing (this is why I’m sharing this tip Smile) so make sure you test in both Light and Dark backgrounds.

Hopefully this tip helps you, moral of the story is test your application in both the Light and Dark backgrounds to bring that right user experience and hopefully not get stung by this on marketplace cert testing.


Tuesday, June 28, 2011 12:25:11 AM (Eastern Daylight Time, UTC-04:00) #    Comments [0]  |  Trackback

 

Windows Phone and Database Support#

After developing quite a few applications for Windows Phone both personally and via my company RedBit, one of the biggest challenges is database support.  I’m not the only one complaining about this and if you have developed apps for Windows Phone 7, you probably have encountered this challenge and come up with workarounds to get data inside your application. 

There are many reasons why you want database support but my biggest reasons are it makes life a little easier to support offline scenarios for apps and to maintain code.  Currently, we have used a combination of methods such as binary, JSON and XML Serialization/DeSerialization.  Not the greatest solution but does work.

For the next version of Windows Phone, codenamed Mango, storing data in particular structured data, is now possible and is pretty easy.  With Silverlight for Windows Phone you are going to use LINQ to SQL for database operations.  You will also use LINQ to SQL to define your database schema in code.

How to access data?

Windows Phone DataContext and Local DatabaseWell the main namespace you will require is the System.Data.Linq which contains the main class to access data called System.Data.Linq.DataContext.  Combining DataContext, ‘plain old CLR objects' (POCOs) and attributes, you can perform your CRUD operations on your data.  If you want a more thorough explanation, check out Local Database Overview for Windows Phone on MSDN.

But I’m Old School
old_schoolIf your are coming from Compact Framework world (and used to using SQL Compact, access to the data is not same.  For example, if you like using table direct to optimize data access (like I did Smile), well, you can’t do that with Windows Phone 7.  I’m assuming it’s because it’s V1 of SQL on Windows Phone but we’ll have to wait and see till next version.  From my preliminary testing and talking to the product group, they have focused on making things fast so for now I’m not worried.

What’s The Difference
If you are going to be using a local database for Windows Phone, you are going to have to be aware of some of the differences from using SQL Server. These are

  1. The database runs in process meaning, that it’s not running as a service like SQL Server but instead is only accessible only when you app is running.
  2. The database is when created is only accessible from the application that created it. The reason for this is it is created in Isolated Storage which is only accessible by the app that created it for security reasons. Think of it as a silo and other applications can’t access the data.

If you are coming from the desktop, then there are a few things you need to be aware of when using LINQ to SQL.  These are items that jump at me but all details can be found on the LINQ to SQL Support for Windows Phone on MSDN:

  1. There is no support for the ExecuteCommand which means you can run and Transact-SQL, DDL (Data Definition Language), or DML (Data Modeling Language)
  2. You cannot use LINQ to SQL to directly access ADO.NET objects such as the DataReader.  Any LINQ to SQL query will return an object collection defined by the DataContext
  3. BinaryFormatter is not supported – This basically means you will have to do some manual work here.  For example, if you are storing an image as binary in a column, you will only get binary back so conversion is not automatic.  You will have to use byte[], System.Data.Linq.Binary, or a LINQ to SQL CustomType

A few other things to be aware of

  1. If you are deploying a SQL Compact Database with your XAP (or it’s included in your project), the file is still accessible but it is read only.  If you want to write to it you will have to make a copy of it to Isolated Storage.  This might be use full if you are making a lookup table that never changes (for example drink mixes)
  2. You can update the database schema on the fly using the Structured Data API. Basically it will allow you to update Tables, Columns, Indexes, Associations/Keys but only basic updates. Complex upgrades might require a full database migration and custom code might also be required
  3. You cannot encrypt a database after it has been created. 
  4. You cannot share database across applications
  5. You can connect to a database from a Scheduled Task

What’s Next
Next up, I’ll follow up on a quick sample on creating a database and accessing the data on Windows Phone 7.  If you have already tried Local Database storage on Windows Phone let me know your experience by commenting below or via twitter @MarkArteaga


Monday, June 27, 2011 5:34:52 PM (Eastern Daylight Time, UTC-04:00) #    Comments [3]  |  Trackback

 

All content © 2012, Mark Arteaga
Related Sites
Archives
Sitemap
Disclaimer

Powered by: newtelligence dasBlog 1.9.7174.0

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Send mail to the author(s) E-mail

Theme design by Jelle Druyts