How to use Converters in Windows phone app (Silverlight/WinRT)

ValueConverters can be used whenever we need to present data in an easy and controllable way such that it doesn’t interfere with other layers of the application.

Converters are called by the Data Binding mechanism whenever binding actually occurs (for example, when a control is notified about the change in the underlying property).

 

ValueConverters need to implement IValueConverter, a simple two-method interface. The two methods are

1) Convert – Modifies the source data before passing it to the target for display in the UI.

2) ConvertBack – Modifies the target data before passing it to the source object. This method is called only in TwoWay bindings.

For more reference you can see this link.

In this following blog post I shall be demonstrating you how to create an indexvalue
converter for your Windows phone app. The different steps you need to follow are

 

Step 1:

First create a class having the name IndexToColorConverter in your Project.

 

 

And add the following code to it as shown below.

 


 

Silverlight

WinRT  
Note: The only difference between Silverlight and WinRT is that the data type of parameter culture has been changed to string in WinRT.

 

Step 2:

Open the XAML page where you need to use this converter and add the following code in the namespace of the XAML page.


Note: Here Tips8 is the name of the Project. You need to replace it with your own project name.

 

Step 3:

Add the following code into PhoneApplicationPage page resources section in the XAML. It will create a Static resource within the XAML page with a specific key which will be used by the UI elements further.

 



  Note: The name of the key can be same as the Class name of color converter or something else. In order to avoid confusion we have kept both names as same.   Step 4: Now in the UI element just bind the property you wish to do so. For example in our project we have binded the Background Property and have assigned the IndexToColorConverter to it. The code for the following is

Note: Here index is the object property to which button is binded.

 

If you have any doubts regarding data binding you can refer to the following blog post.

http://windowsapptutorials.com/windows-phone/data-binding/data-binding-in-windows-phone-app-one-way-binding/


Reading and Writing in an Existing text file in Windows phone app (Silverlight / WinRT)

This is a small blog post in which I shall be explaining you how to read and write to an existing text file which is present locally in your project.

Let us suppose the text file is having the name myfile.text and is present under main root directory.

 


 

Step 1:

Now first thing you need to do is to set Build Action to Content. And, change Copy to Output Directory to Copy Always. This will ensure the file itself ships with your application. If it doesn’t, you won’t have a file to read.

 


 

Step 2:

Now you can read and write your text files easily as shown in the code below

 

Windows Phone Silverlight

Reading

 

 

Writing

 

 

WinRT

In WinRT you can access files in the local app data store using the “ms-appdata:///local/” protocol. To access files in the app package, use Windows. ApplicationModel. Package. Current. InstalledLocation.

Reading

 

 

Writing

 

 

Note: Suppose your file is not located in main directory and is located under the root folder Files as shown below.

 


 

Then file name would be


Note: You can use the same technique for an xml or json file.


Deserialize Json data using Newtonsoft Json.NET library

As we learn to make more and more advanced apps, we need more tools in out kitty to make an amazing app. Local apps work great but they can only do so much. Exchanging data from a server or web service is very essential to make a dynamic and constantly updated app. Let’s see how to work with Json in Windows Phone 8 app using the Json.NET library.

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999.

What is Json.NET library?

Json.NET is most popular, free and open source library to work with Json in Windows Phone or Windows apps. In this example, we will be learning how to parse Json data and store it in a variable which can be later used to bind that data to the UI elements such as a ListBox or LongListSelector
Let’s get started. I’ll be making a sample project with 1 style of Json and its parsing. But for the article I’ll be writing about one style, rest of the styles can be seen in the source code shared at the end of the article. Also, I won’t be covering DataBinding in this post, I shall cover that in a separate post. For the time being, the Json data is stored in a local text file stored in assets folder.

1. Adding Json.NET to your app

Go to the Nuget Package manager and search for Json.NET and add the Json.NET library to your project.

Nuget Package Manager
Adding Newtonsoft Json.NET

2. Add the following namespaces to your project

3. Convert the Json data into classes

To convert any Json data into it’s relevant classes, simple go to Json2Csharp and paste your data and this website will give you all the necessary classes. Or alternatively, yon can use the Visual Studio’s in built feature of Paste Json as Class feature from Edit -> Paste Special menu. This is my sample Json data used for this project:

