Hello World with MVC 6

In this post we will see how to write your first application using MVC 6 and Visual studio 2015.

We will go step by step.

First of all let us add simple MVC 6 project.

For that Open your Visual Studio 2015 and Create new project as shown below:

new-project-mvc6

and then select empty Asp.Net 5 preview.

new-project-select-empty-aspnet5-template

You can see the project structure like this:

aspnet5_beginning_demo_2

What is new in folder structure?

  • src folder – contains all projects that contain source code that make up your application.
  • global.json – this is where you put solution-level settings, and allows you to do project-to-project references.
  • wwwroot – is a folder in which all your static files will be placed. These are the assets that you web app will serve directly to the clients including HTML, CSS, Image and JavaScript files.
  • project.json – contains project settings
  • startup.cs – this is where you put your startup and configuration code.

But wait! Is it MVC?

No it is not.

Our next step is to configure the site to use MVC. This requires changes to the project.json file and Startup.cs file. First, open project.json and add “Microsoft.AspNet.Mvc” to the “dependencies” property:

So our project.json would be like this:

{
  "dependencies": {
       "Microsoft.AspNet.Mvc": "6.0.0-*",
       "Nowin.vNext": "1.0.0-*",
       "Kestrel": "1.0.0-*"
    },
  "commands": {
        "web": "Microsoft.AspNet.Hosting --server Nowin.vNext",
        "web-kestrel": "Microsoft.AspNet.Hosting --server Kestrel"
    }
}

Ok, so now it is Mvc project right?
Wait, we forgot to add configurations.

For that open Startup.cs and modify it as follows:

using System;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

public class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseServices(services =>
        {
             services.AddMvc();
        });

        app.Use(async (context, next) => 
        {
             Console.WriteLine(context.Request.Path);

             try
             {
                  await next();
             }
             catch(Exception ex)
             {
                   Console.WriteLine(ex);
             }
         });

       app.UseMvc();
      }
}

This code enables MVC and defines a route.

Voila! Yes now it is an Mvc Project.

Now let us add controlls and views.

Oh! Well we need to follow some steps to add controlers and views because we need to add simple class and make it a controller as below:

  • Add a Controllers folder
  • Add an MVC Controller called HomeController.cs class to the Controllers folder
  • Add a Views folder
  • Add Home folder in the Views folder
  • Add an Index.cshtml MVC View Page to the Views/Home folder.

The project structure should be as shown:

project-structure-controller-view

Now, Edit Index.cshtml as below:

<h1>Hello from Razor!!<h1>

And in HomeController:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

Run the application – you should see Hello World output in your browser.

hello-world

Congratulations for your first MVC 6 project!

Stay tuned for more!

New JSON parser in vNext : No Comments (Yet!)

Few days ago .Net team has announced about new JSON parser in Microsoft.Framework.Runtime which removed the dependancy on Newtonsoft.Json

Why did they removed dependency on Newtonsoft.Json?
Because Using Newtonsoft.Json in the run time prevents customers from choosing a specific version of Newtonsoft.Json in their applications. This change will allow customers to use any version of Newtonsoft.Json in their applications.

Ok, what it will parse basically?
Currently It is used to parse only the project.json, project.lock.json and global.json files.
Other components still use Newtonsoft.Json to parse JSON files i.e. Microsoft.Framework.PackageManager

Got it, That’s it or any other changes?
Umm… well one more thing, which is :

The new JSON parser doesn’t support the following syntax:
1. Comments in the form of // … and /* … */
2. Trailing commas after the last member of objects and arrays

Yes, I can feel your reaction, same as it was faced by .Net team when they announced this.

What was the main negative reaction?
It was for comments like why it is not supported.

Can you explain more like how will comments not supported?
Suppose you have very basic web project in vNext and you have project.json file as below:

 {
   "dependencies": {
     "Kestrel": "1.0.0-*",
     "Microsoft.AspNet.WebSockets.Server": "1.0.0-*",
     "Nowin.vNext": "1.0.0-*"
     },
   "commands": {
      "web": "Microsoft.AspNet.Hosting --server Nowin.vNext", 
       ////Here commenting like this will not be supported.
       "web-kestrel": "Microsoft.AspNet.Hosting --server Kestrel"
    }
}

