Cloud Functions for Firebase

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 the server side code that runs in a serverless architecture,  and no, I’m not talking about Azure Functions, today we are going to talk about Cloud Functions for Firebase the new tool from the Google Cloud team.

About Cloud Functions for Firebase

Cloud Functions is a hosted, private, and scalable Node.js environment where you can run JavaScript code. What that it means? well 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.

Cloud Functions for Firebase provides a way to extend the behavior of Firebase and integrate Firebase features through the addition of server-side code.

Common scenarios for Cloud Functions for Firebase

  • Real-time Database Triggers: Handle events in the Firebase Real-time Database. It’s important to highlight that each change in the database is processed individually, the function runs with Admin privileges and you can change the behavior anytime.
  • Firebase Authentication Triggers: The function can be triggered in response to the creation and deletion of user accounts via Firebase Authentication.
  • Cloud Storage Triggers: The function can be triggered in response to an upload or delete of a file in the cloud storage.

  • HTTP Triggers: Of course the function support HTTP triggers which means that you can manually trigger the function on demand.

notify

Create and deploy your first Function

We are going to use the Firebase CLI tool to create the project for our function. If you haven’t done yet you can install the tool by using this command: npm install -g firebase-tools. Once we have the Firebase CLI tools then we need follow this steps:

  • Run firebase login
  • Navigate to our project folder and run firebase init functions

This will create the following structure:

myproject
 +- .firebaserc    # Hidden file that helps you quickly switch between
 |                 # projects with `firebase use`
 |
 +- firebase.json  # Describes properties for your project
 |
 +- functions/     # Directory containing all your functions code
      |
      +- package.json  # npm package file describing your Cloud Functions code
      |
      +- index.js      # main source file for your Cloud Functions code
      |
      +- node_modules/ # directory where your dependencies (declared in
                       # package.json) are installed

Import the required modules and initialize

At this point our Cloud Function is almost ready to go. First we need import the providers modules. In order to do that we need to edit the index.js file which contains the function code.

const functions = require('firebase-functions');

const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

And now as in every nodeJs application we need export the function we want run. As you can see in the code below we create a HTTP function that takes the parameter from the query string and add it to the database.

exports.addText = functions.https.onRequest((req, res) => {
const original = req.query.text;
admin.database().ref('/messages').push({original: original}).then(snapshot => {
res.redirect(303, snapshot.ref);
});
});

Now we need deploy our function to Firebase. In order to do that we just need execute the following command: firebase deploy –only functions. After do that our function will be available to use via HTTP request.

https://us-central1-MY_PROJECT.cloudfunctions.net/addText?text=AddThisMessage

This is just a small taste of what you can do with this new functionality from the Google Cloud team.  We can use this new tool to maintenance task or just to add more functionality to our current apps. The idea to have a backend for our firebase applications is something really exciting and allow us to have more powerful apps.

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

For more details of Cloud Functions for Firebase 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.

Deploying an Angular 2, .Net Core 1.1 Web API and MongoDB using Docker Containers

What’s up guys, Eze is here. Again to those who follow me on Twitter (if you are not a follower you better do it now @skielo) already knows I’ve been working on an app to show you how to create an Angular 2 app using a ASPNET Core 1.1 Web API with a MongoDB database and using all those components in different Docker containers. Today I want to show you how easy is to get up and running an Angular 2 app and connect it to ASPNET Core 1.1 Web API to retrieve data from a MongoDB database, sounds amazing right? well this will be the first out of a series of post  where we are going to find out more about those tools

The frontend skeleton

First we need build the frontend and the back-end for our app. As I already told you the front-end will be an Angular 2 app. To create it we are going to use the Angular cli tool. There is nothing new here, and you can follow the steps I already wrote here. The only difference is this time we are creating a server.js file which will be our entry point in the Docker container.

The back-end skeleton

Well the back-end will be an ASPNet Core 1.1 Web API. This API will receive request from the frontend, get/put data to the database and provide a response. to create this application we will use the Yeoman generator. So let’s first install all the required dependencies by running the following command npm install -g yo generator-aspnet@0.2.6 generator-docker. This will install the latest version of the Yeoman tool + the latest generator for aspnet projects and a docker generator. The last one is not completely necessary but it good to have it.

