Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / All-Topics

Overview of MVC6 & Deploy Application to Azure

5.00/5 (3 votes)
4 Apr 2016CPOL9 min read 13.2K  
Overview of MVC6 & Deploy Application to Azure

This article is an entry in our Microsoft Azure IoT Contest. Articles in this section are not required to be full articles so care should be taken when voting.

Introduction

With an anticipation and hope, this article would be interesting and effective somehow. This article will be covering the ASP.NET 5’s MVC6 Welcome application. a brief about all the new concepts of MVC6 and the new structure it beholds. Then, we 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 application is what ASP.NET 5 is intended for. ASP.NET 5 is now being called off as .NET core is what that stands out today. It is a framework with open source & cross platform for building cloud based web applications. Here, Azure comes integrated to the Visual Studio applications. Web applications either can be deployed to cloud or be running on 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. :)

.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 the 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 application running on different versions of CLR can be set up as well. This is the magic the team wanted to result out, which is great!

With .NET 5 and VS 2015 comes MVC6 into the picture. Microsoft builds are moving faster than the world! ??

When I first looked at the structure of the Solution when I added a new MVC project, I was like What!!

thinkzoo

Where is Global.asax.cs? Where is Web.config, App_Start?. Did I download the correct files and select 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

MVC6, 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 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.

C#
public class TestController: Controller {

}

public class ApiTestController ; ApiController {

}

In the earlier version as shown above, the controller base class was from System.Web.MVC.Controller and for API, System.Web.Http.ApiController. But in MVC6, it is only one, i.e., Microsoft.AspNet.Mvc.Controller.

Different Style of HTML Helpers

In MVC6, there comes a new title termed as Tag Helpers. They make life much more simpler. 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 MVC6, it is under the System.Web.MVC assembly.

The HTML helpers which we used in Razor or ASPX were quite difficult for normal HTML developers to understand (suppose designers). Now, I MVC6 that has been simplified using the Tag Helpers.

C#
@using (Html.BeginForm())
{
        @Html.LabelFor(m => p.EmpName, "Employee Name:")
        @Html.TextBoxFor(m => p.EmpName)
        
        <input type="submit" value="Create" />
}

But in MVC6:

C#
@model AzureDemoProject.Models.Employee
@addtaghelper "Microsoft.AspNet.Mvc.TagHelpers" 
<form method="post">
<div><label>Employee Name:</label> 
<input type="text" /></div>
<input type="submit" value="Save" />

</form>

Now the second snippet looks more like HTML friendly and is also a bit simple.

Mr. Damian Edwards has posted the source code on Github which has examples of Tag Helpers. Please go through it for better live understanding.

Support for Grunt, NPM & Bower

These are the latest trending front end development tools. These are quite new to me as well, ?? but will be learning and posting articles on these as well in coming days. Stay tuned!!

Ok branding apart, ?? let's have a brief idea on 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: Then, you can find that 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 MVC6 project when we add, we can find the gulpfile.js, this is kind of an alternative to the Grunt as both performs the same kind of functions. The operations they perform is 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.

C#
"dependencies": {
    "EntityFramework.Commands": "7.0.0-rc1-final",
    "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
    "Microsoft.ApplicationInsights.AspNet": "1.0.0-rc1",
    "Microsoft.AspNet.Authentication.Cookies": "1.0.0-rc1-final",
    "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-rc1-final",
    "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-rc1-final",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions" : "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.UserSecrets": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final"
  },
 "scripts": {
    "prepublish": [ "npm install", 
    "bower install", "gulp clean", "gulp min" ]
  }

As we can see in the above snippet, which is just a part of the project.json file. This is to show the default dependencies added to the project and the pre publish scripts mentioned. When we suppose 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 below 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:

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 MVC6 application has in built and integrated dependency injection facility. There is no more need for the packages like, Ninject, Unity, Structure Map3 and all. The code for the configuration setting for the dependency injection is added inside the StartUp.cs class file as below:

C#
// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext(options =&gt;
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

            services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;()
                .AddEntityFrameworkStores()
                .AddDefaultTokenProviders();

            services.AddMvc();

            // Add application services.
            //Dependency Injection as well
            services.AddTransient&lt;IEmailSender, AuthMessageSender&gt;();
            services.AddTransient&lt;ISmsSender, AuthMessageSender&gt;();
        }

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 an upper hand over the JSON than the XML. ??

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:

C#
"Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=(localdb)\\
	mssqllocaldb;Database=aspnet5-AzureWebAppDemo-XXXXXXXXXXXXXXXXXXX-XXX;
	Trusted_Connection=True;MultipleActiveResultSets=true"
    }
  }

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. Loos like below:

C#
{
  "projects": [ "src", "test" ],
  "sdk": {
    "version": "1.0.0-rc1-update1"
  }
}

The appsettings is initialized into the project in the Startup.cs file as below:

C#
var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

The App_Start which had the RouteConfig.cs file also goes missing. In MVC, it is present inside the Startup.cs file as below:

C#
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
               app.UseMvc(routes =&gt;
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Thus, let's have a look at the entry point of the application:

C#
// Entry point for the application.
        public static void Main(string[] args) =&gt; 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, where as the ViewModel will deal with the model classes which are required in the View binding.

This was just a brief about MVC6, more information and application building will be shown in the upcoming articles on MVC6. Now let's jump start the deployment to azure.

done

Head Start Deployment

Now let's discuss creating a new MVC6 project from VS 2015 and then deploying to Azure, mostly I will pictorially explain to you which will help to understand it 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 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. For now, we skip 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 the 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 1112

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)