Overview Of MVC 6 and Deployment On Azure

Introduction

I hope and anticipate that this article will be interesting and effective. This article will be covering the ASP.NET 5's MVC 6 Welcome application, a brief bit about the all new concepts of MVC 6, and the new structure it offers. Then we will create our first Welcome application and then have a walk through of the new Azure Portal and deploy our first web application.

Collage
 
The above image is all that we will be covering in our article.

Get Started

A perfect blend of cloud and web applications is what ASP.NET 5 is intended for. ASP.NET 5 is now being pulled back as .NET core is what stands out today. It is a framework with open source and cross platform for building cloud based web applications. Here Azure comes integrated with the Visual Studio applications. Web applications either can be deployed to cloud or be running on-premise. .NET core is available on Visual Studio 2015 build. You can download the community edition of the Visual Studio which is actually free. :) Community Edition Download. Give a try for sure! .Net 5 core contains a small optimized run time environment called "CoreCLR" One more important point to note is, .Net Core is opensource and the progress can be updated on Github. They have the code exposed and the build can be tracked easily. .Net core is said to contain a set of libraries known as "CoreFx". Below are the links to Github. Just have a look: Another important benefit is termed as "Portability". What this means is, we can package and deploy the Core CLR which can in turn help you eliminate the dependency on the installed version of .NET framework. Multiple applications running on different versions of CLR can be set up well. This is the magic the team wanted to happen, which is great! With .NET 5 and VS 2015 comes MVC 6 intothe picture. Microsoft builds are moving faster than the world! :D When I first looked at the structure of the Solution when I added a new MVC project, I was like What!! Where is Global.asax.cs? Where is Web.config, App_Start?. Did I download the correct files and selected the correct template? These sort of questions were flickering in my mind. When I ran the application it ran successfully as well. Strange!!

Let's have a small trip into the MVC6

Unified MVC Controllers

MVC 6 is the merger, the blend of three frameworks, i.e. MVC, Web API2 & Web Pages. Previous versions of MVC, while adding a new template would prompt to check whether we want Web API along with MVC. Here we select the MVC project and we get the opportunity to work with the API as well. In previous versions there were two base controller classes, separate for normal controller and also for the API controller, i.e. ApiController.
  1. public class TestController: Controller  
  2. {  
  3.   
  4. }  
  5. public class ApiTestController: ApiController   
  6. {  
  7.   
  8. }  
In earlier versions as shown above, the controller base classes were from System.Web.MVC.Controller and for API, System.Web.Http.ApiController. But in MVC 6 it is only one, i.e. Microsoft.AspNet.Mvc.Controller.

Different style of HTML helpers

In MVC 6 there comes a new title termed  Tag Helpers. They make life much more simple. How! We will get to know once we see the code snippet. For normal web pages, as we know the HTML helpers are defined within the System.Web.WebPages.Html under System.Web.WebPages , whereas in MVC 6, it is under the System.Web.MVC assembly. The HTML helpers which we used to use in Razor or ASPX, were quite difficult for normal HTML developers to understand (suppose designers). Now MVC 6 has been simplified using the Tag Helpers.
  1. @using(Html.BeginForm())  
  2. {  
  3.     @Html.LabelFor(m => p.EmpName, "Employee Name:")  
  4.     @Html.TextBoxFor(m => p.EmpName) < input type = "submit"  
  5.     value = "Create" / >  
  6. }  
But in MVC 6 ,
  1. @model AzureDemoProject.Models.Employee  
  2. @addtaghelper "Microsoft.AspNet.Mvc.TagHelpers"  
  3. < form method = "post" > < div >   
  4. < label > Employee Name: < /label>       
  5. < /form>  
Now the second snippet looks more HTML friendly and also a bit simple. Mr. Damian Edwards has posted the source code on Github which has examples of Tag Helpers. Please go through for better live understanding Git Hub Tag Helpers Download and play around.

Support for Grunt, NPM & Bower

These are the latest trending front end development tools. These are quite new to me as well, but I will be learning and posting articles on these as well in coming days. Stay tuned!! Ok branding apart, ;) lets have a brief idea about what these are.

gnpmbower

Bower:

This is a client side item added by default to MVC6 project. If not added, then Right click on the project, Add, New Item, Installed(Client Side)-> Bower.json. You can find then the file is already installed. The file is inside the wwwroot, lib, bootsrap, bower.json. As you open up the file, you can find the client side tool packages added to the project and their versions. Thus, we got to know that the bower is a client side package manager which is used to add the front-end packages like bootstrap, jQuery, angular, etc.

