#CognitiveServices–#Bing Autosuggest API, cool new feature and some sample code

Hi !

After my yesterday post on how to get the new Cognitive Services API keys, today I’ll review one of the new services: Bing Autosuggest API. So as the main documentation explains:

The Bing Autosuggest API lets partners send a partial search query to Bing and get back a list of suggested queries that other users have searched on. In addition to including searches that other users have made, the list may include suggestions based on user intent. For example, if the query string is “weather in Lo“, the list will include relevant weather suggestions.

As today, there is no samples or client library in the official SDK, so I decided to create one of my own for this. In my samples repository, you’ll find a 2 projects solution which includes a sample console app and the Client library to work with the Bing Autosuggest API.

image

The AutosuggestClient class is the one who performs the calls to the API and also transforms the JSON result into .Net classes. Cool experience here, I found a nice website: http://json2csharp.com/ which basically generates the necessary .Net clases from a JSON response.

image

So with this, I generate my contract classes and my AutoSuggest library becomes a little more friendly.

image

Finally the ServiceClient class, is based on the Microsoft.ProjectOxford.Common.ServiceClient class and uses some basic HttpClient code to perform the request to the Bing API.

image

Now in Toronto, my sample and test search criteria will change a little, in example make a search for “toronto rap” will return results like “toronto raptors”, “toronto raptors schedule”, and more.

Clipboard01

GitHub Sample https://github.com/elbruno/Blog/tree/master/CognitiveServices/BingAutoSuggest

Greetings @ Toronto

-El Bruno

References

Advertisements

#AZURE – Enviando datos a un #AzureIoTHub utilizando un HttpClient y texto plano

Hola !

Azure IoT tiene un excelente SDK que incluye ejemplos para apps C#, apps Java, y varias otras plataformas. Sin embargo, existen escenarios que son la base más simple que podemos pensar, enviar datos Json al IoT Hub utilizando HttpClient.

Así que antes de pasar a Java, he creado una Console app que envía datos a un Azure IoT Hub con el siguiente código fuente.

image

El ejemplo completo es una extensión de mis posts anteriores. Aunque en el camino he aprendido un par de lecciones que voy a compartir.

Para que la petición HttpRequest funcione hay que definir un modelo de autorización con una firma especial llamada SharedAccessSignature. Hay una explicación sobre el proceso de creación de esta firma (es solo un string), sin embargo Sandrino ha creado una herramienta que nos permite generar esta firma con solo un paso Event Hubs Signature Generator tool

image

De cara a validar la información que iba a enviar en modo plano, utilicé un parser Json online que me ayudo a tener el string correcto.

image

Finalmente, tenemos que conocer la url a la que enviaremos la información. Por lo general la url se construye con el siguiente formato

https://{Event hub compatible end point}/{EventHub compatible name}/publishers/{Device Id}/messages

Y dentro de nuestro Azure IoT Hub, podemos encontrar información del EventHub relacionado en la sección settings // messaging

Picture1

El último valor a completar es el DeviceId que fué una de las primeras acciones que hicimos en los posts, en este caso es “Device01”.

GitHub Code https://github.com/elbruno/Blog/tree/master/Azure

Saludos @ Toronto

-El Bruno

References

#AZURE – Post data into an #AzureIoTHub using plain text and HttpClient

Hi !

Azure IoT has a great SDK which includes tons of samples for C# apps, Java apps, and more. However there are some scenarios where you only need to send data from a device using a simple HttpClient, and plain JSON data.

So, for this scenario I created a simple Console app which send information to an Azure IoT Hub with the following source code.

image

The complete sample is based on my previous posts, but there are a couple of lessons learned to make this work

The authorization included in the header of the HttpRequest must have a special signature named SharedAccessSignature. The best way to deal with this is to use the Event Hubs Signature Generator tool from Sandrino. You type a couple of fields and this will generate the SharedAccessSignature

image

I’ve used a Json parser online tool to get the correct string to be sent to my IoT Hub.

image

Finally you need to know the url to post data. This information must use the following format

https://{Event hub compatible end point}/{EventHub compatible name}/publishers/{Device Id}/messages

We get the EventHub information from the settings // messaging section in Azure Portal

Picture1

Finally the DeviceId is the one we defined in our previous posts.

GitHub Code https://github.com/elbruno/Blog/tree/master/Azure

Greetings @ Toronto

-El Bruno

References

#Garmin – Mostrar gráficos e información de varios sensores al mismo tiempo

Hola !

