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 – Implementing FirebaseUI for Web Authentication

What’s up guys, Eze is here. Earlier this week I wrote a post explaining how easy is to implement Firebase Authentication in our AngularJs projects, in case you missed it here you go the link. As I told you @lmoroney have written a bunch of posts regarding this topic, in one of his post he pointed out the need to have a good user experience during the login flow. Even if Firebase simplify the login process we still need to write a good user interface to support the process. What if I told you that Firebase team has this covered as well? Well it is true, they have  an amazing tool called FirebaseUI for web. 

Adding the component to our project

First thing we need to do is adding this awesome component to our project. In order to do that we have several options:

  • CDN: just reference the .js and the .css files from this location https://cdn.firebase.com/libs/firebaseui/1.0.0/
  • npm Module: By executing this command you can get all the necessary files $ npm install firebaseui –save
  • bower component: You can add the reference to your bower.json file or just execute the following command to the files $ bower install firebaseui –save and then reference those files in your project.

If you check my code here you can see that I have the reference in my bower.json file but you can use the option that best fit for your needs.

Using FirebaseUI

Unfortunately this component doesn’t have yet a native version for Angular anyway it doesn’t stop us to use it in our Angular projects. If you remember from the last post I’m using $firebaseAuth from the Angular Fire component. In order to use the same instance of the Firebase Authentication object I made an small modification in my auth service as you can see in the code below.

 var authObject = firebase.auth();
 var firebaseAuthObject = $firebaseAuth(authObject);
 var ui = new firebaseui.auth.AuthUI(authObject);

Doing that the AuthUI and $firebaseAuth object are using the same reference to the Firebase Auth object. Then we need to add the following element to our html. FirebaseUI will use it to display the authentication flow.

<div id="firebaseui-auth-container"></div>
<div id="loader"&amp;gt;Loading...</div>

And finally we need to configure FirebaseUI passing a config object to the start method.

 vm.callback = function(currentUser, credential, redirectUrl) {
    $rootScope.$broadcast(AUTH_EVENTS.loginSuccess, {});
    $location.path('/citytimer');
    return false;
 };

 // FirebaseUI config.
 var uiConfig = {
    callbacks: {
       signInSuccess: vm.callback,
       uiShown: function() {
          document.getElementById('loader').style.display = 'none';
       }
    },
    redirectUrl: '',
    credentialHelper: firebaseui.auth.CredentialHelper.ACCOUNT_CHOOSER_COM,
    queryParameterForWidgetMode: 'mode',
    signInFlow: 'popup',
    signInOptions: [
       firebase.auth.EmailAuthProvider.PROVIDER_ID
    ]
 };

 // The start method will wait until the DOM is loaded.
 authService.firebaseUI.start('#firebaseui-auth-container', uiConfig);

As you can see the config object has a lot of properties to define our authentication process.

  • callbacks: This property contains the callback functions to execute.
  • signInOptions: In this property we define the list of providers we have enabled in our Firebase console.
  • signInFlow: Define if we do a full redirect to login or we just open a popup. The full redirect option is recommended for mobile versions.
  • credentialHelper: I’ve configured the account chooser to let the customer select which email select.

login.png

As you can see handle the authentication using Firebase Authentication it’s really simple and even simplest if you add FirebaseUI for web. I have a working example that you can check here. As I always say in this post I just covered the basic to get up and running the authentication in our app. It’s up to you guys continue reading the documentation to get more knowledge.

For a complete reference of FirebaseUI use this link.

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.

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.