Let’s understand what this data is, I’d suggest doing a search to understand the basic format of JSON data if you don’t already know. This is a object, mydata which is an array of objects. The objects in the array are all alike have 5 tags with different values in each object.

This is what the classes look like after converting the data into classes using Json2Csharp, don’t forget to paste these classes in you .cs file:

Now let’s take a moment to understand what these classes really mean. First class, MyData maps the object in the mydata array in our Json file. You can see the that this class has 5 variables with the same name as the our Json Objects in the mydata array. Second class, RootObject contains a list of class MyData, that means it acts like the array mydata as seen in our sample Json file. This RootObject is the container in which we will deserialize then Json data. It’ll then be a List of Json objects which we can use anyway we like. [DataBinding being a great use, which I will cover in another post.]

4. Read the Json data in a string

Since our file is locally hosted, we are simply reading the contents of the text file in a string using this function:
This function is called like this:

5. Deserialize

The final step.

Let’s see how and what really happened in the second statement(line 5). We created an object obj of class RootObject and then called DeserializeObject function for JsonConvert class and passed the variable containing our Json data as the parameter. That’s it and this data is now ready to be used in anyway you like. I’ll be making a tutorial on using this data with a DataBound LongListSelector soon.

Download source code from Github

Visit my website at chauhanvaibhav.net

Cancelling an Async Task

Sometimes you may need to cancel a running asynchronous task, this following tutorial will show you how. Here’s how your task will work without an async cancellation.

Step 1: Create a new Windows Phone 8/8.1 Project

Start Visual Studio and create a new Windows Phone 8/8.1 project.

Step 2: In the MainPage.xaml paste the following code

Step 3: In the MainPage.xaml.cs above the constructor declare our CancellationTokenSource

 

CancellationTokenSource.Token property of cancellationToken is passed into our asynchronous task as an argument, while doing work the task can check the token to see if cancellation has been requested.

 

Step 4: Thereafter paste the following methods below the constructor


When the restart button is clicked, we cancel the current CancellationTokenSource which will stop the running task, we then instantiate a new CancellationTokenSource & start a new task. Here’s how it works,

Download the project source code and use it as a reference.

Download AsyncCancel.zip

Integrating video file in Windows Phone 8 and Windows 8 app as app background

These days few top developers are using a video as app’s background. You would imagine it’s quite simple to do so. Yes, the process is small but you should know how exactly it must be done. We don’t just want a video put in the background but we want it to play in loops and also if the user navigates to some other page, it doesn’t start over from the beginning. Just putting a video in the background will work fine if it’s a single page app but the issue with this approach, if the user navigates to the next page, the video will start over in the next page (even if the first page passes the time elapsed of the video to the next page, you will notice a very ugly blinking in the video). Here’s what we mean:

It’s important to understand the architecture behind modern Windows apps. Every time you want to navigate from a page to another, the Frame will render the new page.

 

 

Windows Phone 8.1 XAML or Windows 8.1 app

So to have one infinite video which plays on all pages, we just need to add the MediaElement to the Frame level instead of the page level. To do this, we will need to modify the default template of the Frame. I’ve created the following style to the App.xaml, and gave it the key name RootFrameStyle.

All what we did there is changing the template to a Grid. Inside that grid we’ve added a MediaElement control behind the ContentPresenter. After that, in App.xaml.cs we apply the style to the Frame:


Note: Set the Background of your pages as Transparent or else you won’t be able to view the video.  

Windows Phone 8 (Silverlight app)

While developing for Windows Phone 8 (Silverlight app) set the target as phone:PhoneApplicationFrame instead of Frame.   And set the Style as follows:

Note: MediaElement in Windows Phone 8 Silverlight app doesn’t support IsLooping. So you will have to manually loop the video.

We used Tareq Ateik’s awesome blog post to build this tutorial. You can download the full source code for both projects and use it as a reference.

Windows Phone 8

Download VideoBG.zip (WP 8)

Windows Phone 8.1 and Windows 8.1

Download Video_BG.zip (WP 8.1 & Windows 8.1)