Wait, does it mean that suppose for config files we will not be allowed to add comments?
For that there was nice answer from Mr David Fowler from Microsoft:

  • We’re using JSON, not any of those formats for the core project file. It’s JSON. Configuration we don’t care about as much, that can be in whatever format you choose, and that’s why there’s a provider model.
  • Build systems and project systems don’t let users choose what the file format is. Don’t mix up configuration files with project files. They are different beasts.
  • project.json, project.lock.json and global.json are not configuration files, they are part of the new project system.

Is there any work around for supporting comments?
There might be one solution like changing whole file format from JSON to any other like YAML, JSON5, TOML etc.

One more solution suggested by .Net team was :

What if we read both formats?

  1. If you have a project.json5 we’ll use that and you can add all the comments in the world.
  2. If you have a project.json, it’s strict JSON no comments allowed.

I’m not saying we’ll do this BTW but I want to see what people think (same for global.json but not project.lock.json, you don’t edit that one).

Something in deep? It might be look like: (Which is yet not confirmed)

image
Conclusion?

Conclusion of this situation is like for time being .Net team decided to stick with the industry standard JSON format.

Reasons for choosing JSON:

  1. Well, it’s an industry standard. That’s pretty neat.
  2. It has support in nearly every tool, web site, editor, parser, which leads to great interoperability.
  3. It is an easy-to-understand, human-readable/writable, computer-readable/writable format.
  4. It supports the right set of data structures: arrays, dictionaries, strings, numbers, Booleans.

And Mr Eilon Lipton from Microsoft said:

Though we’re not opposed to changing this(comments) in the future, this is where we are right now.

So, For now JSON format is fixed which would be parsed by new JSON parser and which will not allow comments in it.

I will update once updated from .Net team.

Till then keep faith in .Net team because they would definitely choose something awesome for all .Net users!

Remove Extra View Engines : Thanks to @Glimpse

Note: Some developers may knew this already but if you do not then read it because it will be used to increase your performance.

First of all what is View Engine?
The view engine is responsible for creating HTML from your views. Views are usually some kind of mixup of HTML and a programming language.

And what is Glimpse?
Glimpse is a web debugging and diagnostics tool used to gain a better understanding of whats happening inside of your ASP.NET application.

How to get Glimpse?
To install Glimpse, run the following command in the Package Manager Console :-

 glimpse_views_viewengine_partial (1)

Will it start automatically?
Well no, after downloading you need to turn Glimpse On.

Run the app, navigate below Url  :
http://localhost:54449/glimpse.axd ////Your port number instead of 54449

now turn Glimpse On as shown in below images.

screenshot-glimpse-axd

Ok, got it but what is the problem?
When you download Glimpse and run your application you will see below bar.

te

Now look closely, Let me zoom it for you:

te

You will see that it is looking for the razor and aspx files to all the possible locations. But as we know that we are using razor view engine so it should not waste time in looking other aspx files because we already know that it is not going to be part of solution.

Will it affect the performance?
It surely does. If you have big project then it will surely slow down the application and it directly decreases the performance,

Ohh! What is the solution then?
The solution is as shown below:

You can add this in global.asax Application_Start.

public void Application_Start()
{
     // Clears all previously registered view engines.
     ViewEngines.Engines.Clear();
     
     ViewEngines.Engines.Add(new RazorViewEngine());
}

Yes, it will only allow Razor as your view engine.

But wait there is a catch! We only need “cshtml” files right?

So here we go:

public void Application_Start()
{
     ViewEngines.Engines.Clear();

     IViewEngine razorEngine = new RazorViewEngine() 
    { 
         FileExtensions = new string[] { "cshtml" } 
    };

     ViewEngines.Engines.Add(razorEngine);
}

You will surely see nice improvement after this piece of code mainly when you have a big project.

In the end some links to redirect you to something awesome which is Glimpse.

Website: http://getglimpse.com/

Documentation: http://getglimpse.com/Docs/

Step by step process to install: http://getglimpse.com/Docs/Installing

Github: https://github.com/Glimpse

Stay tuned for more updates!

@inject : New directive of MVC

Few days ago there was a long discussion going on in .Net MVC team between [Activate] and @inject.

But recently they have announced that they are getting loud and clear positive feedback for @inject

Ok, so first of all what is inject for?

fear-of-needles-trypanophobia-150x150