Grunt:

In MVC 6 project when we add, we can find the gulpfile.js, this is kind of an alternative to Grunt as both perform the same kind of functions. The operations they perform re minification, cleaning, concatenation, etc. of both js & css files.

NPM: 

Node Package Manager is present under the project with the name project.json. This holds the dependencies and their versions required by the web application we have set up.
  1. "dependencies":   
  2. {  
  3.     "EntityFramework.Commands""7.0.0-rc1-final",  
  4.     "EntityFramework.MicrosoftSqlServer""7.0.0-rc1-final",  
  5.     "Microsoft.ApplicationInsights.AspNet""1.0.0-rc1",  
  6.     "Microsoft.AspNet.Authentication.Cookies""1.0.0-rc1-final",  
  7.     "Microsoft.AspNet.Diagnostics.Entity""7.0.0-rc1-final",  
  8.     "Microsoft.AspNet.Identity.EntityFramework""3.0.0-rc1-final",  
  9.     "Microsoft.AspNet.IISPlatformHandler""1.0.0-rc1-final",  
  10.     "Microsoft.AspNet.Mvc""6.0.0-rc1-final",  
  11.     "Microsoft.AspNet.Mvc.TagHelpers""6.0.0-rc1-final",  
  12.     "Microsoft.AspNet.Server.Kestrel""1.0.0-rc1-final",  
  13.     "Microsoft.AspNet.StaticFiles""1.0.0-rc1-final",  
  14.     "Microsoft.AspNet.Tooling.Razor""1.0.0-rc1-final",  
  15.     "Microsoft.Extensions.CodeGenerators.Mvc""1.0.0-rc1-final",  
  16.     "Microsoft.Extensions.Configuration.FileProviderExtensions""1.0.0-rc1-final",  
  17.     "Microsoft.Extensions.Configuration.Json""1.0.0-rc1-final",  
  18.     "Microsoft.Extensions.Configuration.UserSecrets""1.0.0-rc1-final",  
  19.     "Microsoft.Extensions.Logging""1.0.0-rc1-final",  
  20.     "Microsoft.Extensions.Logging.Console""1.0.0-rc1-final",  
  21.     "Microsoft.Extensions.Logging.Debug""1.0.0-rc1-final",  
  22.     "Microsoft.VisualStudio.Web.BrowserLink.Loader""14.0.0-rc1-final"  
  23. }, "scripts":   
  24. {  
  25.     "prepublish": ["npm install""bower install""gulp clean""gulp min"]  
  26. }  
As we can see in the above snippet, it is just a part of the project.json file. This is to show the default dependencies added to the project and the pre published scripts mentioned. When we are supposed to add a new dependency, suppose I try and add System.Linq, it will list up the Nuget package as intellisense and then we add the version which also comes under the IntelliSense. Like the following image:

projectjson

Then after hitting Ctrl+S, the restoring of the references packages starts.

restor
 
Then we see the references added. For more information on the project.json file and its contents, please visit the below link: Project.json Integration to Cloud & optimized: This is another major boost feature added to MVC6 application. Now it comes integrated to the cloud with Microsoft Azure and also the optimizing and monitoring tool provided by Azure, i.e. Application Insights. We will have a walk through of adding the cloud Web application and then a brief on Application insights as well. Boosted Dependency Injection: Now MVC 6 application has built-in and integrated dependency injection facility. There is no more need for the packages like Ninject, Unity, Structure Map 3 and all. The code for the configuration setting for the dependency injection is added inside the StartUp.cs class file as below:
  1. // This method gets called by the runtime. Use this method to add services to the container.    
  2. public void ConfigureServices(IServiceCollection services)  
  3.   
  4.   
  5.     // Add framework services.    
  6.   
  7.     services.AddApplicationInsightsTelemetry(Configuration); 
  8.   
  9.     services.AddEntityFramework()  
  10.   
  11.     .AddSqlServer()  
  12.   
  13.     .AddDbContext(options =>  

  14.   
  15.         options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));  
  16.   
  17.   
  18.     services.AddIdentity < ApplicationUser, IdentityRole > ()  
  19.   
  20.   
  21.     .AddEntityFrameworkStores()  
  22.   
  23.   
  24.     .AddDefaultTokenProviders();
  25.   
  26.   
  27.     services.AddMvc();  
  28.   
  29.     // Add application services.    
  30.   
  31.   
  32.     //Dependency Injection as well    
  33.   
  34.   
  35.     services.AddTransient < IEmailSender, AuthMessageSender > ();  
  36.   
  37.   
  38.     services.AddTransient < ISmsSender, AuthMessageSender > ();  
  39.   
  40.   
  41. }  