Developer Unlock your Windows Phone 8 device

There are always some features which you feel like testing on your device. So, you could unlock your Windows Phone 8 device and deploy apps to it directly from Visual Studio. Windows Phone Developer Registration tool is a standalone application that gets installed with the Windows Phone SDK and can be used to register your phone for development.

To register your phone by using the Windows Phone Developer Registration Tool

  • Turn on your phone and unlock the phone screen.
  • On your phone, ensure that the date and time are correct.
  • Connect your phone to your computer by using the USB cable that came with your phone.
  • On your computer’s Start screen, switch to All apps view or else just search for it using smart search
  • Under Windows Phone SDK 8.0, click Windows Phone Developer Registration. The app starts, as shown in the following image.

 

 

Click on Windows Phone Developer Registration under Windows Phone SDK to start the registration process.

 

 

Verify that the Status message displays Identified Windows Phone 8 device. Click the Register button to unlock the phone. If your phone is already registered, the Status message indicates this and you see an Unregister button.

 

 

Click Register. In the Sign In dialog box for your Microsoft account (formerly known as a Windows Live ID), enter the email address and password for your Microsoft account. Click Sign In. If you’re a registered developer, be sure to use the Microsoft account associated with your developer account. After your phone is successfully registered, the Status message displays Congratulations! You have successfully unlocked your Windows Phone.

See this MSDN article if you are having trouble registering your device.

Note: After you unregister a phone, apps that you deployed no longer run because the app licenses are no longer valid.

To unregister your phone by using the Windows Phone Developer Registration tool

  • Connect your registered phone and run the Windows Phone Developer Registration tool as described in this topic.
  • Click Unregister in the tool.

To unregister your phone on Windows Phone Dev Center

  • In your web browser, browse to the Devices page for your Dev Center account.
  • Click the Remove link next to the phone that you want to unregister.

Note: If you get a IpOverUsbSvc error while registering the device then here’s how you could resolve the problem.

http://windowsapptutorials.com/tips/general-tips/how-to-fix-ipoverusbsvc-error-while-registering-windows-phone-device/

How You Can Use a Template to Design a Fantastic Windows 8 App

Designing your own app can be an incredibly stressful process.

 

Even when you have a brilliant idea in mind and all your market research suggests that your app will blow all of your competitors out of the water, it can be terribly difficult to execute. A lot of that is down to the actual design of the app as without planning meticulously and noting down exactly what you want your app to do, actually building the software (or getting a team to do it for you) is going to be a big task.

 

But, it really doesn’t have to be.

 

Whether you’re looking to bring your Windows app to mobile devices or have users download it to their desktops, the templates from
Windows8Templates.com will help you create a wonderfully looking app mock-up.

 

1. Layout

 

While the Metro theme of Windows 8 has brought easily organisable tiles to users of Microsoft’s operating system on mobile and desktop, this can be a bit of a headache for app designers.

 

For example, how do you know if your app’s logo or cover image is going to fit all sorts of tile sizes? Does the logo look as good as a rectangle as it does a square?

 

An ugly app is an unwelcome one, especially when your users will see it every time they fire up their Windows phones and desktops. Thankfully,
Windows8Templates lets you easily customise and adjust the size of your app mock-up to ensure that it looks just right.

 

 

 

2. Colour Schemes

 

Furthermore, the templates can also help you to decide on a color scheme.

 

While your favorite color might be burgundy and this is how you’d imagined the app, does it actually work with the design of this app? Would a soft blue or bright red be better?

 

Alternatively, you may even have dozens upon dozens of color combos in your mind. Previously it would have taken painstakingly long to try them all out but with these templates the huge color palette is a click away so you can test out your proposed color schemes and figure out which one you like best.

 

 

3. Content of the App

 

Not only this but
Windows8Templates let you add content to your app mock-up. This is could be anything from the body of text in your app (particularly good if your app is data or information heavy) or more images to illustrate your point to users.

 

This part of the app design process is especially key as this is the very reason that users would download your app in the first place. Here you can test fonts, font sizes and the colour of the lettering too.

 

 

4. Clickable Prototypes

 

Once you’ve got your colors picked out, your layout has been decided upon and you have a good idea about your content, it’s important to think about how users will interact with your app.

 

