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.

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.

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.

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 + 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.

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.

Advanced C# – Enumeration Types as Bit Flags

Hi guys, it have been a while since my latest post. Today I want to show you a really useful way to use Enumerations in C#. I know everyone knows how and what for use Enums. For instance the most common use for enumerations is to define a list of types. Anyway lets take a few seconds to remind the basics of enumerations in C#.

enum Days 
{ 
	Sunday, 
	Monday, 
	Tuesday, 
	Wednesday, 
	Thursday, 
	Friday, 
	Saturday 
};
enum Months : byte 
{ 
	Jan, 
	Feb, 
	Mar, 
	Apr, 
	May, 
	Jun, 
	Jul, 
	Aug, 
	Sep, 
	Oct, 
	Nov, 
	Dec 
}; 

By default every item in the enumeration is represented by an Integer value (int) but in case you want using a colon you can specify the numeric data type as I did in the example above. The approved types for an enumeration in C# are byte, sbyte, short, ushort, int, uint, long, or ulong.

Days today = Days.Monday;
int dayNumber =(int)today;
Console.WriteLine("{0} is day number #{1}.", today, dayNumber);
//output: Monday is day number #1

We can use either the numeric value of the enumeration or the label value as string so it gives us the possibility to define types and use it along our solution.

Enumerations as bit flags.

One property of the enumerations in C# it’s the possibility of use them as bit flag. It means that you can store in a Enum property several values using the logical operations like AND, OR or XOR as I show you in the following example.

//Adding Tuesday, Thursday and Friday as flag using bitwise OR.
Days meeting = Days.Tuesday | Days.Thursday | Days.Friday;

//test if Thursday is a flag using bitwise AND.
bool test = (meeting &amp;amp; Days.Thursday) == Days.Thursday;
Console.WriteLine("Thursday {0} a meeting day.", test == true ? "is" : "is not");
//output: Thursday is a meeeting day.

// Remove a flag using bitwise XOR.
meeting = meeting ^ Days.Tuesday;
Console.WriteLine("Meeting days are {0}", meeting);
//output: Meeting days are Thursday, Friday

As you can see we can easily add a flag using OR statement or remove a flag using XOR. In the same way we can validate if a flag is present just using AND. Really easy to use an useful tool.

Just an interesting point the Enum class has a method call HasFlag which receive an Enum value and determines whether one or more bit fields are set in the current instance.

Hope you have enjoyed this post. If you have any question or doubts please do not hesitate to let me know. Otherwise see you online.