You might have seen this before whether in Java or in spring. Now this is going to be used as a directive in MVC.

As the name suggests it is used for dependency injection. @inject supports injecting anything the container can resolve.

Wait, is it for Razor View?

Oh , Yes it is!

It is nothing but a new page directive which allows you to inject some method calls from a class or service directly into your view.

Confused?

Let us understand this by a simple example!

Suppose i have a ProductRepositry class in which i am having different methods as below:

using System.Threading.Tasks;

 namespace InjectDemo.Models
 {
    private ProductManager _manager = new ProductManager();

    public async Task<int> GetProducts()
    {
       return await Task.FromResult(_manager.GetAll.Count());
    }

    public async Task<int> GetProductById(int id)
    {
       return await Task.FromResult(_manager.GetProductById(id));
    }

    public async Task<int> GetProductByName(string id)
    {
       return await Task.FromResult(_manager.GetProductByName(id));
    }
 }

and in view:

@model System.Collections.IEnumerable

@inject InjectDemo.Models.ProductRepository Stats
     <h3>My Products</h3>
 <ul>
 @foreach (var p in Model)
 {
     <li>@string.Format("{0} {1}", p.Name, p.Type)</li>
 }
 </ul>
 <div> 
     <span>Product Number 1 : @await Stats.GetProductById(1)</span> 
 <br/> 
     <span>Product X: @await Stats.GetHeroCountByType("X")</span> 
 <br/> 
     <span>Ttal Count: @await Stats.GetProducts()</span> 
 </div>

Awesome, so now should it work?

Wait we need to add something more.

we need to configure the AddTransient() method by adding the ProductRepository model into it. So the Configure method would now look like this:

public void ConfigureServices(IServiceCollection services)
 {
       services.AddMvc();
       services.AddTransient < InjectDemo.Models.ProductRepository > ();
 }

Voila!

By the way if @inject is for razor then what is for MVC ?

It WAS [Activate].

the reason for using “WAS” is it is recently removed by .Net team due to the feedback.

So as stated by .Net team:

  • [Activate] is gone – we’d rather plug in a 3rd party DI for users who want property injection. There’s a consistency issue with MVC providing this and other parts of Asp.Net which don’t.

.Net team is working so hard to make it easy for all .Net developers and still asking for feedback.

I will update once updated by .Net team about @inject and related things.

Till then stay tuned for more updates.

Get source code via dnu sources : A New born MVC command

Today while surfing i got to know interesting very new born command by MVC which is called dnu sources.

Suppose you are extra enthusiastic person and who is willing to get code of particular package of MVC then .Net team is making it easier for you.

Now very first question that appears in mind is:

What is dnu sources?

dnu sources will retrieve the source code for the package.

Example:

Write below command :

dnu sources get <package-name>

this will retrieve the source code for the package named <package-name>

How can i try it?

Below are few steps to follow:

  1. First of all add refference of Microsoft.Framework.OptionsModel in your project.json file
  2. Run dnu restore command to restore the packages
  3. Run dnu sources get Microsoft.Framework.OptionsModel command in the project’s folder.

Ok, what are the conditions for running dnu sources?

  1. Package must be installed locally.
  2. The reference of the package(which you are looking for) must be added in the project.

Great, Any limitations?

Well currently it is new born baby so it is quite understable to have limitations which are as below:

  • Only Git is supported.
  • If you application references multiple versions of the same package, you will not be able to use dnu source.
  • Each version of a package will create a new folder under %userprofile%\.dnx\sources. That folder is never cleaned up.
  • There is no first class Visual Studio support (Yet).
  • If you don’t have the dev feed (myget.org/aspnetvnext) as a NuGet source and the package references any of the *.Sources packages (like Microsoft.Framework.NotNullAttribute.Sources), you will not be able to compile the new sources. The workaround is to add the feed to NuGet.config.
  • Currently, only the packages shipped by the ASP.NET and EF teams have source information. The CLR packages (System*), Roslyn or any other packages does not have source information. You will get an error message if you try to source them.
  • dnu sources works only for packages produced in beta6 or later. Any beta5 or earlier packages do not have source information in them.

Lastly have a look here to know how to add repository information to a package.

This command is at its very first stage and .Net team is asking for the feedback and i will update here once it is updated by the team.

Stay tuned for more updates.