Overview about .Net CLI

The .Net Core Command Line Interface is a new tool essential for development in ASP.NET Core. What do I mean by “essential?” Simple, any person or tool that wants to develop in the new platform of Microsoft must use this tool. It is the first layer of development. The VS2015 uses the .Net CLI to build, publish, run and other things. .Net CLI also is cross-platform, that is, it can run in Windows, Apple and Linux and to start with it you must download your distribuition to your SO.

You may wonder, “Do I need to learn this tool?” Those who work with Visual Studio 2015 UPDATE 2 do not need to, because internally the VS will use the .Net CLI. But when you do not use the VS, it will need to be used to develop in platform. Remember, now I can develop in other tools as Visual Studio Code, Sublime, Vim and others. Therefore, learning about it is good!

What can get people a little confused it is that some time ago the DNX tool was used. With the arrival of ASP.NET Core RC2, the DNX was replaced by DOTNET and all commands below are installed by default:


To use the CLI there is a pattern, driver (dotnet) + verb + argument (if there is). For example, after installing the .Net CLI type “dotnet new” in a test folder. You will see that a project was created, but in this example I only used driver + verb. Below I explain the other commands:

“dotnet restore” restores all dependecies needed to project.
“dotnet buil” compiles the application to validate if there are errors.
“dotnet run” runs the application.
“dotnet test” runs the tests of application.
“dotnet publish” publishes the application.
“dotnet pack” creates a Nuget Packages.

To execute the project created previously, we must execute the commands following: “dotnet restore”, “dotnet build” and “dotnet run”. Restore, build and run is something that all developers understand as a process in development. If you did not change the class created of project, you will see a message in console: “Hello World!”.

By default these are all the commands included, but you can create your own commands for this access.

.NET Core CLI extensibility model


The .Net CLI is a tool of the interface to develop in the .Net platform. Through it, we can create a new project, restore packages, do running and others. With the .Net CLI, code editors can use it for development, because it is cross-platform. Developing in Windows, Linux or Apple already does not make a difference in the new platform of Microsoft.

.NET Core Command Line Tools (CLI)

.Net CLI

O .Net Core Command Line Interface é a nova ferramenta essencial para desenvolvimento no ASP.NET Core, o que quer dizer com essencial? Simples, qualquer pessoa ou ferramenta que queira desenvolver na nova plataforma da Microsoft devem utilizar essa ferramenta. O VS2015 utiliza o .Net CLI para build, publish, run e entre outros. .Net Cli também é cross-platform, isso é, pode rodar em windows, apple e linux e para iniciar basta baixar a distribuição certa para o seu sistema operacional em https://github.com/dotnet/cli.

Você pode estar se perguntando, preciso aprender essa nova ferramenta? Para quem trabalha com o Visual Studio 2015 UPDATE 2 e tem o RC2 não precisa, pois internamente ele irá utilizar o .Net CLI, mas fora do VS você deverá aprender para poder desenvolver na plataforma, como em outros sistemas operacionais.  Lembre, agora você pode desenvolver fora do VS como: Visual Studio Code, Sublime, Vim e entre outros. Portanto aprender sobre .Net CLI is good.

O que pode deixar as pessoas um pouco confusas é que a até pouco tempo era utilizado os comandos do DNX. Com a vinda do ASP.NET Core RC2 o DNX foi trocado pelo DOTNET e todos os comandos abaixo são instalados por default:

  • new
  • restore
  • run
  • build
  • test
  • publish
  • pack

Para utilizar o CLI existe um padrão, driver (dotnet) + verbo + argumento (caso exista). Por exemplo, após instalado o .Net CLI, em uma pasta de teste, digite “dotnet new”. Você irá perceber que um projeto foi criado, mas nesse exemplo eu só utilizei o driver mais o verbo. Abaixo explico os demais comandos:

  • “dotnet restore” restaura todas as dependências necessárias para o correto funcionamento do projeto.
  • “dotnet buil” compila a aplicação para validar se existem erros.
  • “dotnet run” executa a aplicação.
  • “dotnet test” executa os testes que estão na solução.
  • “dotnet publish” faz a publicação da aplicação.
  • “dotnet pack” faz o build da aplicação e cria um Nuget Packages.