El post de hoy es uno de los rápidos. Durante estos últimos días, mi principal objetivo era completar todo lo necesario para poder comenzar a vivir en Toronto, y aprovechando huecos de ocio, me puse a conocer el Garmin ConnectIQ SDK.

Como se puede ver en el siguiente video, hoy he llegado a un punto donde he creado una app

  • Que puede leer información de diferentes sensores: posición y ritmo cardíaco
  • En base a una muestra SDK la app puede dibujar un gráfico con los datos del sensor de latidos de corazón
  • La app crea un diseño de forma dinámica con colores diferentes (y bastante feos) para cada línea de texto, cuando el dispositivo está utilizando datos de sensores

2016 02 25 Garmin display multiple sensors

Sobre la app, un par de detalles a tener en cuenta

  • La app debe configurarse para utilizar sensores y obtener información, en las propiedades de aplicación

image

  • La clase App inicializará los eventos para la captura de datos de los sensores y el posicionamiento global. En cada evento de captura de datos, se invocará la clase View para mostrar estos datos
  • La clase de vista tiene algún código para dinámicamente trabajar en el diseño para crear textos y gráficos para la View

image

  • El gráfico utilizado para los datos de frecuencia cardíaca es un archivo de Graph.mc de los ejemplos del SDK

Y eso es todo! la aplicación es lo suficientemente inteligente y sencilla como para mostrar información en tiempo real de sensores y posiciones de una manera muy sencilla!

GitHub Source Code: https://github.com/elbruno/Blog/tree/master/Garmin

Saludos @ Toronto

-El Bruno

References

#Garmin – Display charts and several sensors information at once

Hi !

Today’s post is a quick one for Friday. My main goal in the past days was to complete all the necesarry stuff I’ll need to live in Toronto, and in the meantime I’ll continue to play around with the ConnectIQ Garmin SDK.

As you can see in the next video, I get to a point where

  • The app can read information from different sensors: position and heart rate
  • Based on a SDK sample the app can draw a chart for the HR data
  • The app creates a dinamyc layout with different (and ugly!) colors when the device is using sensors data or not

2016 02 25 Garmin display multiple sensors

So, the important stuff for this demo is

  • The app must be configured to use Sensors and Position information, in the app properties

image

  • The App class will initialize the sensors and positions. On each “get data” event, it will invoke the View class to display this data
  • The View class has some code to dinamically work in the layout to create texts and charts for the View

image

  • The chart used for the Heart Rate data is a Graph.mc file from the SDK samples

And that’s it ! the app is kind of smart enought to display real time information of positions and sensors in a very simple way!

GitHub Source Code: https://github.com/elbruno/Blog/tree/master/Garmin

Greetings @ Toronto

-El Bruno

References

#Garmin – Working with resources and cultures in a #ConnectIQ app

Hi !

When we create an app for a Garmin device, working with a resources is a #MustHave. We need to take take of simple stuff like change the culture of an app, In the following video, the main label of the app will change every time I change the culture of the smartwatch.

2016 02 24 Garmin Resource Languages

About Resources and Cultures

The ConnectIQ apps have a standard resource structure where we can define strings, store images and also define UI layouts or menus for our apps. We can find all of this elements in the main root folder of our project.

image

The root content folder for this is “resources”. For each different culture, we can add our owns folders and add only the different elements we need for each culture. In example, the main resource has this content in the “resources\strings\strings.xml” file

<strings>
<string id=”AppName”>App04</string>
<string id=”prompt”>Hello Martina</string>
<string id=”menu_label_1″>Item 1</string>
<string id=”menu_label_2″>Item 2</string>
</strings>

The same content for the Spanish culture will be located in “resources-spa\strings\strings.xml” and includes this content

<strings>
<string id=”AppName”>App04</string>
    <string id=”prompt”>Hola Martina</string>
    <string id=”menu_label_1″>Item 1</string>
<string id=”menu_label_2″>Item 2</string>
</strings>

There is also another important element in the app: the layouts (clearly explained in the programmers guide). I created a custom layout stored in a file named “resources\layouts\layoutcustom.xml”, which includes the following content

<layout id=”CustomLayout”>
<label x=”center” y=”5″ text=”@Strings.prompt” color=”Gfx.COLOR_WHITE” justification=”Gfx.TEXT_JUSTIFY_CENTER” />
<bitmap id=”id_martina” x=”center” y=”30″ filename=”../drawables/martina.png” />
</layout>

There are several elements which can be used in a layout file, like texts, images, shapes, etc. Again the programmers guide explains all the necessary information for this.