Creating the code

Once we have all the required tools by executing this command yo aspnet Yeoman will create an small web api project. In order to test if our project has been created correctly we need navigate into the project folder and execute this commands: dotnet restore and then dotnet run, when the server has started we can browse this url http://localhost:5000/api/values to test our webapi.

yo_webapi

In order to create a data layer to access our MongoDB from our Web API project I’m using MongoDB Driver for C#. Basically I’m using the repository pattern, if you want to know more about that please follow this link. Something which is important to highlight is that within the connection string I’m using as a server name / ip address the name mongodb after the docker image. I will go into more details lately.

Then  I’ve created a new web api controller to handle the request from our Angular 2 app.

Installing Docker

Well we are almost ready to go. In order to complete our system we need to get the right version of Docker according with our operating system. Please follow this link to get it. Also it’s important to know that we will required the docker-toolbox, you can find it here. This toolbox will create the docker machine in our computer and using this console we will interact with our docker application.

By running this command yo docker and selecting .Net Core as a project we need to follow some bootstrapping scripts to create the docker files in our project. Regardless of the structure used by this tool in my project I’ve created a folder called .docker where I place the created dockerfile. This is a recommendation by @DanWahlin.

Exploring the dockerfile

In the dockerfile we will find the instruction for docker to build and run our images. In the example below we instruct docker to base our image in one from the docker hub: microsoft/dotnet:latest but, what that means? Well that means that we are going to use the official docker image created by microsoft to run a dotnet app. Then we select which port will be available within our container and which is the entry point for this image.

FROM microsoft/dotnet:latest
WORKDIR /app
COPY bin/Debug/netcoreapp1.1/publish /app
ENV ASPNETCORE_URLS http://*:80
EXPOSE 80
ENTRYPOINT ["dotnet", "WebAPIApplication.dll"]

Exploring the docker-compose file

This is the file we are going to use to build our images. In this file we specify all the characteristics of our images.  We also define the container_name (otherwise docker will pick a funky name on runtime for us), the image we want to use, the internal al external port for the container and something which is really cool, the network. This network specification will allow us to talk from one container to another. As you can see in the code below I’m using as a container_name for the database mongodb, the same I used in the connection string of our web api.

version: ‘2’

services:
webapiapplication:
container_name: webapiapplication
image: webapiapplication
build:
context: .
dockerfile: .docker/Dockerfile
ports:
– "80:80"
networks:
– webapi-network

node:
container_name: nodeapp
image: nodeapp
build:
context: .
dockerfile: .docker/Dockerfile
environment:
– NODE_ENV=development
ports:
– "3000:3000"
networks:
– webapi-network

mongodb:
container_name: mongodb
image: mongo
networks:
– webapi-network

networks:
webapi-network:
driver: bridge

Start the engine

Now we have our applications ready, we already configured the containers so it’s time to start our system. The first step is build and publish our .Net Core app. By running this commands dotnet build and dotnet publish we will do that. Then we need open the Docker Toolbox terminal. This will initialize our docker machine.

If you are running docker in Windows you probably are using hyper-v, if this is your case you might have to edit the start.sh file for your docker-toolbox in order to use hyperv as a driver and a virtual switch.

docker-machine create –driver hyperv –hyperv-virtualswitch “My Internal Switch”

Once the toolbox terminal is done we need to navigate to our project folder and run the command docker-compose build. This will build our images and after that by running docker-compose up -d, Docker is going to start up all our images and keep it running in daemon mode. And that’s it, our application will work all together. Because the images are running in daemon mode we can check the logs by executing docker-compose logs, there is another useful command which is docker ps -a which will show us all the instance for our images.

If you want to see the full code working together I have a working example here. Be aware that this is only an example, is not meant to be use in a production environment because as you can see the database doesn’t have any security at all. If you want more details please follow the official documentation.

For a complete reference of Angular 2 use this link.

For a complete reference of .Net Core use this link

For more references about Mongo images 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 – Real-Time Database using Angular 2

