Google Maps API – How to make a custom marker

What’s up guys, Eze is here. Today I want to show you how easy is to create a custom marker using the Google Maps API. First let’s create a map reference using the Google Maps API. We will be using this object to place our marker.

// Create a map centered in NY
vm.map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40.7128 , lng: 74.0059},
zoom: 15
});

As you can see in our code above we only need to pass as a parameter the element reference, in my case it’s just a div element with id = ‘map’. The API will create the map view in this element. Then using the PlacesService we get the details of an specific place. I’m using this service because in my working example (you can check the code here) I have an input element where the user can select a place, this input is populated using the autocomplete service so basically I have the place_id parameter to provide but if you don’t want to use it in this way in the request object you can provide a reference property to search different places.

 

var request = {
placeId: place.placeId
};

var service = new google.maps.places.PlacesService(vm.map);
service.getDetails(request, callback);

function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: vm.map,
position: results.geometry.location,
title: results.formatted_address
});
var infowindow = new google.maps.InfoWindow();
vm.map.setCenter({lat: results.geometry.location.lat(), lng: results.geometry.location.lng()})
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('
<div><img src="'+ vm.place.photoUrl + '" style="width:128px;height:128px;"/></div>
');
infowindow.open(vm.map, this);
});
}

Once I get the details for a specific place I use the Marker object to create a new marker in the map. The object I’m using to create this instance contains the reference to my map, the geometry location object which I get from PlacesService and a title. And that’s it, this is all you need to create a new marker in a map using the Javascript library for Google Maps API.

places.PNG

For a complete reference of Google Maps API use this link

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Advertisements

Firebase – Advance querying join reference

What’s up guys, Eze is here. I already did couple of posts about Firebase and how to use the Real-Time database and the storage with AngularJs in case you missed it you can check here. Today I want to give you more details on how to do an advance query to join two references.

Let’s suppose we have the schema below and we want to retrieve the list of orders.

database_schema.png

To do that we just need to do as we did several times in our previous examples and attach to the child_added event as I did in the code below. As you can see we get the data under the path orders, but we still need to show the data under the path users which is linked to our orders.

query_first

In the code below we now changed the query in order to get as well the user data from the path users. It’s important to highlight that this time I’m using the method once which will retrieve the data once and this data it’s not going to be live data, we are not going to receive notification if this data changes. There is another way to get the data in real time but we need to keep the reference to dispose the connection we no longer need it. But again if you don’t really need the related data in real time you can use this easy way to join two references.

query_second.PNG

For a complete reference of Firebase use this link

For a complete list of querying functions you ca use this link.

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Microsoft Bot Framework – Forms Dialog and how to add dynamic options.

What’s up guys, Eze is here. As you know I’ve already written a post about Microsoft Bot Framework, in case you missed it you can check it here. Today I want to go deeper and explain a really good feature: Form Dialog. This feature is used to create a form and allow our Bot to ask field by field until completes the form and in particular I want to explain how to add dynamic options to our font so let dive into the description right away.

Creating the form

Let’s suppose we have a form and we want our bot to ask for each property in our form to the user in order to complete it so first we need to define our form. In my case I’m using the same I have in my working example. As always the working example is available here.

