terça-feira, 20 de fevereiro de 2018

ASP.NET MVC with Entity, Identity and Migrations Part 3 - File Upload

In the third part of this MVC tutorial we add two new controllers and models with the ability to upload files to our web site.

The Room model is pretty simple:

 public class Room {
        public int nr { get; set; }

        [Required(ErrorMessage = "Deve indicar o piso do quarto")]
        public int piso { get; set; }

        [Required(ErrorMessage = "Deve indicar a lotação")]
        public int lotacao { get; set; }

        [Required(ErrorMessage = "Deve indicar o estado do quarto")]
        public bool estado { get; set; }

        [Required(ErrorMessage = "Deve indicar o preço por dia do quarto")]
        public decimal custo_dia { get; set; }

Just add the controller with Entity framework and that's it.

Next add the Client model:

    public class Client {
        public int ClientId { get; set; }

        [Required(ErrorMessage = "Tem de indicar o nome do cliente")]
        [MinLength(5, ErrorMessage = "O nome é muito pequeno")]
        public string nome { get; set; }

        [Required(ErrorMessage = "Tem de indicar a morada do cliente")]
        [MinLength(5, ErrorMessage = "Morada muito pequena")]
        public string morada { get; set; }

        [Required(ErrorMessage = "Tem de indicar o código postal do cliente")]
        [MinLength(7, ErrorMessage = "O código postal é muito pequeno")]
        [Display(Name = "Código Postal")]
        public string cp { get; set; }

        public string email { get; set; }

        public string telefone { get; set; }

        [Display(Name = "Data de Nascimento")]
        [Required(ErrorMessage = "Tem de indicar a data de nascimento do cliente")]
        public DateTime data_nascimento { get; set; }

Next add the controller and the view with the Entity framework.

Now in the Client create view add the file upload control, like so:

        <div class="form-group">
            <input type="file" name="fotografia" id="fotografia" class="form-control" /><br />

Next alter the form generation line:

@using (Html.BeginForm("Create", "Clients", FormMethod.Post, new { enctype = "multipart/form-data" }))

This makes a web form with multipart encoding.

To close things up we have to change the function that receives the form to save the file:

 public ActionResult Create([Bind(Include = "ClientId,nome,morada,cp,email,telefone,data_nascimento")] Client client)
            if (ModelState.IsValid)
                //save the file
                HttpPostedFileBase fotografia = Request.Files["fotografia"];
                if (fotografia != null) {
                    string imagem = Server.MapPath("~/Images/") + client.ClientId.ToString() + ".jpg";
                return RedirectToAction("Index");

            return View(client);

Don't forget to create the Images folder.

To be able to see the files uploaded we change the index view adding a new column with the picture:

            <img src="@Url.Content(String.Format("~/Images/{0}.jpg",item.ClientId))" width="100" />

All this is available on Youtube

And GitHub

domingo, 18 de fevereiro de 2018

TensorFlow Variables and Placeholders

In this second part of the introduction to TensorFlow we add two new node types: variables and placeholders.

Let's use the same example that we have used in the first part. We start by importing TensorFlow:

import tensorflow as tf

Next we start a session, but before let's make a reset to the graph internal state:


And now we create two variables of type 32 bit float:

x = tf.Variable(2.0,tf.float32)
y = tf.Variable(3.0,tf.float32)

Since we are using variables we must initialize them:

init = tf.global_variables_initializer()

The mathematical expression is this:

sumnodes = x + y

To evaluate the expression:


Because we are using variables we can change the values like so:


As always we must execute the assign operation inside a TF session. To make multiple assigns we create references to the operations and execute them with one line:

NewX = x.assign(5.0)
NewY = y.assign(10.0)


Now the expression evaluates to a diferente result:


Placeholders have a different behavior as they allow to define the value only when the expression is evaluated and they can be assign to one value or a range of values.

Something like this, first define the placeholder:

a = tf.placeholder(tf.float32)

As you can see there is no value set. Next, let's change the expression:

sumnodes = x*a + y

To evaluate the expression we must use:

print(sess.run(sumnodes,{a: 10}))

The parameter defines the value of the placeholder. It's possible to use this:

print(sess.run(sumnodes,{a: range(10)}))

or this:

print(sess.run(sumnodes,{a: [2,5,8,11]}))

As we are working with placeholders and variables it's very important to close the TensorFlow session:


The video on youtube

The code on GitHub

segunda-feira, 12 de fevereiro de 2018

Introduction to TensorFlow - Part 1

"TensorFlow is an open source software library for numerical computation" in tensorflow.org

In TensorFlow each node can be a constant, a variable or a numerical expression that uses variables and/or constants.

This nodes can be executed in a CPU or a GPU taking advantage of multicore devices.

Start by import the tensorflow library:

import tensorflow as tf

Create a constant with:

node1 = tf.constant(3.0)


node2 = tf.constant(4.0, dtype=tf.float32)

The first line allows tensorflow to guess the data type.

Start a tensorflow session:

sess = tf.Session()

If you need to see the node type use:


With this line you get to evaluate the nodes value:


Create a mathematical function that adds the two constants with:

sumnodes = tf.add(node1,node2)

Evaluate the function:


Youtube video:

Code on GiHub

How to install TensorFlow in Anaconda:

ASP.NET MVC with Entity, Identity and Migrations Part 2 - Dropdownlist

In the second part of this MVC tutorial we add a dropdown list to select the user role when creating or editing a user.

In the User model we must add a new field that represents an interface that stores the options:

public IEnumerable<System.Web.Mvc.SelectListItem> perfis { get; set; }

Now in the User controller the Create and Edit functions must be changed. Each function must add the options to the perfis interface before showing the view. Something like this:

        // GET: Users/Create
        public ActionResult Create()
            //perfis options for the dropdownlist
            var user = new User();
            user.perfis = new[] {
                new SelectListItem{Value="0",Text="Admin"},
                new SelectListItem{Value="1",Text="User"},
            return View(user);

In the views the text box must be deleted and a drop down must be added to the field.

The line that generates the drop down is this:

 @Html.DropDownListFor( model=>model.perfil,new SelectList(Model.perfis,"Value","Text"))

Youtube video

Project code in Github

terça-feira, 6 de fevereiro de 2018

ASP.NET MVC with Entity, Identity and Migrations

In this tutorial we explore the Microsoft MVC architecture with Entity framework, Identity framework and Migrations for the database manipulation.

Entity framework is responsible for Object-Relational Mapping, i.e., storing objects in a relational SQL Server database, without SQL.

Identity framework controls the user credentials, login and access control with different roles for each user.

The database will be created with migrations (code first), we start by creating the class that represents the data in memory and then with migrations the table gets created.

Checkout the video bellow

The code is available on Github.

sexta-feira, 26 de janeiro de 2018

Decision Trees

In this article we create a decision tree to classify the gender of people based on their height, weight and size of footwear.

To begin we import from the tree from framework sklearn.

from sklearn import tree

Then we create a vector X with the values ​​that allow us to create a trend.


To these values ​​we have to join the classification of each element, so we created the vector Y.


Now we can create an object of type DecisionTreeClassifier.


We enter values ​​and ratings.


Finally we can make a prediction based on a new example.


Just change the values ​​to get a different rating.

Code on Github

Video on YouTube

quinta-feira, 4 de janeiro de 2018

Installing TensorFlow in Windows 10 with Anaconda

This video shows how to install TensorFlow in Windows 10 with Anaconda without the need to use the terminal window.

Start by opening the Anaconda Navigator tool and create an Environment.

Now, with the environment selected, search for the TensorFlow package e click install.

Next install the Anaconda code editor, Spyder.

When all is finished, update the TensorFlow version with this command:

     conda install -c conda-forge tensorflow

Don't forget that you must start Spyder through the terminal window of this environment, other wise it won't be running in the new environment and, for that, you must start the terminal window and type spyder.