What’s up guys, Eze is here. Those who follow me on Twitter (if you are not a follower you better do it now @skielo) already know I’ve been working on an app to show you how to use Firebase from an Angular 2 app. I have several post talking about Firebase and how to use almost all its functionalities from an AngularJS app, in case you missed it you can check it here. Today I want to show you how easy is to get up and running an Angular 2 app and connect it to Firebase. This will be the first out of a series of post  where we are going to find out more about those tools.

The skeleton of our app

I want to show you first how to create a new Angular 2 app from the scratch. To do that we will need to install in our machines the angular cli tool. The installation of this tool it’s really simple we just need run the following command npm install -g @angular/cli. Please be sure you have a node version higher than 4 because it’s a requirement for this tool to run.

This tool will provide us lots of functionalities that we are going to use during the development of our app but first we need to create the scaffolding of our app, by executing the following command ng new app_name the Angular cli will create a new Angular 2 app. We can see our app running by executing ng serve command.

ng_create.PNG

Adding Angular Fire 2 and Firebase to our project

We already have the basics of our project it’s time to add the reference to Angular Fire 2 and Firebase and we will do it by running the following command inside our project folder  npm install angularfire2 firebase –save. This command is going to install all the necessary files in our project. So now it’s time to dive into our app.module.ts in order to configure our Firebase project. First we need import AngularFireModule and then export the configuration we get from Firebase.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AngularFireModule } from 'angularfire2';

import { AppComponent } from './app.component';

export const firebaseConfig = {
apiKey: '',
authDomain: '',
databaseURL: '',
storageBucket: '',
messagingSenderId: ''
};

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
AngularFireModule.initializeApp(firebaseConfig)
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

Creating a Database layer

Now we have configured Firebase to our project so it’s time to create our database layer in order to have access to our database. Again we are going to use Angular cli by typing ng generate service databaseservice. This time the command is going to generate a new service but you need to take care of something else which is the warning we got from the tool: “WARNING Service is generated but not provided, it must be provided to be used”. In order to provide this new service we need to include it in the AppComponent as I did below.

import { Component } from '@angular/core';
import { DatabaseService } from './core/database.service';

@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'app.component.html',
providers: [DatabaseService]
})
export class AppComponent {

}

As you can see in the code above we use a great feature of Type Script that allows us to define a property in the constructor which means that Angular will automatically inject the right object for us.

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { AngularFire, FirebaseObjectObservable, AngularFireAuth } from 'angularfire2';

@Injectable()
export class DatabaseService {

constructor(private _af: AngularFire) {
}

createBattle(obj: Battle){
return this._af.database.list('/battles').push(obj);
}

And that’s it, after doing that we are ready to go. This AngularFire object will give us access to all Firebase functionality. In this example I’m using the database object in particular the list method. As you can see we need pass the path reference to this method and the return will be an FirebaseListObservable object that will let us work with our database.

If you want to see the full code working together I have a working example here. This example is an small version of the game battleship.

For a complete reference of Angular Fire 2 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.

Microsoft Bot Framework – Forms dialog from JSON Schema.

What’s up guys, Eze is here. I’ve already written few posts about Microsoft Bot Framework, in case you missed it you can check it here. Today we are going deeper and review another really good feature of the Form Dialog, the possibility to create a form using a JObject. As we did before the Form Dialog is going to create a form and allow our Bot to ask field by field until completes the form but instead of using a static c# class to define our form we are going to provide a JSON Schema.

In order to utilize this feature you need to ensure that you add the NuGet project Microsoft.Bot.Builder.FormFlow.Json to your project. This defines the new namespace Microsoft.Bot.Builder.FormFlow.Json that contains the code to allows using JSON Schema for FormFlow.

Creating the JSON Schema

Now we need to define our form, this time we are going to create a json file to do it.  In the References property we are going to define all the dependencies for our form. In the same way under the Imports property we define all the namespaces to include. And another important property for our form is the OnCompletion property, here we are going to put a C# script to execute after our bot complete to fulfill the form. And then we have the properties field where we are going to place the fields we want our bot ask to the customer.

{
 "References": [ "CityTimerBot.dll" ],
 "Imports": [ "CityTimerBot.Models" ],
 "type": "object",
 "required": [
   "SelectedPlace"
 ],
 "Templates": {
 "NotUnderstood": {
 "Patterns": [ "I do not understand \"{0}\".", "Try again, I don't get \"{0}\"." ]
 }
 },
 "properties": {
 "PlaceName": {
 "Prompt": { "Patterns": [ "Name a place to know the current date-time {||}" ] },
 "Before": [ { "Message": [ "Welcome to the City Timer bot!" ] } ],
 "Describe": "Name of the place",
 "type": [
 "string",
 "null"
 ]
 },
 "SelectedPlace": {
 "Prompt": { "Patterns": [ "Select a place {||}" ] },
 "Before": [ { "Message": [ "Welcome to the City Timer bot!" ] } ],
 "Describe": "Place to find the current date time",
 "type": [
 "string",
 "null"
 ]
 }
 },
 "OnCompletion": "var businesLogic = new CityTimerBot.Models.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);"
}

Once we have defined the schema file we need create a method to return an object which implements the IForm interface as we did las time. As you can see in the code below we need use the FormBuilderJson object and we just pass the schema in the constructor.