Resource Compiler

Finally we have the resource compiler. Every time we built our app, the resource compiler creates a set of classes which will allow us to work with this elements. If we have any issue or bad defined file, we’ll get some guidance in the Console log for Connect IQ.

image

Once we have a successful build in our app, we can access to this elements via code using the Rez module. This is an autogenerated module with a structure similar to this one

module Rez
{
    module Drawables
    {
        var bitmap_id = 123;
    }
    module Strings
    {
       var hello_id = 456;
    }
    module Fonts
    {
       var font_id = 789;
    }
}

In our sample, in order to access and use the Custom Layout, the way to do this is

image

In the same way we can access strings, fonts, bitmaps, etc.

In the next post more stuff and maybe some Azure connected sample.

GitHub Source Code: https://github.com/elbruno/Blog/tree/master/Garmin

Greetings @ Toronto

-El Bruno

References

#GARMIN – Read and display sensors data in a #ConnectIq app

Hi !

In today’s sample I’ll show how to create a WatchFace app which displays the current time and also the heart rate of the smart watch user. Most of the details will be added in the references section where you can find plenty of information on how the MonkeyC language works, or the different types of apps supported for Garmin watches.

The final output of the app in the simulator will be like this:

2016 02 22 Garmin HrData

So, once we created an app in Eclipse, next step is to configure some project properties. I selected the app type as “Watch App” so I can access to the sensors information. Other project types does not allow access to sensors information.

image

I also selected the target platform with my current smartwatch,m and finally I grant permissions to the app to access sensors information.

You can also update all this information in the [manifest.xml] file.

image

In the Developer Guide there is specific section for the build and package of applications where the manifest.xml file details are exposed. Once we have our app configured to access the sensors information, we can create some code to display this information.

In the following sample, there are some important topics

  • When the app is initialized, I allow the access to the Heart Rate sensor data
  • The the HR data is updated, there is a callback function to onSensor() method
  • In the onSensor() method I store the data in a local variable, display this information in the console log, and also I force an app User Interface layout update
  • In the Layout update method, I display the current time and also the current Heart rate sensor information

image

So, right now we have the basic code to create and app and display HR sensor data. If we run the app in the simulator, we’ll realize that the sensors data is NULL. We can emulate the data from the emulator with the options “Simulation // FIT Data // Simulate Data”

image

And now you can start to get some dummy HR data to your app.

From this post on, I’ll also start to also share the code in my GitHub repo: https://github.com/elbruno/Blog/tree/master/Garmin

Greetings @ Toronto

– El Bruno

References

#Garmin – #Eclipse and #ConnectIQ as a good starting point to create #SmartWatch apps

Hello!

After yesterday’s Hello world, today I’l write a post on a more friendly way to create Garmin apps. The Garmin Development team, has chosen MonkeyC as Development language and Eclipse as IDE for development, and the truth that fit the development environment is fairly simple.

Setup Development Environment

First we must download a version of Eclipse Luna. Choose the option for Java Developers, in the first step of the installer.

image

Once we have installed Eclipse, we must add the extension to work with Garmin Apps projects. So we access to the menu “Help / / Install new Software”

image

We must add the software from

http://developer.garmin.com/downloads/connect-iq/eclipse/:

Once added the URL we should add the tools of Connect IQ

image

We accept the EULA, restart Eclipse and now is time to configure the location of the Connect IQ SDK in Eclipse. In the “Windows / / Preferences” menu select the option Connect IQ and the same configure the location of the SDK,

image

Important: You must select the location Root of the SDK, not the directory BIN, for exampleC:\Garmin\connectiq-sdk-win-1.2.4”

My First App, Hello World !

Now we can now create our first project for a Garmin app. Let’s start with “File / / New Project” and then select “Connect IQ / / Connect IQ Project”

image

After you define a name for the App, comes to define the type of app. There are 4 options

  • Watch Faces – These replace the main watch face and are the home screen of the watch.
  • Data Fields – Data fields run within Garmin activities. They allow developers to compute values based off of the current activity, such as running, biking, etc.
  • Widgets – Widgets are full screen pages that can be embedded into the main page loop. They are loaded when brought on-screen and shut down when the user switches to the next widget. Widgets will timeout and automatically shutdown after a device specific period of inactivity.
  • Wearable Apps – Started from the action list, wearable apps can be used to implement use cases like third party activities, games, and other user-initiated actions. Apps push a page onto the UI and exit when the user backs out of the last page of the page stack. While running, the app has full control of the UI.