Para executar o projeto criado anteriormente, devemos executar a seguinte lista de comandos: “dotnet restore”, “dotnet build” e “dotnet run”. Caso você não altere nada na classe criada para o projeto irá ver uma mensagem no console: “Hello World!”. A explicação para funcionamento do app com esses comandos executados é simples: Restore, Build, e Run é algo que faz parte do processo do desenvolvedor.

Por default esses são todos os comandos inclusos, mas você poderia criar os seus próprios comandos, para isso acesse a página https://dotnet.github.io/docs/core-concepts/core-sdk/cli/extensibility.html


O .Net CLI é uma ferramenta de interface para desenvolver na plataforma .Net, através dela, podemos criar um novo projeto, restaurar, executar e entres outros. Com o .Net CLI outras IDEs em sistemas Linux ou Apple poderão utiliza-la para o desenvolvimento, pois o .Net CLI é cross-plataform. Desenvolver em Windows, Linux ou Apple já não faz diferença na nova plataforma da Microsoft.

The Startup Class In ASP.NET Core

The new Startup class in ASP.NET Core was changed and now it is clearer and divided in better sections. This is my opinion. The first thing that we have to understand: what is it for? How is it run? I begin the answer that this class is intended to be the initial point of project, by default the class called Startup is initialized by configuration of host, I am going to explain later. In this class is initialized all configurations needed to the project and now I am going to show so you can understand better.

In ASP.NET Core we have configuring a web host to start listening, because the new ASP.NET is only console apps. Program class does this configuration, in case where you create a web application using the VS. Below following the code:

As can be seen, the Program class is simple and it has an initial method (main). The web host created has some configurations and there we have a configuration to call the Startup class, through the method UseStartup, and this starts the life of the Startup class.

Three methods are seen in Startup class when created by VS:

  • Startup method where is responsible by load the values of configuration.
  • ConfigureServices method where is responsible by adding the services in container of dependency injection.
  • Configure method where is responsible by adding the middlewares and services in HTTP pipeline.

If you still are not familiar about middlewares, you can read other article where speaks about the subject.

Now comes the code time!

Startup method

As we all know, now we do not have anymore the file classic called “web.config” to configure your web site. It was changed for JSON. This is a tendency of others platforms and Microsoft joined. If we do not have the “web.config”, now we have the “appsettings.json” that looks like:

The file shows the configurations that will be loaded in constructor of Startup class. However, to load we need the interface IConfigurationRoot. The code is simple, it initializes a builder that loads the configurations of JSON and the environment variables, because to each environment, you can have different configurations. This new feature came in the ASP.NET Core. In the last line, we have the Configuration being loaded.

Note: The web.config still there is, but only to publish.

ConfigureServices method

Other nice changes that came in ASP.NET  is the arrived of a native dependency injector (DI), but you are free to add other DI that you like. In this method, I inform the services that will be added to DI to be enabled to use these classes without need of creating an instance, According what can be seen, was added the services: EF, identity, MVC and 2 classes. In relation to EF, observe that was informed using the SQL Server and Data Base Context where is informed a connection string through of Configuration, one that was initialized by Startup method.

In case you have specific class of project that you would like to add to DI, you also will use the IServiceCollection. For this, we must use one of the methods following according to Microsoft documentation:

  • Instance: A specific instance is given all the time. You are responsible for its initial creation.
  • Transient: A new instance is created every time.
  • Singleton: A single instance is created and it acts like a singleton.
  • Scoped: A single instance is created inside the current scope. It is equivalent to Singleton in the current scope.

Observe that for the specific interfaces, IEmailSender and ISmsSender, utilized the method AddTransient. From now, you can use these interfaces by inserting in constructor that the DI will load for you.