Then we normally inject the services into the constructor of the controllers. Isn't that great!!

appsettings.json:


As we know there is no Web.config file in our application, but we need to have a place where we have the settings required by the application at all stages. This is this place. In MVC6, they have had a upper hand over the JSON than the XML. :P The connection strings, the other app settings file we used to add inside the Web.config will now be contained here, that too in Json format. An example like below:
  1. "Data": {  
  2.     "DefaultConnection": {  
  3.       "ConnectionString": "Server=(localdb)\\  
  4.     mssqllocaldb;Database=aspnet5-AzureWebAppDemo-XXXXXXXXXXXXXXXXXXX-XXX;  
  5.     Trusted_Connection=True;MultipleActiveResultSets=true"  
  6.     }  
  7.   }  
global.json:

This is a separate folder named Solution Items. Here is the global.json file, which contains the solutions's project references and their dependencies as well. Looks like below:
  1. {  
  2.     "projects": ["src""test"],  
  3.     "sdk":   
  4.     {  
  5.         "version""1.0.0-rc1-update1"  
  6.     }  
  7.  
The appsettings is initialized into the project in the Startup.cs file as below:
  1. var builder = new ConfigurationBuilder()  
  2.   
  3.   
  4. .AddJsonFile("appsettings.json")  
  5.   
  6.   
  7. .AddJsonFile($ "appsettings.{env.EnvironmentName}.json", optional: true);  
The App_Start which had the RouteConfig.cs file also goes missing. In MVC is present inside the Startup.cs file as below:
  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  2.   
  3.   
  4. {  
  5.     app.UseMvc(routes =>  
  6.         {  
  7.             routes.MapRoute(  
  8.   
  9.                 name: "default",  
  10.  
  11.                 template: "{controller=Home}/{action=Index}/{id?}");  
  12.         });  
  13. }  
Thus, lets have a look at the entry point of the application:
  1. // Entry point for the application.    
  2.  public static void Main(string[] args) => WebApplication.Run(args);  
Another nice feature is the segregation of the Models & View Models. The Model now only will deal with the Db Entities and the context, whereas the ViewModel will deal with the model classes which are required in the View binding. This was just a brief about MVC 6, more information and application building will be shown in the upcoming articles on MVC 6. Now lets jump start the deployment to Azure. 

Head start Deployment

Now le's discuss creating a new MVC 6 project from VS 2015 and then deploying to Azure, mostly I will pictorially explainto  you which will help you understand better.
  • Step 1:

    Create a brand new project from the Visual Studio 2015 templates. Select the cloud directly and then the Web project as we will be deploying our application to azure.

     1

  • Step 2:

    Then after giving a name for the project, another window will prompt which will ask for the Microsoft Azure configurations. Web App Name, which will actually be the URL for the application after hosted on cloud.Then it asks for the Application Service under which the application will be registered and deployed. Region is another important factor which might come handy in the performance of the application. Thus, we select East Asia here. If asked for the Database server and the application required we add a new database server or use any existing database. We skip for now the database integration.

    2

  • Step 3:

    After setting up, we land in creating our first web application and the structure is like below,

    3

  • Step 4: Let's have a look at project structure which gets created.

    4

  • Step 5:

    Let's now publish and deploy our web application. Right click on the project and click 'Publish'. We then see a window pop up like below:

    8

  • Step 6:

    This will now create an Application Service(Webservice) on Azure portal and also deploy our Web Application as a new Website. The status can be seen under Azure Activity,

    10

    11

    12

    The above images are the over all status and the name of the publish package that got deployed.

  • Step 7:

    Then navigate to the Azure portal, already notifications would be highlighted to let you know that web site is now hosted and you can browse.

    15
         
    The status app type and the app status will update in a few minutes.
Conclusion:

Thus, once the website is hosted on Azure, we can browse and run our application and share with anyone to navigate through our application. We came to know in this article how easy it is to deploy to the cloud in the latest builds, making the lives of developers much easier. I will be sharing and covering the Application Insights in the next article which will follow this up. I hope this has helped in learning some facts about MVC6 and please post your feedback.
Application Insights- upcoming.

References
Read more articles on Azure: