Working with local database in Windows Phone 8- Part II

This is the third post of the Windows Phone’s local database series and I will discuss updating and deleting data from a database. Here are the links to other posts in this series

Deleting data from a table

Follow these steps to delete data from a local database’s table

Step 1. Create a new class DatabaseDelete.cs

This class will contain all the methods needed in the project to delete records from any table. It is always beneficial to follow a modular approach keeping similar codes in same file.

 

 

Step 2. Add functions DeleteAllUsers and DeleteUser(string id)

We are going to create two separate functions for two different purposes. The function DeleteAllUsers() will delete all records from User_details table and DeleteUser function accepts a parameter id and deletes a single user whose id matches the parameter passed.

 

Note

  • The function DeleteAllUsers call DeleteAllOnSubmit to execute the delete operation. This function accepts a list of records and deletes all the records in that list

    If ever you need to delete duplicate records from a table then this article may prove to be useful. http://www.maskaravivek.com/blog/c/how-to-delete-duplicates-records-from-a-table-using-linq-in-c/

  • The function DeleteUser calls DeleteOnSubmit accepts a single record and deletes it.
  • In both case the changes are saved when SubmitChanges() function is called

We are done with the back end work. Let us work with the UI to use both these functions

Step 3. All a `Delete all users` button in MainPage.xaml to delete all records

<Button Content=”Delete all users” Height=”80″ Click=”Button_Click2″/>

 


 

Step 4. Add the click event handler for this button and put the code to delete all users

On the click event of this button we will insert the code to delete all users by calling DeleteAllUsers() function

 

Step 5. Modify the data template of listbox on AllUsers.xaml page to delete a single user

Now to delete a single user let us move over to AllUsers page. We will eidt the data template of the listbox to add a delete button to it. Notice the change in the XAML code where we have added a delete button and placed the id of that user in its Tag attribute.

 

 

Step 6. Add the click event handler code for this button

In the click event handler we first fetch the id from the tag element of the button which sent the click event and then call the code to delete the record from the table. Then we update the list to reflect the changes

 

The code is self-explanatory and it accomplishes the desired result.

 

Updating records in a table

Updating records is very similar to adding records to a table.

Step 1. Add a new class DatabaseUpdate.cs in your project

Continuing with our modular approach we create a new class for all database updates. Unlike delete operation there’s no function to update all records. You need to iterate manually through all records to do so.

 


 

Step 2. Add UpdateUsers function to this class

UpdateUsers function accepts id, name and email id and updates the row whose id matches in the database. It’s not necessary to update all columns in the table. You could update all columns or even just one.

Note

  • We first match the id passed in the parameter with the ID in the database
  • We take the first matched record in the entityToUpdate variable
  • We simply assign the new values and submit the changes to update the database
  • The database is not updated until we call the SubmitChanges() function

Now let us try updating all records. We will add an update function that will convert all the user_name values to lower case

Note

  • We store the fetched records in a IList
  • We then use a foreach iterator to go through all the records and update the user_name by replacing it with its lower case equivalent
  • Notice that we have used the SubmitChanges() after the foreach loop. This lets us submit all the changes at once

Now let us move over to the design part as the backend work is done.

Step 3. Add a button on MainPage.xaml to update all user names to its lower case equivalent

Again we update the MainPage.xaml to add one more button to it.

<Button Content=”Update all user names to lower case” Height=”80″ Click=”Button_Click3″/>

 

 

Step 4. Add the click event handler for the update button

The code behind is simple as you have already done all the hard work. Just call the UpdateUserToLower() function and you are done

 

Step 5. Move over to AllUsers.xaml and add an update button in its ListBox data template

The data template is already clumsily handled but that’s not a big concern right now. So go ahead and add an update button to its data template.

 

Step 6. Add a new page Update.xaml and put two text boxes in it for name and email id respectively and an Update button

We will be needing this page to update the record once it is selected. Add two text boxes and a button in it

 

 

Step 7. Add the LayoutRoot_Loaded event handler to get the id passed from AllUsers.xaml page

When an update button is clicked on AllUsers.xaml page we pass the id of the clicked button while navigating to Update.xaml. We use the navigation context to fetch the id when the layout root is loaded. We already have variables id, nam and email_id global to this page. So in the LayoutRoot_Loaded event handler just add the following line of code

id=NavigationContext.QueryString[“id”];

 

Step 8. Add the Button_Click event handler to call the UpdateUser function

On Update button click we update the user by calling the UpdateUser function which we created earlier in DatabaseUpdate.cs class


 

Step 9. Move back to AllUsers.xaml and add the code behind to handler the Update button click event

We just have to navigate to the Update.xaml page passing the id with the navigation Uri.


 

Now you are done with the code. Let run the app in the emulator to see if things work as intended.

 

I can’t show you all the screen shots but things do work. Try implementing it in your app and sound off below if you face any difficulties. In the next part of this series I will talk about updating database schema to add columns to existing tables, adding new tables or adding attributes to tables. Also we will see how one can move a referential database from app resources to isolated storage.