Configure method

In this method we control the ASP.NET pipeline. I am going to add all middlewares needed to the project. Be alert, do not add a middleware that will not be needed in the project, because how many more middlewares are added, heavier your application gets. The explanation is simple, each middleware stays in HTTP pipeline analyzing the request and response of application. To add a middleware, we must use the IApplicationBuilder parameter and call the middleware needed, case nothing is added in this method, neither the MVC will run, because you do not say what want to use for this application

Below I explain some middlewares and your responsibilities:

  • UserBrowserLink: Creates a channel of communication between the development and one or more browsers.
  • UseDeveloperExceptionPage: Shows the detail of exception thrown by application.
  • UseIISPlatformHander: Enable the use the web server IIS.
  • UseStaticFiles: Enable the utilization of static files as CSS, JS and others.
  • UseMvc: Enable the use of framework MVC.

Beyond the parameter IApplicationBuilder, we have the parameters IHostingEnvironment and ILoogerFactory, where the first loads the information about the current environment. In the code above we are utilizing this parameter to validate if we are in development environment and in case positive is added middlewares specific to this environment. Already the second parameter enables the system log where this is done in the first line.


It is not difficult to understand the behavior of the Startup class, but is essential to apply this fundamental to a correct working of application and for this to get alerts to which services are added.

A nova classe startup

Hoje vou falar sobre a nova classe Startup no novo ASP.NET Core e a entende-la melhor. Eu falo nova por que como o ASP.NET Core sofreu mudanças internas, a forma de inicializar o sistema também muda.

A nova classe startup no ASP.NET Core mudou e agora está muito mais limpa, dividida e como consequência mais clara. Essa pelo menos é a minha opinião. A primeira coisa que temos que entender é para que serve essa classe? Como ela é executada sendo que nada foi configurada para iniciar? Respondendo, esta classe serve para ser o ponto de partida do projeto, por default, a classe com nome Startup é inicializada de forma automática pelo ASP.NET. Nela é iniciada todas as configurações necessários para o projeto e agora vou mostrar a entender melhor essas configurações.

Três métodos são vistos na classe Startup quando criado através do template do VS:

• Método Startup onde é responsável por carregar os valores da configuração
• Método ConfigureServices onde é responsável por adicionar os serviços no container do injetor de dependência.
• Método Configure onde é responsável por adicionar os middlewares e serviços no HTTP pipeline.

Se você ainda não está familiarizado sobre Middleware, você pode acessar um outro artigo meu que fala sobre o assunto.

Agora vem a melhor hora, vamos ver código!

O primeiro código é o método Startup.

Como todos sabem, agora não temos mais o clássico arquivo chamado “web.config”. A verdade é que toda configuração em XML foi extinta nessa nova versão do ASP.NET e no seu lugar estamos usando o formato JSON. Isso já é uma tendência de outras plataformas e a Microsoft resolveu aderir. Se não temos o “web.config”, agora temos o “appsettings.json” e ele se parece como isso:

Estas configurações que serão carregadas no construtor da classe Startup. Mas para carregar precisamos da interface IConfigurationRoot. O código é simples, é inicializado um builder que carrega as configurações do JSON e as variáveis de ambiente, por que para cada ambiente você poderá ter configurações diferentes. Isso é uma nova feature que vem no novo ASP.NET. E na última linha temos a propriedade da classe Configuration sendo setada, isso será importante para os próximos métodos.

O segundo código é do método ConfigureServices.

Outra mudança legal que tivemos no novo ASP.NET é a entrada de um DI nativo, mas você está livre para usar um outro de sua preferência. Neste método estamos informando quais serviços iremos adicionar ao DI para que possamos usar facilmente em todo o nosso aplicativo.

Neste especifico método, conforme pode ser visto, foi adicionado os serviços EF, Identity, MVC e duas classes especificas. Em relação ao EF, note que estamos informando a utilização do SQL Server e o Data Base Context onde é informado uma string de conexão do banco através da propriedade Configuration que foi inicializada no construtor.