For non-technical types it can be difficult to plan this – without coding knowledge how will you test which features users can click on and such?

 

Handy then that the mock-ups you create in PowerPoint with
Windows8Templates can easily be made clickable. Using action buttons you make items move on the page or even move to a new slide in the PowerPoint. These can help you figure out which features users will click on and what it could look like when they open a new window in the app.

 

Not only this, but making your prototype clickable can make it seem like a functional prototype which will only further impress those who you show your prototype to. It is even better if you can demo your prototype right on a Windows 8 touch device.

 

 

5. Visual Studio Integration with “Storyboard Shapes”

 

For the more technically savvy, PowerPoint’s ‘Storyboarding’ integration with Visual Studio can also be used to illustrate your point. Using the included Storyboard Shapes available in the Windows8Templates Pro Bundle, you can easily facilitate the handoff of you design and requirements to the development team.

 

Read more about Storyboarding User Stories or Requirements Using PowerPoint on MSDN.

 

 

 

6. Professional Uses

 

What the templates are also brilliant for is the way that they can aid your professional life.

 

Because
Windows8Templates works in PowerPoint you’ll be able to put together an entire presentation centering your app mock-up. With slides to show examples to clients, bosses and whoever else who needs to see your app proposal, there will be no room left for confusion.

 

Just your app mock-up, your design choices and an early look at what your app could be. Simple.

 

How to create a Custom MessageBox in Windows phone application

CustomMessageBox is a new control inside the Windows phone toolkit which is exactly what it sounds like, a customizable, Windows Phone-UI compliant, easy to use message box offering the following features:

 

1. Native look & feel including font sizes, layout, alignment and animations

2. Ability to display full screen or to only consume as much space as needed

3. Very simple “basic” mode with ability to easily extend it to complex scenarios

4. Customizable buttons without needing to re-template

 

In this blog post I shall explain you how to use it and will explain its different features to you.

 

Getting Started

CustomMessageBox is a component that is present in the Windows phone toolkit assembly. To use the CustomMessageBox in your app you first need to add the following toolkit into your project.

 

You can add the Windows phone toolkit to your project with the help of NuGet Package Manager.

 

1

 

If you don’t know how to integrate a toolkit with your project you can refer to the following blog post.

http://www.windowsapptutorials.com/windows-phone/how-to-integrate-a-toolkit-or-third-party-sdk-with-windows-phone-app-using-nuget-package-manager-2/

 

Different Types of Usage

 

Now I shall be explaining different uses of CustomMessageBox to you.

 

Type 1: Basic MessageBox

 

The basic usage is very similar to the default MessageBox. You need to set the different properties, add the Dismissed eventhandler when user dismisses the MessageBox and call the show method.

 

The different properties that you can customize are

 

  • Caption – sets the title caption of the message box
  • Message – the actual message to display to the user
  • LeftButtonContent, RightButtonContent – the buttons that appear on the bottom of the dialog, if you omit the text then the button won’t be shown.

 

An Example of the following type is given below

 

2

 

The code required to display the following Message is given below.

 

 

Type 2: CustomMessageBox with Content Property

 

What we have done till now is good. But what is custom comes with the content property where you insert your own content into the overall layout.  You can define your extra content in either code-behind or as a XAML resource and then set it to the Content of the CustomMessageBox.

I shall be demonstrating both the methods in this post.

 

Example 1:

Suppose you want to display the following message give below in the picture

 

3

 

The code required to display the following Message is given below.

 

 

By default the message box only takes up as much space as required but you can force it to full-screen by setting the property IsFullScreen to true.

 

Example 2:

Suppose you want to display a message box with checkbox as shown below.

 

4

 

The code required to display the following Message is given below.

 

 

Example 3:

To add a listpicker to the CustomMessagebox

 

5

 

The code required to display the following Message is given below.

 

 

Type 3: CustomMessageBox with ContentTemplate Property

You can easily predefine the data template you wish to display inside the custom message box in the Xaml window. And set the content template source directly to it.

Suppose I wish to display the following message to user

 

6

 

The steps you need to follow to display the following message are