Get the source code here

Download full project Database-Part-2.zip

UPDATE: More posts have been added to this series. Here are the links to other posts in this series

How to send and receive push notifications for Windows Phone 8 – Introduction

You can setup your apps to receive push notifications from a web-service and update its live tile, display a toast notification or a raw notification. Firstly your app needs to be registered for receiving push notifications and then a web service (or even an app capable of sending messages to Microsoft Push Notification Service). MSDN describes its push notification service as

“The Microsoft Push Notification Service in Windows Phone is an asynchronous, best-effort service that offers third-party developers a channel to send data to a Windows Phone app from a cloud service in a power-efficient manner.”

The diagram (taken from MSDN) shows how a push notification is sent.

  1. Your app requests a push notification URI from the Push client service.
  2. The Push client service negotiates with the Microsoft Push Notification Service (MPNS), and MPNS returns a notification URI to the Push client service.
  3. The Push client service returns the notification URI to your app.
  4. Your app can then send the notification URI to your cloud service.
  5. When your cloud service has info to send to your app, it uses the notification URI to send a push notification to MPNS.
  6. MPNS routes the push notification to your app.

 

Note: It is recommended that your web-service should be authenticated and use a secure channel. Heres how you could set up an authenticated web-service. Later on we will show how to create a web-service using PHP but not ASP.NET.

To send push notifications your app/ web-service should do the following

  • For each Windows Phone device a POST message should be created
  • There are different formats for toast, tile and raw notifications. Construct a message accordingly (which will be describe later in the post). Downgrade your message for windows phone 7 by removing fields that are not supported
  • Post the messages to push notification service
  • Get the response from MPNS and respond accordingly

You can have 3 different types of notifications in your app

Toast

A toast notification displays for about 10 seconds unless the user dismisses it with a flick to the right. If the user taps the toast, by default, your app’s start screen launches.

Tile

A Tile is an image that represents your app on the Start screen. Windows Phone 8 supports three Tile templates: flip, iconic, and cycle.

Raw notifications

They are notifications that appear while the app is running.

Custom HTTP Headers

Custom HTTP headers can include a notification message ID, batching interval, the type of push notification being sent, and the notification channel URI.

  • The MessageID is the notification message ID associated with the response. If this header is not added to the POST request, the push notification service omits this header in the response.

For example: XMessageIDUUID

  • The NotificationClass is the batching interval that indicates when the push notification will be sent to the app from the push notification service. 

For example: X-NotificationClass: 1

  • The Notification Type is the type of push notification being sent. Possible options are Tile, toast, and raw. If this header is not present, the push notification will be treated as a raw notification.

For example: X-WindowsPhone-Target:toast 

Push notifications batching intervals

The batching interval describes the values different types of notifications could take for various types of delivery times.

Time/Type Toast Tile Raw
Immediate delivery 2 1 3
Delivery within 450 seconds 12 11 13
Delivery within 900 seconds 22 21 23

 

Special characters

The following characters should be encoded while using in XML

In the next few posts I will explain how to integrate tile, toast or raw notifications in your windows phone app.

Add in app purchases in your Windows Phone App

In app purchases is an excellent way to increase your revenues from your Windows Phone app. It lets you distribute your app for free and then charge the users for some added features or service. I will show you how you can easily add it in your app. You would need an active Windows Phone developer account for this tutorial as even for testing purposes you need to create a product for your app.

Step 1. Start off with submitting your app as beta version in the marketplace or if your app is already live then skip this step

Go to Windows Phone developer portal and submit a new app at https://dev.windowsphone.com/en-us/AppSubmission/Hub

 

Go to App Info and fill in the details. Reserve your app’s name and choose its category.

 

Go down to More Options and choose distribution channel as Beta. Add the live account email ids of your beta testers.

 

 

Browse and upload the XAP package for the project that you compiled earlier. You will need to fill in all the mandatory fields and upload the app icon and screenshot too.

 

Submit the app and go to App details page and note down the App ID from there.

 

Step 2. Update App ID and Publisher GUID in WMAppManifest.xml of your project


 

Step 3. Add a product to your app in Windows Phone Developer portal


 

Products can be of two types, consumable and durable. Consumable products need to be re-bought once used where as durable products need to bought only once. Fill in the details of your product and save it.

 

Add title, description and product icon.

 

We have successfully created a beta app and have also added an in app product for it. Now we need to move to the coding part.

Step 4. In app product listing

  1. The file in_app_purchase.xaml shows the XAML that could be used to list the in app products. Copy and paste in in the ControlPanel of your app.
  2. Next a clss ProductItem has been defined in file product_item.cs which is will contain the information about the product. Copy and paste it above the constructor in the MainPage.cs
  3. Lastly place the code in in_app_purchase.cs in MainPage.cs which will populate the products for the current app.

