Archive

The very weird way of checking if Bluetooth or Location is enabled

BT_GPS_WP_Blog

As I am in constant development of new features for my NFC Toolkit, I came to the point where I needed to detect if Bluetooth and Location is enabled or not.

I searched about an hour across the internet, searched all well known WPDev sites as well as the MSDN Windows Phone documentation.

The solution is a very weird one.

As I change the opacitiy of an Image depending on the stauts (on/off), I created the following async Task to check:

private async Task GetBluetoothState()
 {
 PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";

            try
 {
 var peers = await PeerFinder.FindAllPeersAsync();

                Dispatcher.BeginInvoke(() =>
 {
 BluetoothTileImage.Opacity = 1;
 });
 }
 catch (Exception ex)
 {
 if ((uint)ex.HResult == 0x8007048F)
 {
 Dispatcher.BeginInvoke(() =>
 {
 BluetoothTileImage.Opacity = 0.5;
 });
 }
 }
 }

As you can see above, we are searching for already paired devices with the Proximity API of Windows Phone. If we don’t have any of our already paired devices reachable, and we don’t throw an exception with the HResult of “0x8007048F”, Bluetooth is on. If the exception is raised, Bluetooth is off.

In a very similar way we need to check if the location setting is on:

private async Task GetLocationServicesState()
 {
 Geolocator geolocator = new Geolocator();

try
 {
 Geoposition geoposition = await geolocator.GetGeopositionAsync(
 maximumAge: TimeSpan.FromMinutes(5),
 timeout: TimeSpan.FromSeconds(10)
 );

Dispatcher.BeginInvoke(() =>
 {
 LocationStatusTileImage.Opacity = 1;
 });

}
 catch (Exception ex)
 {
 if ((uint)ex.HResult == 0x80004004)
 {
 Dispatcher.BeginInvoke(() =>
 {
 LocationStatusTileImage.Opacity = 0.5;
 });
 }
 else
 {
 //tbd.
 }

}
}

For the location services, the HResult is “0x80004004”. We are trying to get the actual GeoLocation, and if the exception is thrown, location setting is off.

On Twitter, I got for the later one also another suggestion to detect if the location settings is enabled or not, by Kunal Chowdhury (=>follow him!):

geoLocator.LocationStatus == PositionStatus.Disabled;

This would work technically, but PositionStatus has 6 enumarations. Also, as stated here in the Nokia Developer Wiki, this can be a battery intese call (depends on the implementation). I leave it to you which one you want to use.

Back to the header of this post. Catching an exception to determine the Status of wireless connections just seems wrong to me. I know this is a working “solution” and we can use that. But it could have been better implemented (for example like the networking API).

I hope this post is helpful for some of you.

Until then, happy coding!

Posted by msicc in Archive, 0 comments

How to select an item of (Rad)ListPicker control via speech recognition

This one is a short follow up to my post from yesterday about speech recognition in Windows Phone 8 apps.

I made the first steps with speech recognition in the last few  days with speech recognition, coming to the point where I had to select Items from a (Rad)ListPicker control (tried both, the Windows Phone Toolkit one as well as the Telerik one).

I was then realizing that calling the SelectedItem or the SelectedIndex does not work. By my app’s design the ListPicker has the IsExpanded property set to true, so there was one problem: in this state, it accepts only touch input.

Today I found a quick solution for this problem. If you rely on the input of the ListPicker control, just make sure that its IsExpanded state is false. You then will be able to set the SelectedItem or the SelectedIndex via code.

As always, I hope this will be helpful for some of you.

Happy coding!

Posted by msicc in Archive, 0 comments

Make your app listening to the user’s voice

speech_recognition_WPLogo

In one of my recent projects, I added speech recognition to start the app as well as for using the app. This blog post gives you a short overview on what’s possible and how to do it.

How to start your app with certain conditions:

Any app can be started by the simple voice command “open [AppName]” on Windows Phone. But what if we want to start certain functions when calling our app via speech? Then you’ll need a so called Voice Command Definition (VCD) file. This is a xml file that tells the OS to launch a certain function of your app.

Before we can start, please make sure you enabled ID_CAP_SPEECH_RECOGNITION, ID_CAP_MICROPHONE, and ID_CAP_NETWORKING capabilities in your app manifest.

Let’s have a look at a VCD with two different launch arguments:

<?xml version="1.0" encoding="utf-8"?>

<VoiceCommands xmlns="http://schemas.microsoft.com/voicecommands/1.0">
 <CommandSet xml:lang="en-US">
 <CommandPrefix>speech test app</CommandPrefix>
 <Example> speech test app</Example>