1. Create a new data template for the above message having the name MyContentTemplate.

 

 

2. Define it inside the MainPage.xaml above the Grid named LayoutRoot as shown below.

 

7

 

3. The following code to display the custom message box with MyContenttemplate defined in the MainPage.xaml is as following

 

 

I hope this post will be helpful to you. You can download the full project source file from the link given below.

 
Download full project file Custommessagebox.zip
 

How to display message using Message box in Windows phone application

In this blog post I will explain you how to display message to user through a Message box in Windows phone application.

A message box is a very non-invasive way to tell the user that something needs his attention and maybe ask for a choice of action.

 

The Message box class that we shall be using is quite limited when it comes to user customization.

In Silverlight application there are two overload methods available as shown below.

 


 

First method

The first method allow the developer to display a simple message with an OK button – as basic as it can get and it is perfect for situations where you don’t need the user to make a decision.

 

An example is shown below

Type 1:


 

 

There is no title here and no additional buttons, so this might be a limitation in some situations.

 

Second method

The second method by allowing the developer to set the title and actually select, whether there is an OK or OKCancel button set needed.

Examples are given below

 

Type 2:

Ok button with a specific heading

 


 

Type 3:

Ok and cancel button with a specific heading. We track the response from the MessageBox via MessageBoxResult in result variable.


 

Note:

When you want to check the result, you will be prompted with an enumeration of possible values and in fact, it is bigger than you expect:


Only OK and Cancel will work if checked against. Other options will simply be ignored, since there is no Yes or No button available. Now, you might think – what about None? This also isn’t an option – when the user closes the MessageBox in a non-standard manner (e.g. by pressing the Back button), the result that is automatically passed as a response is MessageBoxResult.Cancel, even if no Cancel button is pressed.

 

I have a created a simple application to display the different types of Messagebox as explained above.

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

Download full project file Messagebox,zip

You can also refer to the following blog post where I have made an efficient use of the Messagebox class to add app review reminder in Windows phone application.

http://www.windowsapptutorials.com/windows-phone/general/adding-app-review-reminder-in-windows-phone-app-without-using-rate-my-app-toolkit/

 

 

Adding app review reminder in Windows phone app without using rate my app toolkit

Reviews are key to your app achieving success.
High ratings in the Windows Phone Store encourage new users to download your app.
So there’s no harm in reminding your users to review your app.

 

I have just prepared a following code which can be useful to you and doesn’t require any toolkit or third party SDK.

So as to use it follow the certain steps given below

 

1. Add the following namespace given below in the MainPage.xaml.cs of the application or the Start page of the application.

  2. Add the following function in the MainPage.xaml.cs of your application.   For Windows 8/Windows 8.1 Silverlight  
For Windows 8.1(WinRT)/Universal app

The code is self-understandable. The only thing you need to do is to set the variable Appname in the code.

For Windows 8.1(WinRT) you need to add the App id also.

 

If you have any doubts you can refer to the following blog post.

http://www.windowsapptutorials.com/windows-phone/isolated-storage/isolated-storage-in-windows-phone-app-store-data-in-isolatedstoragesettings/

 

3. Now call the following function in the constructor of the MainPage.xaml.cs.

 


 

When the user will open the app 4 time the following message will be shown to user.

 


 

If the user click on OK button the Review Page of Application will be shown to user.

If the user rejects the message and clicks on cancel button the same message will be shown to user 7 time. If then also he rejects the option the same process will be repeated in an interval of number 10 as written in the code. Once the user has rated the application the following message will not been shown to user.

 

Important Note:
When you are testing the application in debug state an error message will be shown to you when you click on ok button as shown below.

 


 

Until your application has passed the submission to be included in the store this error message will be shown to you.

 

Note: You can configure the interval according to your need. You can change if condition given in the review function code and set the interval according to your need.

 


 

For example I want to display this message in the interval of 5. I can change the If condition to as shown below.

 


 

I hope this post will be helpful to you. You can download the full project file from the link given below.

Download project file reviewcode.zip

You can also use ratemyapp toolkit for getting feedbacks from the user. The link of the blogpost is given below.

Adding app review and feedback reminder in Windows Phone 8 app using ratemyapp toolkit