Step 5. Buy an Item ButtonBuyNow_Clicked is the event handler on click of Buy now button. It takes the user to his wallet where he can purchase the product.
The screenshot shows the product listed in the app.

Remove ads

That’s all you need to do to let the user buy any in app product from your app. I have posted another tutorial where I will show how IAP can be used to implement blocking ads in your app. That way you can offer the app free with advertisements to your users and let them make an IAP if they wish to remove the ads

Download full project WAT-Test.zip

How to integrate a Toolkit or Third party SDK with windows phone app using NuGet Package Manager

Toolkit provides the developer community with new components, functionality, and an efficient way to help shape product development. Certain controls and features are not provided by Microsoft for which we basically use Third party SDK.

We can integrate them with our project in a easy way with the help of NuGet Package Manager. Here are certain steps which needs to be followed for adding a toolkit or Third Party SDK.

1. There are two ways by which you can open the NuGet Package Manager window in your app.

Method 1

First one is to go to the menu bar and click on Project->Manage NuGet Packages

Method 2

Second way is to go to the Solution Explorer Window and right click on the project name and Choose Manage NuGet Packages.

2. Then the following screen appears before you.

3. Here you can search online for the toolkit or the SDK you wish to add and install it easily. For example I wish to add Windows Phone toolkit I can easily do it through this method.

4. Another method to install a SDK or toolkit is by directly adding their .dll file in the project. We can do this by going to Solution explorer window.

Then go to the References option given under the project . Right click on it and then choose the option add reference.


Then the following windows will appear before you.

Here you can add the extension dll files or you can choose it from your computer with the help of Browse option.

5. If you face any error while installation of the toolkit or SDK. The possible error might be that your NuGet Package is not up to date. You need to update the NuGet Package Manager before you add any toolkit or SDK. You can easily update it by going on the header menu and Choosing Tools->Extensions and Updates.

6. Then choose the update option in the Window that appears before you and see whether your NuGet package Manager is up to date or not.


In the above Windows there is no update for NuGet Package Manger.

How to integrate Google Analytics to Windows Phone app

There is always a clash between Google and Microsoft be it apps, APIs or operating system. When it comes to website analytics, Microsoft hasn’t got a solution and most websites rely on Google Analytics to keep a track on its usage. Google hasn’t released its official apps for Windows phone and likewise it doesn’t have an official SDK for analytics on windows phone but thanks to some excellent 3rd party SDKs its very simple to add it to your app. Here are four simple steps that would integrate Google analytics to your app.

 

Step 1. Create a account and get your tracking id.

 

If ever you have used google analytics for websites then this step would be quite simple. Just create a new account for your apps.

Heres the link for managing your account: http://www.google.com/analytics

 


Fill in the details and click on Get Tracking ID.

 


 

On the next screen you will be able to see the tracking ID and options to download SDKs for android and iOS . For windows phone we will be using a 3rd party SDK.We don’t need to download them.

 

Step 2. Install Google Analytics SDK for Windows Phone.

You can add Google analytics SDK for Windows 8 and Windows Phone using NuGet package manager. Here’s an article explaining how you could integrate a toolkit or third party SDK using with your Windows Phone app using Nuget Package Manager.

 

061814_1929_Howtointegr3.png

 

Step 3. Setup Google Analytics SDK to work with your tracking code by editing analytics.xml file

 

After the installation complete you will see that a file called analytics.xml has been added to your project.

Open analytics.xml and uncomment the lines corresponding to app name and app version. Also insert the tracking ID you generated earlier

 

<trackingId>UA-52075301-1</trackingId>

<appName>Google Analytics</appName>

<appVersion>1.0.0.0</appVersion>

 

Step 4. Now you can track Various events, Page views and Exceptions of your app.

 

Page view:

In the loaded event handler or the constructor of the page add the code given below to track pageviews

GoogleAnalytics.EasyTracker.GetTracker().SendView(“MainPage”);

 

Event:

To track events add the following code in the event handler for that event

GoogleAnalytics.EasyTracker.GetTracker().SendEvent(“Button clicks”, “Upload picture”, null, 0);

 

Exceptions:

To track exceptions add the following code in the catch part of a try catch statement or anywhere you intend to catch an exception

GoogleAnalytics.EasyTracker.GetTracker().SendException(exc.Message, false);

 

Heres the screen shot of the app with a click me button. The constructor for the page has the code to track page view and the click event handler has the code to track events. Also it can catch exceptions and report it.



 

Heres the screen shot of the app with a click me button. The constructor for the page has the code to track page view and the click event handler has the code to track events. Also it can catch exceptions and report it.

 



 

You can get the full source code of the project from the link given below.

 

Download full project Googleanalyticsforwindowsphone8.zip

Supports Visual studio 2012 and 2013(Windows 8 app)

 

Download full project Google analytics 8.1.zip

Supports Visual studio 2013 only(Windows 8.1 app)