<Command Name="open MainPage">
 <Example> open the MainPage </Example>
 <ListenFor> open the MainPage </ListenFor>
 <ListenFor> bring me to Mainpage </ListenFor>
 <ListenFor> let me see my MainPage </ListenFor>
 <Feedback> loading Mainpage....</Feedback>
 <Navigate />
 </Command>

<Command Name="open SettingsPage">
 <Example> open the settings page</Example>
 <ListenFor>open settings</ListenFor>
 <ListenFor>bring me to settings page</ListenFor>
 <ListenFor>let me see my settings page</ListenFor>
 <Feedback>opening settings ...</Feedback>
 <Navigate />

</Command>

</CommandSet>
 </VoiceCommands>

As you can see, the syntax is pretty easy to use. Here is some short explanation about the commands:

  • <CommandPrefix> is for telling the OS how to launch your app
  • <Command Name=”xxx”> is for telling the OS which launch parameter should be passed to your app
  • <ListenFor> defines which speech cases you want to allow to let the OS launch your app (pretty important point)
  • <Example> Text entered here is shown in TellMe’s speech Window and on the “What can I say?” page
  • <Feedback> this is the answer of TellMe to the user

The next part is to load the VCD file once the app starts. Therefore, you will need to add the VCD file in the App constructor. I created an async Task for that:

private async Task InitializeVoiceCommands()
 {
 await VoiceCommandService.InstallCommandSetsFromFileAsync(new Uri("ms-appx:///VoiceCommandDefinitions.xml"));
 }

It is recommended that you set “Copy to Output Directory” property of the VCD file to “Copy if newer”.

Now that we have implemented and loaded our VCD file, let’s have a look on how we can open our app based on the arguments. Based on that VCD file, our app gets key/value pairs of the launch arguments. The implementation is pretty easy in a few lines of code:

if (NavigationContext.QueryString.ContainsKey("voiceCommandName"))
 {
   string voiceCommandName = NavigationContext.QueryString["voiceCommandName"];
   switch (voiceCommandName)
    {
       case "open MainPage":
       //let the App launch normally
       //you can also pass other launcharguments via the VCD file that could launch other functions
       break;

       case "open SettingsPage":
       //let the App lauch immediately to the settings page
       NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
       break;
     }
 }

And with this few lines we already added our app with individual voice commands to the speech function of the OS.

 

Using your app with in app voice commands:

We now learned how to start our app with certain conditions. However, this is not how we are using the speech recognition within our app.

There are several ways on how you can implement in app voice commands. I will show you two of them.

First of all, using the Windows button does not work in app. You will need to add a dedicated button to start the voice recognition.

Let’s start with a List<string> or string[] array, and launch the SpeechRecognizerUI:

            try
            {
                //initalize speech recognition
                SpeechRecognizerUI speech = new SpeechRecognizerUI();

                List<string> InAppCommandList = new List<string>
                {
                       "goto home",
                       "goto settings",
                        "set name",
                        "set age",
                        //add more to that list as you need
                };

                //load the List as a Grammar
                speech.Recognizer.Grammars.AddGrammarFromList("InAppCommandList", InAppCommandList);

                //show some examples what the user can say:
                speech.Settings.ExampleText = " goto home, goto settings, set name, set age ";

                //get the result
                SpeechRecognitionUIResult result = await speech.RecognizeWithUIAsync();

                //delegate the results
                switch (result.RecognitionResult.Text)
                {
                    case "goto home":
                        //your code here
                        break;
                    case "goto settings":
                        //your code here
                        break;
                    case "set name":
                        //your code here
                        break;
                    case "set age":
                        //your code here
                        break;
                }
            }
            catch (System.NullReferenceException)
            {
                //do something with the Exception
            }

 

As you can see, there are only a few steps needed:

  • initalize speech recognition
  • load the List<string>/string[] as a Grammar
  • get the result
  • delegate the results

You might have noticed that I wrapped the code into a try/catch block. I needed to do that as I often got a NullReferenceException on closing without voice input or also if no text was heard. This way, your app will not crash.

There is also another way to add a Grammar to the speech recognition engine: SRGS (Speech Recognition Grammar Specification), which is again a XML file that contains which input is accepted.

While I was working on this app, I noticed that it is pretty powerful – and complex. This is why I decided to mix both methods to get things done (you know, timelines and such). I will dive into that topic deeper and then write another blog post about it. But for now, I’ll show you a simple example.

In this case, I wanted the SpeechRecognizerUI to only accept numbers as input. This is how my SRGS file looks like:

<?xml version="1.0" encoding="utf-8" ?>