Caso você tenha especificas classes do projeto que queria adicionar ao DI do aplicativo, você também utilizará o IServiceCollection. Para isso devemos utilizar um dos métodos abaixo conforme a documentação na Microsoft:

• Instance: A specific instance is given all the time. You are responsible for its initial creation.
• Transient: A new instance is created every time.
• Singleton: A single instance is created and it acts like a singleton.
• Scoped: A single instance is created inside the current scope. It is equivalent to Singleton in the current scope.

Notem que no método ConfigureServices para as especificas interfaces, IEmailSender e ISmsSender, foi utilizado o método AddTransient. A partir de agora, você poderá utilizar essas interfaces apenas inserindo no construtor das controllers que o DI se encarrega de injetar por você. Coisa linda!

Configure é o último método para ser analisado.

Neste método controlamos o ASP.NET pipeline. Vamos adicionar todos os middlewares necessários para o projeto. Fique atento, não adicione um middleware que não seja necessário ao projeto, pois isso acarreta em perda de performance pois é inserido no HTTP pipeline.

Para adicionar um middleware basta usar o parâmetro do tipo IApplicationBuilder e adicionar os necessários ao projeto. Caso nada seja configurado neste método, nem o MVC irá rodar corretamente pois você não informou ao aplicativo o que usar. Abaixo eu explico a responsabilidade dos middlewares ativados:

• UseBrowserLink: Cria um canal de comunicação entre o ambiente de desenvolvimento e um ou mais browsers.
• UseDeveloperExceptionPage: Mostra o detalhe da exception gerada pela aplicação.
• UseExceptionHandler: Manipula a exception gerada em uma especifica página
• UseIISPlatformHander: Indica o usa do servidor web IIS
• UseStaticFiles: Habilita a utilização de arquivos estáticos como CSS, JS e outros.
• UseMvc: Habilita o uso do framework MVC.

Além do parâmetro IApplicationBuilder, temos os parâmetros IHostingEnvironment e ILoggerFactory, onde o primeiro armazena informações sobre o atual ambiente hospedado. No código acima estamos utilizando essa variável para validar se estamos em ambiente de desenvolvimento e em caso positivo é adicionado middlewares especificas para esse ambiente. Já o segundo parâmetro permite configurar o log do sistema onde isso é feito na primeira linha do método.


Não é difícil entender como se comporta a nova classe Startup no ASP.NET Core, mas é essencial aplicar esses fundamentos para um correto funcionamento da aplicação e por isso se atente em quais serviços e middlewares serão adicionados para que você tenha uma aplicação leve e rápida.



Middleware In ASP.NET Core

Today we are going to learn how to injecting little codes in HTTP Pipeline of ASP.NET Core using middleware. In addition, we are going to learn how construct one, so let us go!

“Middleware is defined in the OWIN specification as pass through components that form a pipeline between a server and application to inspect, route, or modify request and response messages for a specific purpose. Middleware consists of application components are incorporated into the ASP.NET HTTP pipeline.” The text is in the ASP.NET Core documentation, and as can be seen, with middleware we can insert a component that is incorporated in ASP.NET HTTP pipeline, that is, we can develop a code with a purpose to manipulate the requests and responses.

A characteristic of middleware is that normally there will a chain of middleware whereby order of configuration, one is called after the end of other and the current middleware can on any moment cancel invoking the next middleware, thus all chains of middleware will be canceled.


Do you have doubts about what is middlewares? We can compare middleware with the old http modules that today don’t exist in the new ASP.NET. I have already seen somebody comparing middlewares with a hamburger, because the middle is middleware and the ends are the application and the server. How much more middleware, bigger is the hamburger.

To get more clarity about the subject, I am going to show some middlewares that already are utilized by default in application templates to ASP.NET Core, and after I am going to create a custom middleware.