[Serializable]
 [Template(TemplateUsage.NotUnderstood, "I do not understand \"{0}\".", "Try again, I don't get \"{0}\".")]
 public class PlaceTemplate
 {
    [Prompt("Name a place to know the current date-time {||}")]
    [Describe("Name of the place")]
    public string PlaceName { get; set; }
    [Prompt("Select a place {||}")]
    [Describe("Place to find the current date time")]
    public string SelectedPlace { get; set; }

As you can see in the code above we just define a new class and the properties of this class are going to be used by our bot to complete the form. Then we need to define a static method to return a IForm<object>. As you can see below this method create an instance of the class FormBuilder and then just return the method Build(). In this FormBuilder it’s going to define which field we want to ask to the user, to do that we are going to use the method Field(). And then using the OnCompletion() method we will define the behavior for our bot after populate all the requested fields. As you can see this is a good way to guide our user through a form.

 
 public static IForm<PlaceTemplate> BuildPlaceForm()
{
var logic = new LocationBL();
OnCompletionAsyncDelegate<PlaceTemplate> process = async (context, state) =>
{
var businesLogic = new LocationBL();
var response = businesLogic.GetCityInfoFromPlaceId(state.SelectedPlace);
var reply = string.Empty;
if (!string.IsNullOrEmpty(response.cityName) && !string.IsNullOrEmpty(response.convertedLocalTime))
{
reply = $"Current date time at {response.cityName} is {response.convertedLocalTime}";
}
else
{
reply = $"Sorry we could not find any location called {state.PlaceName}";
}
await context.PostAsync(reply);
};
var builder = new FormBuilder<PlaceTemplate>()
.Message("Welcome to the City Timer bot!")
.Field(nameof(PlaceName))
.Field(new FieldReflector<PlaceTemplate>(nameof(SelectedPlace))
.SetType(null)
.SetActive((state) =>
{
return string.IsNullOrEmpty(state.SelectedPlace);
})
.SetPrompt(new PromptAttribute("Please select one of the following options: {||}")
{
ChoiceStyle = ChoiceStyleOptions.Buttons

})
.SetDefine((state, field) =>
{
var result = logic.GetPlaces(state.PlaceName);
foreach (var item in result)
{
field
.AddDescription(item.Item1, item.Item2)
.AddTerms(item.Item1, item.Item2);
}

return Task.FromResult(true);
}))
.OnCompletion(process);
return builder.Build();
}

Adding dynamic options to a field.

I saw a lot of examples where the use can chose one of many options but those options are always defined using an Enum. In my case I want to define the options dynamically so to do that our field needs to be an instance of FieldReflector. This new object has a method SetDefine as you can see in the code above which is used in my example to get the list of places and return a list to the user to select one option.

As you can see creating a form using the Microsoft Bot Framework it’s really easy and adding dynamic options to a field is even easier.

bot_fields.PNG

For mode details of Microsoft Bot Framework you can use this link.

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Firebase Storage is officially in AngularFire 2.3.0 – The easiest way to upload binary content

What’s up guys, Eze is here and today I want to talk you about some great news. The AngularFire team have released a new version which is 2.3.0 and you can check it here.  This new version officially supports Firebase Storage and believe me this feature it’s amazing. I already have a post explaining how to upload images using Firebase Storage from AngularJs in case you missed it  here you go the link. So the idea for today’s post is to refactor the actual working example I have (here is the link to the code) and make it work using Angular Fire Storage, let’s see how it works.

Creating your data layer

I’m going to keep the same data layer because the concept it’s the same but this time I’ll add as a reference $firebaseStorage as you can see in the code below. The other change we need to do it’s return an instance of this object in our service because we are going to use this object to communicate with Firebase directly.

 function storageService($http, $firebaseStorage, $q) {
    var storageRef = firebase.storage().ref();
    var storage = null;

    var service = {
       getStorage: getStorage
    };

    return service;

    function getStorage(uid, fileName) {
       if(!storage){
          storage = $firebaseStorage(storageRef.child(uid).child(fileName));
       } 
       return storage; 
    }
 }

So basically we are using the service to create our Firebase Storage object. This new object is going to handle all the communication with Firebase in order to upload our files.

New unterface to interact with

Previously I’ve used the put method to upload our file. This method receives three functions as parameters to handle progress, error and the completion or our upload. Well all this is part of the past. With this brand new version we are going to use  use the method $put to upload our file and this method is going to return us an Upload Task object. We need to provide a callback function to the method $progress, $error and $complete in order to handle the events as we did before.

 
	vm.uploadTask = vm.storageRef.$put(vm.file);

	vm.uploadTask.$progress(function(snapshot) {
			var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
			vm.progress = 'Upload is ' + progress + '% done';
			switch (snapshot.state) {
				case firebase.storage.TaskState.PAUSED:
					console.log('Upload is paused');
					break;
				case firebase.storage.TaskState.RUNNING:
					console.log('Upload is running');
					break;
			}
	}); 
	vm.uploadTask.$complete(function(snapshot) {
		vm.newPlace.photoUrl = snapshot.downloadURL;
		vm.places.$add(vm.newPlace);
		$rootScope.$broadcast('successAlert', { header: 'Well done.', msg: 'Your request has been process successfully.' });
	});
	vm.uploadTask.$error(function(error) {
		var msg = '';
		switch (error.code) {
			case 'storage/unauthorized':
			msg = 'User does not have permission to access the object.';
			break;
			case 'storage/canceled':
			msg = 'User canceled the upload.';
			break;
			case 'storage/unknown':
			msg = ' Unknown error occurred, Please try later.';
			break;
		}
		$rootScope.$broadcast('dangerAlert', { header: 'Oh snap!', msg: msg });
	});

As you can see now it’s much easier upload files and handle event with this new Firebase Storage Service. I have a working example in this link if you want to see the complete implementation. In this example I created an app that allows you to select different places around the world and upload an image that appears in a google maps.

firebase_storage

For a complete reference of Firebase storage use this link.

For a complete reference of Angular Fire use this link.

For a complete reference of Firebase use this link

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Firebase + Azure Functions + Azure Service Bus + Microsoft Bot Framework – Connecting the dots. Part II

What’s up guys, Eze is here. In my last post I’ve described a system which has several parts such as Firebase, AngularJs and Azure Functions interconnected. I also added new tools like Microsof Bot Framework and Azure Service Bus to enhance our app in a decouple way. As always the working example is available here.  Yesterday I put my focus on the NodeJs Azure Funtion, but today I’ll describe the Microsoft Bot Framework. As I said in my last post (in case you missed it you can check it here), the idea is to create a bot that receives a place name and response with the current date time at that location. After the bot parse the input and generate the proper response puts into the Azure Service Bus a message that will trigger our NodeJs Azure Funtion to store the data in Firebase, pretty cool, isn’t it? You can check the working version here.

Microsoft Bot Framework

Microsoft has created an awesome framework that allows us to create a bot, yes a conversational tool able to interact with our customers. The Bot itself is a web api application that can run in any web server. Then we just register our bot in the Microsoft Bot framework website and under the configuration page we define different channels where our bot is going to run. And that’s it, as simple as that our bot will be able to interact with customer from Skype, Facebook chat or Tulio.

bot

 

Creating the Bot

I already told you the bot is just a web api that can run in any server and the reason I said that is because Microsoft Bot Framework has two different versions, of course a Bot Builder for .Net and a Bot Builder for NodeJs.

 [ResponseType(typeof(void))]
public virtual async Task<HttpResponseMessage> Post([FromBody] Activity activity)
{
if (activity != null)
{
// one of these will have an interface and process it
switch (activity.GetActivityType())
{
case ActivityTypes.Message:
await Conversation.SendAsync(activity, () => EchoChainDialog.dialog);
break;

case ActivityTypes.ConversationUpdate:
case ActivityTypes.ContactRelationUpdate:
case ActivityTypes.Typing:
case ActivityTypes.DeleteUserData:
case ActivityTypes.Ping:
default:
Trace.TraceError($"Unknown activity type ignored: {activity.GetActivityType()}");
break;
}
}
return new HttpResponseMessage(System.Net.HttpStatusCode.Accepted);
}

As you can see in the code above we only need to define a post action in our webapi controller which will be the SPOC of our bot. Every message is going to be route to this action. In my case based on the activity type I let my bot response. In this example we are creating a new instance of the class  EchoChainDialog. This dialog entity is going to handle the conversation base on what we define. In my case I just use a switch method from the IDialog object to parse the text and response to our customer.

Azure Service Bus

I’ve created as well an Azure Service Bus to use as a trigger for my NodeJs Azure Function. What that means? Ok the idea is like this after the Bot process the request and generates a response it puts a message into the Azure Service Bus. As you can see below the code to do that it’s really simple. We just need the Service Bus connection string and the queue name. When a new message arrives to this particular queue in the Azure Service Bus that will trigger our NodeJs Azure Function we created yesterday. This mechanism is created and configure in Azure.

 try
{
var client = QueueClient.CreateFromConnectionString("connectionString", "queueName");
var message = new BrokeredMessage(JsonConvert.SerializeObject(responseData));
client.Send(message);
}
catch
{
}

 

For more details of Azure Service Bus you can use this link.

For mode details of Microsoft Bot Framework you can use this link.

For more details of Azure Functions you can use this link.

 

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Firebase + Azure Functions + Azure Service Bus + Microsoft Bot Framework – Connecting the dots.

What’s up guys, Eze is here. I’ve been working in an example that you can check it here, this example uses Firebase, AngularJs and Azure Functions. I used a bunch of cool tools to create rapidly powerful front-end app, in case you missed it you can check here. Today I’ll add couple of new tools like Microsof Bot Framework and Azure Service Bus to enhance our app in a decouple way. The idea is to create a bot that receives a place name and response with the current date time at that location. After the bot parse the input and generate the proper response puts into the Azure Service Bus a message that will trigger our NodeJs Azure Funtion to store the data in Firebase, pretty cool, isn’t it? You can check the working version here.

NodeJs Azure Function

Today we are going to put the focus only in our Azure Function so I’ll talk about how to create a NodeJs Azure function and how to configure it in order to be able to use Firebase from a NodeJs Azure function.

As we did last time, in case you missed it you can check here our Azure function is composed for two files the function.json (function metadata) and because this one is a NodeJs function we need to have an index.js file to place our code to execute. All JavaScript functions must export a single function via module.exports for the runtime to find the function and run it. This function must always include a context object. In the example below you can see how I configure my function.

module.exports = function(context, mySbMsg) {
   if(!app) {
      context.log('Initializing Firebase App');
      app = firebase.initializeApp(config);
   }
   var defaultAuth = app.auth();
   if(!_user){
      defaultAuth.signInAnonymously()
                 .catch(function(error) {
                    context.log('Anonymous login failed: ' + error.message);
                    context.done();
                 });
   }

   defaultAuth.onAuthStateChanged(function(user) {
   if (user) {
      _user = user;
      context.log('User is signed in. user uid: ' + _user.uid);
      var defaultDatabase = app.database().ref().child('requests').child(_user.uid).child('userRequests');
      mySbMsg['userName'] = 'Anonymous';
      defaultDatabase.push(mySbMsg)
                     .then(function() {
                          context.log('JavaScript ServiceBus queue trigger function processed message', mySbMsg);
                          context.done();
                     })
                     .catch(function(error) {
                          context.log('Synchronization failed');
                          context.done();
                      });
    } else {
       context.log('User is signed out.');
       context.done();
    }});
};

Configuring the environment

Before going further with the explanation of the function I want to explain first how to configure the Azure function to use Firebase node package. Let’s remember that this function is going to run in Azure serverless. That only means that we don’t have full control over our server but we still can run npm install  in the function app’s SCM (Kudu) command line interface in order to add packages to our app:

  1. Navigate to: https://<function_app_name&gt;.scm.azurewebsites.net.
  2. Click Debug Console > CMD.
  3. Navigate to D:\home\site\wwwroot\<function_name>.
  4. Run npm install firebase --save.

kudu

After doing this we will be able to import our Firebase library like this:

var firebase = require('firebase');

After that we can use our firebase object as we did before so let’s dive directly into our function so I can explain you what’s going on. First I use the method signInAnonymously under the object auth and this is because I need a logged in user to write in my database, don’t worry we didn’t talk about it yet but believe me I’m going to explain you more about database rules and authentication with Firebase.

Then I use the object that I receive as parameter from my Azure Service Bus and directly store it in our database. During this week I’ll be posting about the other parts of this system so you can know more about Microsoft Bot Framework and Azure Service Bus

For more details of Azure Functions you can use this link.

For more details of NodeJs Azure Functions you can use this link.

For mode details of Firebase npm package us this link.

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.

Azure Functions -Process events with a serverless code architecture

What’s up guys, Eze is here. During the past post we were talking about Firebase, AngularJs and a bunch of cool tools to create rapidly powerful front-end apps, in case you missed it you can check here. Today I want to bring you a server side code that runs in a serverless architecture, yes we are going to talk about Azure Functions.

About Azure Functions

This is a cool feature that Azure team has created for us. The idea is to mix events + code to execute in a serverless environment which basically means you don’t need to take care about where your code is going to run, about which configuration has this server, how much memory is using or which OS version has. You just need to define the code to execute and which event is going to trigger our function. As they say.

An event-based serverless compute experience to accelerate your development. It can scale based on demand and you pay only for the resources you consume.

Common scenarios for Azure Functions

Trigger by time: Azure functions uses CRON job syntax to expecify an event based on a timer. So lets say that we want our code to run every 10 minutes.

Azure service event: We can setup our function to execute every time something happen in an Azure service. For example when a new file is uploaded in a blob storage.

Serverless web application architectures*: This one in particular is the one I’ve used for our example. In this case a front-end app calls a function to execute a procedure in a server side.

Function components

As you can see in the image below the Azure function is made by two files the first one is a function.json that represents the structure of our function, basically the metadata of our function. The second one is a run.csx file (because I’m using C#) which is directly the method we want our function to execute. Microsoft offers us a web editor to edit directly in the browser our functions but if we want we can configure a github project and setup an automatic deploy when we push our repository.

function.png

I have a working example in this link if you want to see the complete implementation. In this example every time a user makes a request in our front-end app we call this Azure Function to store the request in an Azure storage table as you ca see below

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ICollector<Request> outTable, TraceWriter log)
{
dynamic data = await req.Content.ReadAsAsync<object>();
string name = data?.userName;

if (name == null)
{
return req.CreateResponse(HttpStatusCode.BadRequest, "Please provide an user name in the request body");
}

outTable.Add(new Request()
{
PartitionKey = "Functions",
RowKey = Guid.NewGuid().ToString(),
cityName = data.cityName,
convertedLocalTime = data.convertedLocalTime,
convertedRequestedTime = data.convertedRequestedTime,
dstOffset = data.dstOffset,
rawOffset = data.rawOffset,
timeAtLocation = data.timeAtLocation,
timeZoneId = data.timeZoneId,
timeZoneName = data.timeZoneName,
userName = data.userName
});
return req.CreateResponse(HttpStatusCode.Created);
}

For more details of Azure Functions you can use this link.

If you found this post useful please don’t forget to press the like button and share it. If you are in doubt don’t hesitate to ask a question and as always thank you for reading.