<grammar version="1.0" xml:lang="en-US" root="Command" tag-format="semantics/1.0"
 xmlns="http://www.w3.org/2001/06/grammar"
 xmlns:sapi="http://schemas.microsoft.com/Speech/2002/06/SRGSExtensions">

<rule id="Command" scope="public">
 <item repeat="1-20">
 <ruleref uri="#Numbers"/>
 </item>
 </rule>

<rule id="Numbers">
 <one-of>
 <item >1</item>
 <item >2</item>
 <item >3</item>
 <item >4</item>
 <item >5</item>
 <item >6</item>
 <item >7</item>
 <item >8</item>
 <item >9</item>
 <item >0</item>
 </one-of>
 </rule>

</grammar>

If you add a SRGS file as to your project, the correct structure is already implemented. You only need to set the root to the first rule you want to be executed. In my case, I defined a rule with the id Command in a public scope (this way, you would also be able to call it from another Grammar).

The rule returns items that will occur minimum 1 time and maximum 20 times. Basically, this defines the range of the input length.

To make the SpeechRecognitionUI only accepting numbers, I defined another rule that contains a list of numbers. the <one-of> property defines here that any of the numbers is accepted. With <ruleref uri=”#Numbers”/> I am telling my app to accept any of the numbers as often as they occur until the count of 20.

Now let’s have a look on how to implement this Grammar into our app and connect it to our SpeechRecognizerUI:

 SpeechRecognizerUI speech = new SpeechRecognizerUI();

            //generate a Numberonly Input Scope based on a SRGS file
            //the ms-appx:/// prefix will not work here and return a FileNotFoundException!
            Uri NumberGrammarUriPath = new Uri("file://" + Windows.ApplicationModel.Package.Current.InstalledLocation.Path + @"/NumberOnlyGrammar.xml", UriKind.RelativeOrAbsolute);

            speech.Recognizer.Grammars.AddGrammarFromUri("NumberGrammarUriPath", NumberGrammarUriPath);

            SpeechRecognitionUIResult speechRecognitionResult = await speech.RecognizeWithUIAsync();

            if (speechRecognitionResult.ResultStatus == SpeechRecognitionUIStatus.Succeeded)
            {
                //using Regex to remove all whitespaces
                string NumberInputString = Regex.Replace(speechRecognitionResult.RecognitionResult.Text, @"\s+", "");
                // do somethin with the string
            }

We are again calling the SpeechRecognizerUI, but this time we are loading our XML formatted SRGS file as Grammar. Notice that loading the file only works with the way above. Using the “ms-appx:///” prefix will return a FileNotFoundException and crash your app.

Instead of AddGrammarFromList we are using AddGrammarFromUri to load the file.

By checking the SpeechRecognitionUIStatus, we are performing actions only if the recognition was succesful based on our SRGS Grammar. If you want to perform other actions on non-success status, you will be able to implement the following enumerations:

  • Succeeded (0)
  • Busy (1)
  • Cancelled (2)
  • Preempted (3)
  • PrivacyPolicyDeclined (4)

As you can see, basic speech recognition is fast to implement. As always, I hope this post is helpful for some of you.

I also recommend to read these pages on MSDN about speech for Windows Phone: http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207021(v=vs.105).aspx

Happy coding everyone!

Posted by msicc in Archive, 1 comment

How to modify the Background of a Telerik RadListPicker Control

In one of my current projects, I needed to change the Background of the Popup on a Telerik RadListPicker control. While it took me some time, I want to share how to achieve that to make it easier for you.

First, you need to create a copy of the RadListPicker Template. You can use either Blend or Visual Studio 2012 to achieve this.

In Blend just go to the menu and choose Object -> Edit Style -> Edit a Copy. In Visual Studio, right click on your RadListPicker in the Designer Window and choose Edit Template -> Edit a Copy.

Now you will find a new Style within your Application.Resources in App.xaml.

To change the style you have to modify two parts, the PopupHeader and the Popup itself.

To change the Background of the PopupHeader search for telerikPrimitives:RadWindow x:Name=”Popup” . Under that, you will find a Grid.

In this Grid, you will need to set the Background to the desired Color or Brush you want to use:

<Grid Background="#FF0A0D38" telerik:RadTileAnimation.ContainerToAnimate="{Binding ., ElementName=PopupList}">

To change the Background of the List in you ListPicker, you will have to style the Background of the underlying RadDataBoundListBox Control:

<telerikPrimitives:RadDataBoundListBox x:Name="PopupList" CheckModeDeactivatedOnBackButton="False" DisplayMemberPath="{TemplateBinding DisplayMemberPath}" IsCheckModeActive="{Binding SelectionMode, Converter={StaticResource SelectionModeToBooleanConverter}, RelativeSource={RelativeSource TemplatedParent}}" telerik:InteractionEffectManager.IsInteractionEnabled="True" ItemContainerStyle="{TemplateBinding PopupItemStyle}" Grid.Row="1" Style="{TemplateBinding PopupStyle}">
   <telerikPrimitives:RadDataBoundListBox.Background>
      <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
          <GradientStop Color="#FF0A0D38" Offset="0"/>
          <GradientStop Color="#FF9FCFEC" Offset="1"/>
      </LinearGradientBrush>
   </telerikPrimitives:RadDataBoundListBox.Background>
</telerikPrimitives:RadDataBoundListBox>

As you can see, the I changed the Background to a GradientBrush to match the rest of the application.
The result looks like this:

wp_ss_20131021_0001

As always, I hope this will be helpful for some of you.

Happy coding!

Posted by msicc in Archive, 1 comment

How to save a List or a Collection on a NFC tag

 

WP8_NFC_PostLogo

As I am currently working again on my NFC app, I needed to save an ObservableCollection to a tag. My first attempts resulted in a heavily overlong string that I wasn’t able to save.

Anyways, after a short convo on Twitter, I went for the right way – serialize to JSON.

The first thing you’ll need for that is the JSON.NET library, which you can get here or via the NuGet package manager in Visual Studio.

After that, you will be able to save your List or ObservableCollection in a few easy steps.

One thing I need to recommend is to make the names in your class/viewmodel as short as possible. Here is my example:

public class ListItems
    {
        //ListItems
        public string i { get; set; }
        //isChecked
        public bool iC { get; set; }
    }

You will need every space you can get on your tag, so you really should go for a similar way like I did above.

After you are done with that, you only need one line of code to convert your List/Collection for writing on your tag:

var ListToSave = JsonConvert.SerializeObject(ItemsList);

Now you will be able to save it as a Text record or  whatever record type you need to save it to.

Deserializing the JSON string works also with only one line of code:

ItemsList = JsonConvert.DeserializeObject<ObservableCollection<ListItems>>(StringFromYourTag);

Then you set the ItemsSource of your ListBox to that (or whatever else the List/Collection is for).

I my case, I was able to save a Collection of 25 items to my tag (writable size 716 bytes) with having still about 200 bytes left in this way.

As always, I hope this will be helpful for some of you.

Happy coding!

Posted by msicc in Archive, 0 comments

Use Telerik RadControls for WP? Then use RadDiagnostics to enable users to find bugs!

I know this is a little provocative title – that is my intention. And of course I will tell you why.

I am participating in several betas for Windows Phone apps. I know some of the developers from Twitter, and had several conversations  about bug finding and solving methods. In the end, we as developers have all one goal: a buttery smooth running app without any bugs.

Some of the betas I use are also using Telerik RadControls. They enable us developers to easily create awesome apps without writing the controls form the ground up. On Top, we are able to customize them for our needs with a bit of XAML manipulation.

One of these controls is RadDiagnostics. RadDiagnostics is catching all unhandled exceptions from your application. And believe me, there will be a ton of it – even if you handle a lot of them already.

I didn’t believe that, too. But then I ran the beta of my TweeCoMinder app for Windows Phone. I tested the app a lot before publishing my beta, including several scenarios like no network connection available, low battery, and so on. At this time, I stumbled over the RadDiagnostics Control in the documentation.
I immediately saw the advantages of using this control:

  • advanced error logging, including a great bunch of information like OS Version, device, network type, and more
  • the app won’t crash even on unhandled exceptions
  • the user feels more integrated in the development process
  • users tend to use the app in other ways than we developers think – and we can’t even get close to catch all those usage scenarios while testing alone
  • there are a lot of users that are really searching for bugs – which is both a good and a bad thing

Let me hook into the last point a bit deeper – as we are able to get the most from it. If users find bugs, they will get either annoyed and stop using our apps or they will talk about it. Let us make them talk about the problems to us, the developer! Like I mentioned above, the RadDiagnostics control makes this very easy for the user.

A MessageBox shows up where the user is asked to send us the report, which is done via email. This has two additional advantages: First, we are able to collect all kind of errors. An even bigger advantage: We are able tor respond directly to the user as we have their mail address. I learned a lot during the first beta versions of TweeCoMinder, be it how users use my app as well as from the coding part – and I was able to continuously improve my app.

Some of you might argue that you don’t want the user to see your code. Really, that is stupid. An average user does not even know what all those lines in of the exception mean. Only developers are able to understand what is going on. Where is the problem? That they see you have an exception at point x? Chances are very high, that they had the same exception at another point and needed them to iron out.

Personally, I don’t have a problem with the fact that the exception is readable for some beta tester/users. I made the experience that users love to give feedback – if you make it very easy for them. RadDiagnostics is a very easy way as it needs only three taps (ok => choose mail account => send button).

As this is a dev post, here is how easy it is to integrate it into your app:

  • Declare the RadDiagnostics in public partial class App : Application
    public RadDiagnostics diagnostics;
  • Initiate Telerik ApplicationUsageHelper in private void Application_Launching(object sender, LaunchingEventArgs e)
ApplicationUsageHelper.Init("0.9.5");
  • call RadDiagnostic in the App() constructor:
diagnostics = new RadDiagnostics();
 {
diagnostics.EmailTo = "yourmail@outlook.com";
diagnostics.EmailSubject = "Here is your email subject";
diagnostics.HandleUnhandledException = true;
diagnostics.Init();
 }

That’s all you need to get it working. A few line of codes that will give you so much input to improve your app, which will result in this message:

ReadDiagnosticsMSG

Once again, if you use RadControls for Windows Phone, then use RadDiagnostics to let users help you finding bugs. You will not get better and more helpful feedback other than this!

You can find the complete documentation of RadDiagnostics here: http://www.telerik.com/help/windows-phone/diagnostics-gettingstarted.html

Another great article that helps you to deeply understand how RadDiagnostics work is over at Kunal Chowdhury’s blog.

Feel free to discuss your sight below in comments. Until then, Happy coding!

Posted by msicc in Archive, 0 comments

Getting productive with WAMS: about the mpns object (push data to the user’s Windows Phone)

WAMS

When it comes to Mobile Services, there are a lot of things you can do with the user’s data. One of them is to update the Live Tiles of their apps as well as send them Toast Notifications. To understand how the mpns (Microsoft Push Notification Service) is working, please see the image below and read this article on MSDN: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402558(v=vs.105).aspx

mpns graph

Windows Azure has a pretty basic example to get the Live Tiles updated: http://www.windowsazure.com/en-us/develop/mobile/tutorials/push-notifications-to-users-wp8/. However, this example sends the data from the app to Azure and directly back to the user’s device. It is a good start if you want to understand how it works, but it does not reflect the most common scenario: the server is fetching data with the app closed on the users device.

The most important part: getting a valid push channel from the Push Client Service

Now that we know how the push notification service works, we need our Windows Phone app to acquire a valid push channel. This is done by a few lines of code in App.xaml.cs. First, we need a globally declared push channel:

public static HttpNotificationChannel pushTileChannel { get; set; }

With this global variable we are now able to get a valid push channel into our app and to our Mobile Service:

public static void AcquirePushChannel()
        {
                  pushTileChannel = HttpNotificationChannel.Find("msicc-test");

                if (pushTileChannel == null)
                {
                    pushTileChannel = new HttpNotificationChannel("msicc-test");

                    pushTileChannel.Open();

       //this binds the push notification to your live tile       
       pushTileChannel.BindToShellTile();

       //this binds the push notification to toasts
       pushTileChannel.BindToShellToast();

 }        

                IMobileServiceTable<pushChannel> pushChannelTable = App.MobileService.GetTable<pushChannel>();
                var channel = new pushChannel { Uri = pushTileChannel.ChannelUri.ToString() };
                pushChannelTable.InsertAsync(channel);
           }

The Find(“desiredNameOfChannel”) method creates or finds a channel exclusive to your app and should be the same for all of your users. The Open() method finally opens the connection from your app to the Push Client Service. To automatically receive the updates for Tiles and Toast, we use the BindToShellTile() and BindToShellToast() methods.

Important for images:

You need to allow the url(s) the images can be from. To this, you need to add the desired uri in the BindToShellTile() method. If you have more than one uri the images come from, just create a Collection of Uri and add them to the BindToShellTile() method  overload. Please note that only the top level domain needs to be allowed (specifying folders is not supported).

public static Collection<Uri> allowedDomains = 
            new Collection<Uri> { 
                                                new Uri("https://yourmobileservice.azure-mobile.net"), 
                                                new Uri("https://yourseconduri.com/") 
                                              };

pushTileChannel.BindToShellTile(allowedDomains);

But that’s not all. We need to add the push channel uri  also to our Windows Azure table to update the users data. This what the last three lines of codes are for. I highly recommend to separate the push channel table from your user data table, to be able to operate easily on this table. In order to avoid duplicate channels (which can be very annoying for users and yourself), we should update our server side data script:

function insert(item, user, request) {

   var channelTable = tables.getTable('pushChannel');
        channelTable
            .where({ uri: item.uri })
            .read({ success: insertChannelIfNotFound });
        function insertChannelIfNotFound(existingChannels) {
            if (existingChannels.length > 0) {
                request.respond(200, existingChannels[0]);
            } else {
                request.execute();
            }
        }
}

This way, you are all set up for updating your app’s Live Tile and for Toast Notifications. But until now, our Mobile Service does not send any data to our app.

How to update Live Tiles and send Toast Notifications from Mobile Services

Once our server side code has fetched all data, we certainly need to update our user’s Live Tiles or even send Toast Notifications. We are able to send the following types of Tiles and Notifications:

The FlipTile is the coolest of all and has the most options you can use. That’s why I choose it over the ‘normal’ Tile. To get the data out to our users, we are using this code:

//call the push channel table

var channelTable = tables.getTable('pushChannel');

//send toast and Tile:

channelTable
    .where({user:userid})
    .read({
        success: function(channels){
            channels.forEach(function(channel) 
                {
                    push.mpns.sendToast(channel.uri, {
                        text1: ToastText1,
                        text2: ToastText2
                        }, {
                    success:function(pushResponse) {
                        console.log("Sent toast: ", channel.id, pushResponse);
                    },
                    error: function (error){
                        console.error("error in Toast Push Channel: " +  channel.id, error)
                    }
                });
                push.mpns.sendFlipTile(channel.uri, {
                     backgroundImage: backgroundImage,
                     backTitle: backTitle,
                     backContent: BackContent,
                     smallBackgroundImage: SmallBackgroundImage,
                     wideBackgroundImage: WideBackgroundImage,
                     wideBackContent:  WideBackContent,

                }, {
                    success:function(pushResponse) {
                        console.log("Sent tile:" ,  channel.id, pushResponse);
                    },
                    error: function (error){
                        console.error("error in Push Channel: "  channel.id, error)
                    }
                });
            });
        }
    });

Like you can  see, we are using quite a few fields in the mpns object payload. You can click on the types above to see which fields are supported on each type.

Images that you send to your users are sent need to be a valid url to the image. The maximum size is 80 KB. If your Images are bigger, they will not be sent!

The mpns object has both a ‘success’ and an ‘error’ callback. The error callback is automatically written to the log. However, it is very hard to identify which id is causing the error in this case. That’s why you should implement it in the way I did above. This way, you know exactly which id is causing an error and which id received their update correctly.

We are also able to add some extra functions to respond to the success and error callbacks. I still need to do this on my WAMS, and I will write about the measures I took in the different cases once I did it (I only started using Azure a few month ago, so I am also still learning). If you are interested, here is a list with all possible response codes for the mpns object: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff941100(v=vs.105).aspx#BKMK_PushNotificationServiceResponseCodes

Conclusion

Like you see, Windows Azure Mobile Services allows us to send out updates to the user very easy within less than an our for setting it up. There are a few things we need to take into account – in fact, most of this points took me a lot of time to find out (as it is the first time I use push in general). As always, I hope this post is helpful for some of you.

Until the next post, happy coding!

Posted by msicc in Archive, 0 comments

How to use and customize “pull to refresh” on Telerik RadDataBoundListBox

If you are following me and my development story a little bit, you know that I am building a new app (ok, it’s RTM already).

I wanted to add a manual refresh button to my MainPage, but there was no place left on the AppBar. So I started thinking about alternatives. As I am using a lot of Telerik controls, I found something that perfectly suits my needs: RadDataBoundListBox .

Wait… what?

You read it right, I am using a ListBox that holds only one item. The reason is very easy: It has the “pull to refresh” feature built in. But it is not all about adding it and you are fine.

raddataboundlistbox-features-pulltorefresh

The first thing we need to do is to set the “IsPullToRefreshEnabled” property to “True”. Honestly I don’t like the controls arrow as well as I wanted to remove the time stamp line on it.

Luckily, we are able to modify the control’s style. Just right click on the RadDataBoundListBox in the designer window and extract the “PullToRefreshIndicatorStyle”.

Screenshot (187)

After choosing whether you want the new Style to be available only on one page or in your app over all, name the new Style as you like. This will add the XAML code as a new style to your application/page resources. Now the fun begins. The first thing I changed was the arrow.

To do this,  I added the beloved metro arrow in a circle (go for the “ContentPresenter  with the name “PART_Indicator””) – done:

<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Grid>
 <Grid Name="backgroundGrid" Width="48" Height="48" Visibility="Visible">
   <Path Data="M50.5,4.7500001C25.232973,4.75 4.75,25.232973 4.7500001,50.5 4.75,75.767029 25.232973,96.25 50.5,96.25 75.767029,96.25 96.25,75.767029 96.25,50.5 96.25,25.232973 75.767029,4.75 50.5,4.7500001z M50.5,0C78.390381,0 101,22.609621 101,50.5 101,78.390381 78.390381,101 50.5,101 22.609621,101 0,78.390381 0,50.5 0,22.609621 22.609621,0 50.5,0z" Stretch="Fill" Fill="#FFF4F4F4" Name="Stroke" Visibility="Visible" />
     </Grid>
       <Path Data="F1M-224.887,2277.19L-240.615,2261.47 -240.727,2261.58 -240.727,2270.1 -226.173,2284.66 -221.794,2289.04 -202.976,2270.22 -202.976,2261.47 -218.703,2277.19 -218.703,2235.7 -224.887,2235.7 -224.887,2277.19z" Stretch="Uniform" Fill="#FFFFFFFF" Width="26" Height="26" Margin="0,0,0,0" RenderTransformOrigin="0.5,0.5">
         <Path.RenderTransform>
             <TransformGroup>
                <TransformGroup.Children>
                  <RotateTransform Angle="0" />
                     <ScaleTransform ScaleX="1" ScaleY="1" />
                 </TransformGroup.Children>
              </TransformGroup>
          </Path.RenderTransform>
   </Path>
</Grid>
</Viewbox>

No we are going to  remove the time stamp. If you simply delete the TextBlock, you will get a couple of errors. The TextBlock is needed in the template. What works here is to set the Visibility to Collapsed. As the control has different Visual States, we need to set the Visibility of every occurrence of  “PART_RefreshTimeLabel” in every state to collapsed. Finally we need to do the same at the TextBlock itself to hide the time stamp line.

Ready… or not?

Now we have our style ready to be used, right? Let’s have a look how it looks when we are using our control right now:

(link for app users)

As you can see, the behavior of the Pull to refresh – control is not like expected. In this state, we have to throw it up first, then it will recognize the pull gesture. To get rid of this, we need to adjust two additional things.

The first thing we need to do is set the “UseOptimizedManipulationRouting” property to “False”.

Second, after setting the ItemsSource of the RadDataBoundListBox, we need to bring the first item into view. You can do this very easily:

RadDataBoundListBox.BringIntoView(ItemsSourceName.First());

After that, we have finally a customized and smooth Pull to refresh function on our RadDataBoundListBox:

(link for app users)

At this point I want to give a special thanks to Lance and Deyan from Telerik for their awesome support on this case.

Happy coding everyone!

Posted by msicc in Archive, 0 comments

Are lockscreens outdated?

In one of their latest shows, Vernon and Andrew from the awesome Glance and Go Radio discussed whether or not having a lockscreen still makes sense.
Unlike many people may think, lockscreens were not really meant to protect a device from being accessed by other individuals, but derived from the keypad locks cell phones used to have to avoid accidentally performing a phone call while carrying the device in your pocket (butt dialing).

While you may argue about the actual use on touch devices, I find lockscreens a great way to further personalize my device. Especially with the new features Microsoft introduced with Windows Phone 8.
Meanwhile several dozens of all kinds of lockscreen apps can be found in the Windows Phone store. Some of them offering quite unique features. I’m currently going with Lock Buster, which you can find here.

And even though there are certainly more important parts of the OS which need optimization and improvements, I seriously hope Microsoft hasn’t reached their end of the line with the lockscreen options. I personally would like to be able to add more than just 5 apps to it. I don’t see a single reason why a second array of icons couldn’t be added.
And while these icons at least serve the purpose of letting users know about the amount of new items for the configured apps, I don’t see it necessarily stop there. I’d love to be able to tap the icons to have them reveal more detailed information about what’s awaiting me. These could simply be displayed above the clock. Perhaps with a net slide or fade in effect.
That’s just my personal opinion of course.

What do you think? Would you rather get rid of this ancient feature or keep it?  Share your thoughts in the comments below.

 

Posted by dkp1977 in Archive, 1 comment

How to search the Windows Phone Store within your app

MPSearch

I am currently working on my NFC app, and I want to make it easier for the end user to search for the AppId which you need for the LaunchApp record. So I thought about a possible solution for this, and of course the easiest way is to search the app.

If you only want to search the Windows Phone Store and let show some search results, there is the MarketplaceSearchTask, which you can call as a launcher. The only problem is, you cannot get any values into your app this way. But I found a way to get the results into my app. This post is about how I did it.

The first thing you will need to add to your project is the HTMLAgilitypack. It helps you parsing links from an HTML-based document. Huge thanks to @AWSOMEDEVSIGNER (follow him!), who helped me to get started with it and understand XPath. Xpath is also important for the HAP to work with Windows Phone. You will need to reference to System.Xml.Xpath.dll, which you will find in

%ProgramFiles(x86)%Microsoft SDKsMicrosoft SDKsSilverlightv4.0LibrariesClient or
%ProgramFiles%Microsoft SDKsMicrosoft SDKsSilverlightv4.0LibrariesClient

Ok, if we have this, we can continue in creating the search. Add a TextBox, a Button and a ListBox to your XAML:

            <Grid.RowDefinitions>
                <RowDefinition Height="90"></RowDefinition>
                <RowDefinition Height="90"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
            </Grid.RowDefinitions>
            <TextBox x:Name="MPsearchTerm" Height="80" Grid.Row="0"></TextBox>
            <Button x:Name="searchButton" Height="80" Grid.Row="1" Content="search" Click="searchButton_Click_1"></Button>
            <ListBox Grid.Row="2" x:Name="ResultListBox">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Image Source="{Binding AppLogo}" 
                                   Height="50" 
                                   Width="50" 
                                   Margin="10,0,0,0">
                            </Image>
                            <TextBlock Text="{Binding AppName}"
                                       FontSize="32"
                                       Margin="12,0,0,0" >
                            </TextBlock>

                        </StackPanel>

                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

After creating this, we will hook up the Click-Event of our Button to create our search. We are going to use the search of windowsphone.com to get all the information we want. You can parse any information that you need like ratings etc., but we focus on AppId, Name of the App and of course the store Logo of each app.

First, we need to create the search Uri. The Uri is country dependent like your phone. This is how we create the Uri:

string currentLanguage = CultureInfo.CurrentCulture.Name;
string searchUri = string.Format("http://www.windowsphone.com/{0}/store/search?q={1}", currentLanguage, MPsearchTerm.Text);

After that, we are using a WebClient to get the HTML-String of  the search. I used the WebClient as I want to make it usable on WP7.x and WP8.

//start WebClient (this way it will work on WP7 & WP8)
WebClient MyMPSearch = new WebClient();
 //Add this header to asure that new results will be downloaded, also if the search term has not changed
// otherwise it would not load again the result string (because of WP cashing)
MyMPSearch.Headers[HttpRequestHeader.IfModifiedSince] = DateTime.Now.ToString();
//Download the String and add new EventHandler once the Download has completed
 MyMPSearch.DownloadStringCompleted += new DownloadStringCompletedEventHandler(MyMPSearch_DownloadStringCompleted);
MyMPSearch.DownloadStringAsync(new Uri(searchUri));

In our DownloadStringCompletedEvent we now are parsing the HTML-String. First thing we need to do is to create a HTML-Document that loads our string:

//HAP needs a HTML-Document as it is based on Linq/Xpath
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(e.Result);

The next step is a bit tricky if you do not know Xpath. You need to got through all the HTML elements to find the one that holds the data you want to parse. In our case it is the class called “medium” within the result table “appList”.

var nodeList = doc.DocumentNode.SelectNodes("//table[@class='appList']/tbody/tr/td[@class='medium']/a");

Note that you have to use ‘ instead of ” for the class names in Xpath. I recommend to open a sample search page in an internet browser and look into the code view of the page to find the right path.

image

Now that we have a NodeList, we can parse the data we want:

foreach(var node in nodeList)
            {
                //get AppId from Attributes
                cutAppID = node.Attributes["data-ov"].Value.Substring(5, 36);

                //get ImageUri for Image Source 
                var ImageMatch = Regex.Match(node.OuterHtml, "src");
                cutAppLogo = node.OuterHtml.Substring(ImageMatch.Index + 5, 92);

                // get AppTitle from node
                //Beginning of the AppTitle String
                var AppTitleMatch = Regex.Match(node.InnerHtml, "alt=");
                var StringToCut = Regex.Replace(node.InnerHtml.Substring(AppTitleMatch.Index),"alt="",string.Empty);
                //End of the AppTitle String
                var searchForApptitleEnd = Regex.Match(StringToCut, "">");
                //FinalAppName - cutting away the rest of the Html String at index of searchForApptitelEnd
                // if we won't do that, it would not display the name correctly
                cutAppName = StringToCut.Remove(searchForApptitleEnd.Index);
           }

As you can see, we need to perform some String operations, but this is the easiest way I got the result I want – within my app. As always I hope this will be helpful for some of you.

You can download full working sample here:  MarketplaceSearch.zip

Happy coding!

Posted by msicc in Archive, 0 comments