Below I show the startup class, note that there are some comments that indicate where there is a middleware.

Did you see the middlewares utilized in code? Here, each middleware has a responsibility and the gain that we have is we can choose only the ones needed for our project, different from old version of ASP.NET that by default many features were added even when they were not necessary. A very good phrase says: “Pay only by what you use”, in other words, how many fewer middleware you use, the less heavy will be the HTPP pipeline.

Other thing to observe that in code above, all the middlewares start with a “Use”, this is a pattern done by team ASP.NET.

Now I am going to create a own middleware and my goal will be creating one that shows the total time of application to take care of a request. Below following the code.

As can be seen, making a middleware is not difficult, it needs a constructor to receive the next middleware and an “Invoke” method that receives the context of HTTP. The goal of showing the total time of application gets in method Invoke. Before calling the next middleware, it is started the time and after of calling the next middleware, when all the middlewares already were executed, I execute the code to show in the HTML the total time.

Remember, I know that all middleware were executed because our middleware must be configured before of all others, thus the code will wait all executions and after the instruction “await _next(context);” we can write our code.

The code above is only to show the set up of our middleware in the Configure method of the Startup class. To that this works, it is needed using the instruction “app.UseMiddleware();”, where the UseMiddleware method is used to call custom middlewares.


The ASP.NET Core has changed, not the code that we know, but your core and by this, the way of manipulating a request and a response was changed to middleware. Now it’s lighter and easier to stay between an application and a server. However, take care, it is not because it got better that you must now only use that to develop.

Middleware em ASP.NET Core

No artigo de hoje vamos aprender injetar pequenos códigos no HTTP pipeline do ASP.NET Core utilizando Middlewares. Também vamos aprender a como construir um próprio, so let’s go!

“Middleware is defined in the OWIN specification as pass through components that form a pipeline between a server and application to inspect, route, or modify request and response messages for a specific purpose. Middleware consists of application components are incorporated into the ASP.NET HTTP pipeline.”. A citação está na documentação do ASP.NET Core, e como pode ser visto com Middleware podemos inserir um componente que é incorporado no ASP.NET HTTP Pipeline, ou seja, podemos desenvolver um código com um proposito especifico que será montado para manipular as requisições e respostas, a manipulação da informação pode acontecer nos dois lados do trafego.

Uma característica do Middleware é que normalmente existirá uma cadeia de Middlewares onde por ordem de configuração, um é chamado após a finalização do outro e o Middleware atual poderá a qualquer momento cancelar a invocação do próximo Middleware, fazendo assim que toda a cadeia pare de ser executada.


Tem dúvidas ainda? Algumas pessoas comparam Middlewares com o antigo HttpModules, que hoje não mais existe no novo ASP.NET. Eu já vi alguém comparando middlewares com um hambúrguer, porque o meio é middleware e as extremidades são a aplicação e o servidor. Quanto mais middleware, maior é o hambúrguer.

Para que você tenha ainda mais clareza sobre o assunto, eu irei demonstrar alguns Middlewares que já são utilizados por default pela aplicação e como criar um customizado. Mão na massa que agora começa os códigos.

Abaixo é mostrado a classe Startup, perceba que existem alguns comentários que indica onde existe um middleware.

Notou o tanto de middleware que são utilizados em um projeto default no ASP.NET Core? Aqui cada Middleware tem uma responsabilidade e um dos ganhos que temos é que podemos escolher apenas os que são necessários para nosso projeto, diferente da versão antiga do ASP.NET que por default muitas features eram adicionadas mesmo que o projeto não fosse utilizar. Middleware não é algo novo em desenvolvimento de sistema e isso já é utilizado na plataforma Node.js e existe um ditado em relação a ele: “pague apenas pelo que você usa”. Em outras palavras, quanto menos middleware você utiliza, menos gargalo existira no HTTP Pipeline e assim mais leve é a aplicação.

Outra coisa a observar no código acima é que todo middleware padrão utilizado começa com um “Use”, isso é um padrão feito pelo time do ASP.NET Core.

Agora vamos criar nosso próprio middleware e nosso objetivo de hoje será construir um que nos alerta o tempo de processamento da aplicação para atender a uma requisição, este será um middleware de log. Abaixo segue o código:

Como podem ver, fazer um middleware não tem nada de difícil, é necessário um construtor para receber o próximo middleware e um método “Invoke” que recebe o contexto do HTTP. O objetivo de mostrar o tempo de requisição da aplicação está no método Invoke, conforme pode ser visto, antes de chamar o próximo middleware é iniciado o contador do tempo e após a chamada do próximo middleware, isso é, quando todos os middlewares já foram executados, eu mando imprimir no HTML o tempo total da requisição no servidor.

Lembre-se, eu sei que todos os middlewares foram executados por que iniciei o nosso middleware por primeiro, conforme pode ser visto no próximo código, e após a instrução “await _next(context);” ser executada, toda a cadeia de middleware também foi executada conforme a nossa imagem do artigo mais acima.

O código acima é apenas para mostrar como ficou a configuração do middleware no método Configure da classe Startup. Para que isso de certo é necessário que ele seja executado por primeiro e em se tratando de um middleware customizado é necessário usar a instrução “app.UseMiddleware<ResponseTime>();”. Abaixo é visualizado como a informação do log na tela será mostrada.


A algum tempo já venho falando que o ASP.NET Core mudou, não o código que conhecemos, mas sim o seu núcleo e por isso a forma que trabalhávamos para manipular as requisições no passado também foram alteradas para Middleware. Mais leve e mais fácil para ficar entre a aplicação e o servidor. Mas tome cuidado, não é por que ficou melhor que você agora apenas deve desenvolver em middleware.

Gulp And Its Tasks

In this article we are going to learn to create tasks and integrate in the build of Visual Studio.

To those that are already used to using the .Net platform, version 4.0 and 4.5, it knows that to decrease files as js, css and others, you must use Bundle. Bundle is something fantastic and widely utilized, but I see a disadvantage, it is only used by those who develop in .Net. Its improvement and extension is limited by the ASP.NET community. Somebody can criticize my argument, I don’t think it’s a big argument, but why can’t we use tools that other communities are using and improving all the time and thus add to our community? Microsoft comes betting on this with your new stack of development. Microsoft, from Visual Studio 2015 to the new ASP.NET, decided to give us the liberty to use Node, Bower (I did an article about both) and Gulp, something that was not developed by Microsoft, but by the Node.js community. Today’s subject is about Gulp, what is and how use it in our projects. With Gulp, we going to learn to create tasks and integrate in the build of Visual Studio. Let’s go!

Sometimes I have the thought that development is easy, focusing only on the code and hearing music is something nice. However, development is not just that. It is taking care of others parts that oftentimes are boring and painful. This moment, I think again and change my mind. Have you ever had this thought? For instance, you create an application of the ground, the start is beautiful and it is following your manifest. Nevertheless, when it arrives close to the end, you notice that it still lacks many things, I am not talking about application functions, but of small things needed and done routinely. A lot of these tasks are in relationship to deployment, such as decreasing files to improve site performance. That is just an example, your team may have more tasks.

In the development of a site, many tasks are repeated and as explained above, Gulp can automate these tasks. In your site, gulpjs.com, it describes itself like “automatize and improve your workflow”. Node.js community has created Gulp. Gulp alone almost does not do too much, because it needs plug-ins to augment the task desired. For instance, do you want to decrease a file? It has a plug-in. Do you want to validate your js? It also has another plug-in. Each plug-in has a specific responsibility. The philosophy of Gulp is simple, set up the tasks through your own code . The configuration of Gulp in ASP.NET Core projects is zero, because it already comes installed. In projects legacies, you must do some steps that I am going to show below.

The first step is installing the Node.js, if you have doubts about the installation, read another article about the subject that I did before. Remember, Microsoft is investing too in Node.js, if you do not know, it is good to know from now on.

After installing Node.js, automatically it is installed the NPM. The objective of this article is not explains about Node.js, but I will do a summary: Node.js is a development platform and NPM is your package manager. With the NPM installed, go to a command-line of your computer and type in root of your web project: “NPM init”. By typing this command, it will do some tasks to be inserted in file created. Was Gulp installed? Of course not, this command serves only to create a configuration file in our project. Through this file, all node packages that I am going to install with the help of NPM will be listed. Validate in root of project if the package.json file was created with success.

After, return to command-line and type: “NPM install gulp –save-dev”. This command will install Gulp in your project and insert your dependency in the file that was created above. Now we have Gulp installed, but is not configured. For this, create a file in the root of your web project called “gulpfile.js”. This is the file responsible for receiving the tasks. Before writing some tasks, I am going to explain some structures of Gulp to improve your understanding. These are all methods used by Gulp: Task, Src, Watch, Dest, Parallel and Pipe.

Task: Method of input, create a task and your parameters are a name and a function to execute the task.

Src: Through this method is selected a file or files that must be modified after of the task.

Watch: As your own name says, it has the goal of watching a file or files that when changed is executed automatically.

Dest: This method informs the destiny where the modified file will be stored.

Pipe: Maybe the most important method, with it is executed all processes needed without expecting the end of each process. Also we can do a chain of process in the order needed.

Parallel and Series: Used in case where must execute processes in parallel.

Nice, you have an idea about Gulp and its methods, now we can go ahead. In file created, called “gulpfile.js”, add the following code and return to command-line and type: “Gulp default”.

var gulp = require('gulp' );

gulp.task('default', function () {

console.log('hello world');


If you note the response in command-line, you will see that was printed the messag was informed in the task. Realize also, to create a task we used the Task method. However, before creating a task, it was necessary to load the Gulp package, for this, it is necessary to use the Require method. According to what I said above, Gulp alone does not do too much and to improve the tasks level is needed to use others packages too. Before seeing more packages, I am going to create an application in Visual Studio 2015 and improve this project utilizing Gulp. The goal is to improve the performance.

I am going to begin the jobs with the css files, note in code below that have two styles in page layout. My idea is concatenate the files to be only one, decrease the size, pulling out spaces not used and finally, generating the styles that are not being used in the application, because when bootstrap is used, neither all styles of css are used. This tip is good to improve your site

	<link href="/Content/bootstrap.css" rel ="stylesheet" />
	<link href="/Content/site.css" rel="stylesheet" />

To do all the processes described above, it is necessary to install packages responsible by these processes. For this, install the packages: gulp-concat, gulp-cssmin e gulp-uncss. To install you must do the same process when Gulp was installed. Below is the code to create tasks.

var gulp = require('gulp' );
var concat = require('gulp-concat' );
var uncss = require('gulp-uncss' );
var cssmin = require(&amp;amp;quot;gulp-cssmin&amp;amp;quot; );

gulp.task('css-concat', function () {

return gulp.src([ 'content/*.css', '!content/*.min.css' ])




gulp.task('css', ['css-concat'], function () {

return gulp.src( 'content/site.min.css')


html: [ 'http://localhost:64161/']



.pipe(gulp.dest( 'content/'));


You have already seen before as Gulp is loaded, then the new packages must be loaded this way. After declaring the variables, it is time to create the tasks and here we have two, the first to concatenate all files that are in “content” folder, and the second task is to generate the styles that are being used by the application. Note that the two tasks are to improve the css.

In the first task, it is loaded the css files of application to concatenate and excluded the css file that will be generated in the end this process, in this case the file with end “min.css”. To exclude a file is placed in front a “!”. Task in Gulp must have an input file and for this the Src method is used. The first Pipe is to concatenate the files generated. The second Pipe is to inform the destiny of file created. Observe the utilization of some packages that were installed above.

The second task is similar, except by some details. The input file is the file generated in the first task. In the first Pipe used the uncss package to compare with the html informed, which styles are being utilized. Instead of passing a page as parameter, you can pass a folder where the entire html are stored. In the second Pipe is used the cssmin package to decrease the files and last, the destiny where the file will be stored. A difference of structure between first and the second task are the parameters. In the second task is informed [‘css-concat’], that informs that this task must be executed before and thus you do not need to execute it.

Now to see the results, it must come back to command-line and type: “gulp css”. Benefits? Before creating the tasks, the application had two css of a total de 125 kb, now it has a css with a total of 8 kb, thus, less traffic and size.

But I did not finish, now I am going to work with the js files. In layout exists three js files being used. The task that I am going to create will concatenate all files and decrease to only a file.

<script type="text/javascript" src ="/Scripts/jquery-1.10.2.js"></script>
<script type ="text/javascript" src ="/Scripts/bootstrap.js"></script>
<script type ="text/javascript" src ="/Scripts/respond.js"></script>

The following, the tasks to generate the file:

var gulp = require('gulp' );
var concat = require('gulp-concat' );
var uncss = require('gulp-uncss' );
var cssmin = require(&amp;amp;quot;gulp-cssmin&amp;amp;quot; );
var uglify = require('gulp-uglify' );

gulp.task('css-concat', function () {

return gulp.src([ 'content/*.css', '!content/*.min.css' ])




gulp.task('css', ['css-concat'], function () {

return gulp.src( 'content/site.min.css')


html: [ 'http://localhost:64161/']



.pipe(gulp.dest( 'content/'));


gulp.task('js', function () {

return gulp.src([ 'scripts/jquery-1.10.2.js', 'scripts/bootstrap.js' , 'scripts/respond.js', '!scripts/site.min.js' ])





Now have a task called “js”, the structure it is the same, it has an input point, that is, files that are being used in the page and less the file that is processed by Gulp. After doing the concatenation, it is selected where the file will be stored. The difference in this task is the utilization of uglify package, it is responsible for decreasing and validating if error exist in the js files.

Coming back to the benefits, in the two next images it is possible to see the browser log, a before and after of changes. It is possible to see a big difference in both size and time of download. A difference between Bundle and Gulp is the process of generating a css file only by what the system is utilizing, that is, in this process the styles not used are eliminated.

gulp antes

gulp depois

Ok, we optimize our files and we are ready to deploy, but how is the development environment? Can I work with files concatenated and minifyed in dev? Of course not, because it is hard to work with these files, you will not get to do debug. Then, I am going to show a technique that helps to use files when doing development and production.


	<link href="/Content/bootstrap.css" rel ="stylesheet" />
	<link href ="/Content/site.css" rel ="stylesheet" />



	<link href ="/Content/site.min.css" rel ="stylesheet" />


By placing this code, the system works on a way to perfect both development and production, thus, we do not need to change in each environment.

Until now Gulp was used by command-line and that is not nice. The right way is to work automatically. And now I am going to show as integrating with build of Visual Studio. By this, I have to create more tasks according to the below:

gulp.task('build', ['css', 'js'], function () {

console.log('executing gulp build');


This task serves only to call the others tasks created. Now we have to go in Web Property of project, Build Events and insert the code below:

cd $(ProjectDir)
gulp build

Now, each time that the project suffers a build, a task build will be executed, thus we cannot need to execute the Gulp in a manual way. Other differences between the Bundle and Gulp is that with Gulp the files are generated before publishing, already with Bundle it is generated after a system to be published, in the first request of a user.


To the ones that are used to developing applications in .Net, also it are used to using only tools made by Microsoft. The bundle of ASP.NET is an example, it’s reliable and safe. But I think arrived at a moment in which we must see other tools in other communities and bring the cases of success. Gulp is a success in the  Node.js community and in other communities. With Gulp we have millions of possibilities to create a task to help our project, because developing code is nice, but already taking care of things that take up our time is not cool.