For this sample I will create a WatchFace app for my Garmin Forerunner 235

image

There is a couple more extra options to choose, like the WatchFace type and the supported languages. And now we have a minimmun set of code to be build and run Eclipse for Garmin Connect IQ App

image

In the meny “Run // Run Configurations” we add some options to build, and run the app in the emulator.

image

So, after we create this new build configuration we can run the app. In the next image, you can see the emulator running the app, displaying my name and also the time in a simple way (line 42)

image

So that’s it as starting sample. More in the next posts !!!

Greetings @ Toronto

-El Bruno

References

#Garmin – #ConnectIQ y #Eclipse, una forma facil de comenzar

Hola !

Después del hola mundo de ayer, hoy vamos a ver algo más amigable para crear apps. El equipo de Garmin, ha elegido Eclipse como IDE para el desarrollo, y la verdad que montar el entorno de desarrollo es bastante simple.

Setup Development Environment

En primer lugar debemos descargar úna versión de Eclipse Luna. Elegimos la opción para Java Developers, en el primer paso del instalador.

image

Una vez que tenemos instalado Eclipse, debemos agregar la extensión para poder trabajar con proyectos para Garmin Apps. Lanzamos el menu “ Help // Install new Software “

image

Debemos agregar el software desde

http://developer.garmin.com/downloads/connect-iq/eclipse/:

Una vez agregada la URL debemos agregar las tools de Connect IQ

image

Aceptamos el EULA, reiniciamos Eclipse y ahora es momento de configurar en Eclipse la ubicación del Connect IQ SDK. En el menu “Windows // Preferences” seleccionamos la opción Connect IQ y en la misma configuramos la ubicación del SDK,

image

Importante: Hay que seleccionar la ubicación Root del SDK, no el directorio BIN, por ejemplo “C:\Garmin\connectiq-sdk-win-1.2.4”

My First App, Hello World !

Ahora ya podemos crear nuestro primer proyecto. Para esto seleccionamos “File // New Project” Y luego seleccionamos “Connect IQ // Connect IQ Project”

image

Después de definir un nombre para la App, llega el momento de definir el tipo de app. Hay 4 opciones

  • Watch Faces – These replace the main watch face and are the home screen of the watch.
  • Data Fields – Data fields run within Garmin activities. They allow developers to compute values based off of the current activity, such as running, biking, etc.
  • Widgets – Widgets are full screen pages that can be embedded into the main page loop. They are loaded when brought on-screen and shut down when the user switches to the next widget. Widgets will timeout and automatically shutdown after a device specific period of inactivity.
  • Wearable Apps – Started from the action list, wearable apps can be used to implement use cases like third party activities, games, and other user-initiated actions. Apps push a page onto the UI and exit when the user backs out of the last page of the page stack. While running, the app has full control of the UI.

En este caso, crearé una WatchFace y para mi Garmin Forerunner 235

image

Seleccionamos otras opciones más, como el tipo de WatchFace y los idiomas soportados. Ahora ya tenemos nuestro proyecto / con el mínimo de código para ser ejecutado en Eclipse.

image

Desde el menú “Run // Run Configurations” debemos configurar las opciones para la compilación y despliegue en el simulador o en el reloj.

image

Creamos una nueva configuración y ya podemos ejecutar la app. En la siguiente imagen podemos ver como he agregado una nueva línea en la app para que muestre mi nombre antes de mostrar la hora.

image

Como ejemplo para el primer día, creo que me vale. Mañana más !!!

Saludos @ Toronto

-El Bruno

References

#VS2015 – Send tweets in an app #UWP #Windows10 using #TweetMoaSharp

Clipboard02

Hello!

Some time ago I wrote a post where I mentioned about a package to a Windows 10 Universal App to work with Twitter. In that post, I also mentioned that it was a shame that the excellent Daniel Crenna’s TweetSharp, does not support Windows Universal Apps.

Yesterday I was updating an app with some new features, and I find TweetMoaSharp. A fork of the latest version of TweetSharp and adds features to use these libraries in apps WinRT. It has been created by Troy Willmot (thanks!)

On this basis, the use is similar to TweetSharp and the truth is that after doing a few tests, it works very well in an app for Windows 10.

image

El paquete aparece si realizas una búsqueda por TweetSharp, a partir de allí es tan simple como agregarlo y comenzar a programar.

image

The package appears if you do a search for TweetSharp, from there it is as simple as adding it and begin to set.

image

The following code shows a simple example of a search criterion “elbruno”:

image

Greetings @ Madrid

-El Bruno

References