 public static IForm<JObject>; BuildJsonForm()
 {
    using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("CityTimerBot.LocationTemplate.json"))
    {
       var schema = JObject.Parse(new StreamReader(stream).ReadToEnd());
       return new FormBuilderJson(schema)
         .AddRemainingFields()
         .Build();
    }
 }

As you can see this feature gives us the flexibility to define custom forms and the availability to change it dynamically.  Thinking out loud I can imagine an use case where we want to provide to our customers a way to model their forms so we can define the form as a JSON Schema and provide them an admin screen to change it.

bot_fields

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.

An AngularJs directive to support Google Places Autocomplete API

What’s up guys, Eze is here. Today I want to talk you about a directive I’ve been working on which is a wrapper for Google Places Autocomplete using the Google Places API. As always you can find the code here. This directive is an improvement for a discontinued project.

bower.PNG

Using the directive

This directive it’s really easy to use. First we need to get the code and you can do it via bower using the following command bower install ng-autocomplete-places –save.  Once we reference the file in our html we are almost ready to go. As you can see in the code below we only need add the directive to the input control we want to convert into an autocomplete text-box  and then define the object in our AngularJs controller.

<input type="text" ng-places-autocomplete ng-model="vm.autocomplete" class="form-control" options="vm.options" details="vm.details" initial-address="vm.initialAddress"/>
 vm.result = '';
 vm.autocomplete = {};
 vm.options = {};
 vm.initialAddress = null;

autocomplete.gif

After we select one of the options of the autocomplete, the directive setup into the ng-model property the formatted address from Google Places API, this is what we show into the text-box element. Into the details object we will have available the complete object returned the API. In this object we have really useful information related the place like the geometry information (latitude and longitude), photos, descriptions, rates etc.

autocomplete_returns.PNG

Improvements to the original project

I’ve added to this project the possibility to use a reverse geocoding. If you already have the place_id property or if you have the latitude and longitud of the place you can provide it to the directive in order to initialize the component. Also I merged almost all the pending pull request in the original project.

For a complete documentation of the directive please use this link.

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.

Firebase – Authentication using AngularJs

What’s up guys, Eze is here. In the past weeks I wrote several post about Firebase Real-Time Database, Firebase Storage and the new version of AngularFire 2.3.0 which includes Firebase Storage as well. In my first post I told you that Firebase provides us a wide range of tools and I mentioned Authentication but I didn’t have the opportunity to talk about it yet. Last week @lmoroney have written a bunch of posts regarding this topic, that inspired me to start this serie of posts to give you my point of view of this powerful tool.

Adding Firebase to your web app

We only need to reference AngularJs, Firebase and AngularFire libraries in your  project.

<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>

<!-- Firebase -->
<script src="https://www.gstatic.com/firebasejs/3.6.4/firebase.js"></script>

<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/2.2.0/angularfire.min.js"></script>

Then we need to add Firebase configuration in our index.html. To do that we need to go into the Firebase console and get the initialization code.

Creating your data layer

Now I will create an AngularJs service to use as data layer. This service will be responsible to create our links to the Firebase Authentication. Here we are going to use this time another object from the firebase library $firebaseAuth.

 function authService($firebaseAuth, firebaseDataService, cityTimerService) {
    var firebaseAuthObject = $firebaseAuth();

    var service = {
       firebaseAuthObject: firebaseAuthObject,
       register: register,
       login: login,
       logout: logout,
       isLoggedIn: isLoggedIn,
       sendWelcomeEmail: sendWelcomeEmail
    };

    return service;

    ////////////

    function register(user) {
       return firebaseAuthObject.$createUserWithEmailAndPassword(user.email, user.password);
    }

    function login(user) {
       return firebaseAuthObject.$signInWithEmailAndPassword(user.email, user.password);
    }

    function logout() {
       cityTimerService.reset();
       firebaseAuthObject.$signOut();
    }

    function isLoggedIn() {
       return firebaseAuthObject.$getAuth();
    }

    function sendWelcomeEmail(emailAddress) {
       firebaseDataService.emails.push({
           emailAddress: emailAddress
       });
    }
}

Enable the Authentication methods

Before going further there is something we need to do in our Firebase console in order to enable the sign-in methods as I did in the image below. In my case I enabled two methods Email/Password and Anonymous but as you can see we can also select Google, Facebook, Twitter or GitHub.

authentication.PNG

Understanding the $firebaseAuth object

This object provides us a really good interface to work with the authentication in Firebase. Today I’ll explain you four methods:

  • $createUserWithEmailAndPassword: This method receives two parameters email and password and returns a promise containing a firebase.User.
  • $signInWithEmailAndPassword: This method receives again two parameters email and password and returns a promise containing a firebase.User object. It throws an error in case the email and password don’t match.
  • $getAuth: This method returns a promise containing a firebase.User.
  • $signOut: This method is going to sign out the current logged in user and returns a string containing the email of the user in case of success.

As you can see handle the authentication using Firebase Authentication it’s really simple. In this post I just covered the basic to get up and running the authentication in our app. In the following post I’ll be covering more complex scenarios.

For a complete reference of the Authentication API 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.

Power BI and how to integrate with Azure Tables Storage

What’s up guys, Eze is here. If you remember for this post I created an Azure Function that stores data from our Web application into a Azure Table Storage. Today I want to bring you a really powerful tool: Power BI, a data visualization tool that allows you to bring your data to life.

About Power BI

This is a great tool by Microsoft that allows us to create custom visualization of our data from different data sources, today we are going to put the focus on Azure integration and how to bring to life our data stored in an Azure Table Storage. You can think Power BI as tool to create awesome dashboards. In they words:

Power BI is a cloud-based business analytics service that gives you a single view of your most critical business data. Monitor the health of your business using a live dashboard, create rich interactive reports with Power BI Desktop and access your data on the go with native Power BI Mobile apps. It’s easy, fast, and free.

Connecting to the data source

The first step it’s to download the Power BI desktop application for free in their website. I wont give the details you guys already know how to do it. Once we have the tool we need to configure our Azure Table Storage to pull data so first we connect using our Storage Account Name and Storage Account Key to connect our data source.

power_bi_select

Then we select our Azure Table Store to pull data from. In my case I’ll use the same I used when I create the Azure Function.

power_bi_select_table.PNG

We are almost there. We already have selected our Azure Table Storage, selected our table to pull data so now we need to define our visualization. In my table I have stored the city name on each request so by selecting this column as I did in the image below Power Bi already created a map data visualization displaying each row as a dot in the map.

power_bi_chart.PNG

The next step is save our report locally and the publish it into Power BI web. And that’s it every time a new row is added into our Azure Table Storage Power BI web is going to pull this new data and display it in our data visualization. As you can see this one it’s a really simple example but believe me when I tell you that Power BI gives us much more flexibility to create awesome dashboards. Later on this week I’ll create another post where I will use the Power BI SDK to integrate this report in our custom website.

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

For more details of Power BI 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.