Thursday, 5 July 2018

Upload and download files using HTML5 File Uploader Control and AngularJS

Upload and download files using HTML5 File Uploader Control and AngularJS


In classic ASP.Net, uploading a physical file using the file upload control is very easy. But when we need to do the same type of work in a normal HTML project using a client-side script like AngularJs and the Web API, there is some special process required. This article explaines how to upload a file using AngularJs. Also, during the upload process, we will copy the file from its original location to a specified location. Then we can also download that file from that specified location.
For the preceding purposes, we create two projects in Visual Studio.
  • One project is a blank website named FileUploader.
  • The second project is an empty Web API project named FileUploaderAPI
Now, in the web site project, we create the following 3 folders namely:
  • HTML
  • Script
  • UserScript 
Now we add an Angular.min.js file within the Script folder. This file can be easily downloaded from the Nuget Gallery or from the Angular website.
Now we will add a HTML file to the HTML folder named FileUploader.html and write the following HTML code there.
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4.     <title>File Uploader</title>  
  5.     <script src="../Script/angular1.3.8.js"></script>  
  6.     <script src="../Script/angular-route.js"></script>  
  7.     <script src="../UserScript/MyApp.js"></script>  
  8.     <script src="../UserScript/FileUploder.js"></script>  
  9.     <>  
  10.         .percent {  
  11.             position: absolute;  
  12.             width: 300px;  
  13.             height: 14px;  
  14.             z-index: 1;  
  15.             text-align: center;  
  16.             font-size: 0.8em;  
  17.             color: white;  
  18.         }  
  19.   
  20.         .progress-bar {  
  21.             width: 300px;  
  22.             height: 14px;  
  23.             border-radius: 10px;  
  24.             border: 1px solid #CCC;  
  25.             background-image: -webkit-gradient(linear, left top, left bottom, from(#6666cc), to(#4b4b95));  
  26.             border-image: initial;  
  27.         }  
  28.   
  29.         .uploaded {  
  30.             padding: 0;  
  31.             height: 14px;  
  32.             border-radius: 10px;  
  33.             background-image: -webkit-gradient(linear, left top, left bottom, from(#66cc00), to(#4b9500));  
  34.             border-image: initial;  
  35.         }  
  36.     </>  
  37. </head>  
  38. <body ng-app="MyApp" ng-controller="FileUploder">  
  39.     <div>  
  40.         <table ="width:100%;border:solid;">  
  41.             <tr>  
  42.                 <td>Select File</td>  
  43.                 <td>  
  44.                     <input type="file" ng-model-instant id="fileToUpload" onchange="angular.element(this).scope().setFiles(this)" />  
  45.                 </td>  
  46.             </tr>  
  47.             <tr>  
  48.                 <td>File Size</td>  
  49.                 <td>  
  50.                     <div ng-repeat="file in files.slice(0)">  
  51.                         <span ng-switch="file.size > 1024*1024">  
  52.                             <span ng-switch-when="true">{{file.size / 1024 / 1024 | number:2}} MB</span>  
  53.                             <span ng-switch-default>{{file.size / 1024 | number:2}} kB</span>  
  54.                         </span>  
  55.                     </div>  
  56.                 </td>  
  57.             </tr>             
  58.             <tr>  
  59.                 <td>  
  60.                     File Attach Status  
  61.                 </td>  
  62.                 <td>{{AttachStatus}}</td>  
  63.             </tr>  
  64.             <tr>  
  65.                 <td>  
  66.                     <input type="button" value="Upload" ng-click="fnUpload();" />  
  67.                 </td>  
  68.                 <td>  
  69.                     <input type="button" value="DownLoad" ng-click="fnDownLoad();" />  
  70.                 </td>  
  71.             </tr>  
  72.         </table>  
  73.     </div>  
  74. </body>  
  75. </html>  
Now in the preceding code, we have taken the reference of the two JavaScript files:
MyApp.Js and FileUploader.JS.
Now, add a JavaScript file within the UserScript folder named MyApp.Js and add the following code.
  1. var MyApp = angular.module('MyApp', []);  
Again add another JavaScript file within the same folder named FileUploader.JS and define the controller in that file as in the following.
  1. MyApp.controller("FileUploder", ['$scope''$http''$timeout''$window',    
  2.         function ($scope, $http, $location, $timeout, $window) {    
  3.             $scope.AttachStatus = "";    
  4.     }    
  5.     ]);    
Now depending on the normal functionality of file upload control of HTML, when we click on the Choose File button, it opens the file open dialog and allows us to select file. Now our objective is, after selecting the file, it will automatically read the file and show the file size in the page. For this purpose, we called the onchange event of the file upload control and written the following code.
  1. $scope.setFiles = function (element) {  
  2.             $scope.$apply(function (scope) {  
  3.                 $scope.AttachStatus = "";  
  4.                 $scope.files = []  
  5.                 for (var i = 0; i < element.files.length; i++) {  
  6.                     $scope.files.push(element.files[i])  
  7.                 }  
  8.                 $scope.progressVisible = false  
  9.             });  
  10.         }
This function takes the instance of the control as an argument and updates the scope with the file detail information, such as file name, file size in bytes and so on.
Now our next objective is to upload the file using the Web API so that this specific file can be copied and saved in a specific location. For this, we already created a button name Upload. We need to click on this button for uploading. When we click this button, it will call an AngularJs function that internally redirects to the Web API controller to copy and save the file into a specific location. (Here I am using Temporary Internet Files folder for the location.)
Now write the following code first into the fileupload.js file.
  1. $scope.fnUpload = function () {  
  2.             var fd = new FormData()  
  3.             for (var i in $scope.files) {  
  4.                 fd.append("uploadedFile", $scope.files[i])  
  5.             }  
  6.             var xhr = new XMLHttpRequest();  
  7.             xhr.addEventListener("load", uploadComplete, false);  
  8.             xhr.open("POST""http://localhost:53154/api/FileUploader/AttachFile"true);  
  9.             $scope.progressVisible = true;  
  10.             xhr.send(fd);  
  11.         }  
  12.   
  13.         function uploadComplete(evt) {  
  14.             $scope.progressVisible = false;  
  15.             if (evt.target.status == 201) {  
  16.                 $scope.FilePath = evt.target.responseText;  
  17.                 $scope.AttachStatus = "Upload Done";  
  18.                 alert($scope.FilePath);  
  19.             }  
  20.             else {  
  21.                 $scope.AttachStatus = evt.target.responseText;  
  22.             }  
  23.         }  
In the fnUpload button, it creates an instance of FormData object and stores the file information within the FormData and sends the data to the webapi as a XMLHttpRequest. And the uploadComplete function checks if the Web API returns a status code 201 (in other words success) or not.
Now for the Web API code. For that we will add a controller file within the controller folder named FileUploaderController and write the following code in that file.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Net;  
  6. using System.Net.Http;  
  7. using System.Net.Http.Headers;  
  8. using System.Web;  
  9. using System.Web.Http;  
  10.   
  11. namespace FileUploader.Controllers  
  12. {  
  13.     public class FileUploaderController : ApiController  
  14.     {  
  15.         [HttpPost]  
  16.         public HttpResponseMessage AttachFile()  
  17.         {  
  18.             HttpResponseMessage result = null;  
  19.             var httpRequest = HttpContext.Current.Request;  
  20.             if (httpRequest.Files.Count > 0)  
  21.             {  
  22.                 var docfiles = new List<string>();  
  23.                 foreach (string file in httpRequest.Files)  
  24.                 {  
  25.                     var postedFile = httpRequest.Files[file];  
  26.                     string filePath = Path.GetFullPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), postedFile.FileName));  
  27.                     postedFile.SaveAs(filePath);  
  28.   
  29.                     docfiles.Add(filePath);  
  30.                 }  
  31.                 result = Request.CreateResponse(HttpStatusCode.Created, docfiles);  
  32.             }  
  33.             else  
  34.             {  
  35.                 result = Request.CreateResponse(HttpStatusCode.BadRequest);  
  36.             }  
  37.             return result;  
  38.         }  
  39. }  
  40. }  
Now our file upload part is complete. Now, if we run the project and select a file and click on the upload button it will display the file location in an alert box. We can check that the file is physically there.
Now to download a file, we already created a button named DownLoad in the HTML page. Now we will write the code for this download button in the fileuploader.js file.
  1. $scope.fnDownLoad = function () {  
  2.            debugger;  
  3.            $scope.FileExt = $scope.files[0].name.substr($scope.files[0].name.length - 4);  
  4.            $scope.GenerateFileType($scope.FileExt);  
  5.            $scope.RenderFile();  
  6.        }  
  7.   
  8.        $scope.RenderFile = function () {  
  9.            var s = "http://localhost:53154/api/FileUploader/DownLoadFile?"  
  10.               + "FileName=" + $scope.files[0].name  
  11.               + "&fileType=" + $scope.FileType;  
  12.            $window.open(s);  
  13.        }  
  14.   
  15.        $scope.GenerateFileType = function (fileExtension) {  
  16.            switch (fileExtension.toLowerCase()) {  
  17.                case "doc":  
  18.                case "docx":  
  19.                    $scope.FileType = "application/msword";  
  20.                    break;  
  21.                case "xls":  
  22.                case "xlsx":  
  23.                    $scope.FileType = "application/vnd.ms-excel";  
  24.                    break;  
  25.                case "pps":  
  26.                case "ppt":  
  27.                    $scope.FileType = "application/vnd.ms-powerpoint";  
  28.                    break;  
  29.                case "txt":  
  30.                    $scope.FileType = "text/plain";  
  31.                    break;  
  32.                case "rtf":  
  33.                    $scope.FileType = "application/rtf";  
  34.                    break;  
  35.                case "pdf":  
  36.                    $scope.FileType = "application/pdf";  
  37.                    break;  
  38.                case "msg":  
  39.                case "eml":  
  40.                    $scope.FileType = "application/vnd.ms-outlook";  
  41.                    break;  
  42.                case "gif":  
  43.                case "bmp":  
  44.                case "png":  
  45.                case "jpg":  
  46.                    $scope.FileType = "image/JPEG";  
  47.                    break;  
  48.                case "dwg":  
  49.                    $scope.FileType = "application/acad";  
  50.                    break;  
  51.                case "zip":  
  52.                    $scope.FileType = "application/x-zip-compressed";  
  53.                    break;  
  54.                case "rar":  
  55.                    $scope.FileType = "application/x-rar-compressed";  
  56.                    break;  
  57.            }  
  58.        }  
In the preceding code, we first created the file extension from the file name and then set the file MIME type depending on the file extension. Then we will again call the Web API get method to download the file where we the file name and file extension as parameter.
The file download method is as in the following.
  1. [HttpGet]  
  2.         public HttpResponseMessage DownLoadFile(string FileName, string fileType)  
  3.         {  
  4.             Byte[] bytes = null;  
  5.             if (FileName != null)  
  6.             {  
  7.                 string filePath = Path.GetFullPath(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache), FileName));  
  8.                 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);  
  9.                 BinaryReader br = new BinaryReader(fs);  
  10.                 bytes = br.ReadBytes((Int32)fs.Length);  
  11.                 br.Close();  
  12.                 fs.Close();  
  13.             }  
  14.   
  15.             HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);  
  16.             System.IO.MemoryStream stream = new MemoryStream(bytes);  
  17.             result.Content = new StreamContent(stream);  
  18.             result.Content.Headers.ContentType = new MediaTypeHeaderValue(fileType);  
  19.             result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")  
  20.             {  
  21.                 FileName = FileName  
  22.             };  
  23.             return (result);  
  24.         }  
This get method actually reads the file from its physical location (where the file was saved during the upload) and then converts the file into a byte array using file stream reader. Then return the byte content as a HttpResponseMessage to the browser so that the browser can download that file directly.
The following is the complete code of the Fileuploader.js file.
  1. MyApp.controller("FileUploder", ['$scope''$http''$timeout''$window',  
  2.     function ($scope, $http, $location, $timeout, $window) {  
  3.         $scope.AttachStatus = "";  
  4.   
  5.         $scope.fnUpload = function () {  
  6.             var fd = new FormData()  
  7.             for (var i in $scope.files) {  
  8.                 fd.append("uploadedFile", $scope.files[i])  
  9.             }  
  10.             var xhr = new XMLHttpRequest();  
  11.             xhr.addEventListener("load", uploadComplete, false);  
  12.             xhr.open("POST""http://localhost:53154/api/FileUploader/AttachFile"true);  
  13.             $scope.progressVisible = true;  
  14.             xhr.send(fd);  
  15.         }  
  16.   
  17.         function uploadComplete(evt) {  
  18.             $scope.progressVisible = false;  
  19.             if (evt.target.status == 201) {  
  20.                 $scope.FilePath = evt.target.responseText;  
  21.                 $scope.AttachStatus = "Upload Done";  
  22.                 alert($scope.FilePath);  
  23.             }  
  24.             else {  
  25.                 $scope.AttachStatus = evt.target.responseText;  
  26.             }  
  27.         }  
  28.   
  29.         $scope.fnDownLoad = function () {  
  30.             debugger;  
  31.             $scope.FileExt = $scope.files[0].name.substr($scope.files[0].name.length - 4);  
  32.             $scope.GenerateFileType($scope.FileExt);  
  33.             $scope.RenderFile();  
  34.         }  
  35.   
  36.         $scope.RenderFile = function () {  
  37.             var s = "http://localhost:53154/api/FileUploader/DownLoadFile?"  
  38.                + "FileName=" + $scope.files[0].name  
  39.                + "&fileType=" + $scope.FileType;  
  40.             $window.open(s);  
  41.         }  
  42.   
  43.         $scope.GenerateFileType = function (fileExtension) {  
  44.             switch (fileExtension.toLowerCase()) {  
  45.                 case "doc":  
  46.                 case "docx":  
  47.                     $scope.FileType = "application/msword";  
  48.                     break;  
  49.                 case "xls":  
  50.                 case "xlsx":  
  51.                     $scope.FileType = "application/vnd.ms-excel";  
  52.                     break;  
  53.                 case "pps":  
  54.                 case "ppt":  
  55.                     $scope.FileType = "application/vnd.ms-powerpoint";  
  56.                     break;  
  57.                 case "txt":  
  58.                     $scope.FileType = "text/plain";  
  59.                     break;  
  60.                 case "rtf":  
  61.                     $scope.FileType = "application/rtf";  
  62.                     break;  
  63.                 case "pdf":  
  64.                     $scope.FileType = "application/pdf";  
  65.                     break;  
  66.                 case "msg":  
  67.                 case "eml":  
  68.                     $scope.FileType = "application/vnd.ms-outlook";  
  69.                     break;  
  70.                 case "gif":  
  71.                 case "bmp":  
  72.                 case "png":  
  73.                 case "jpg":  
  74.                     $scope.FileType = "image/JPEG";  
  75.                     break;  
  76.                 case "dwg":  
  77.                     $scope.FileType = "application/acad";  
  78.                     break;  
  79.                 case "zip":  
  80.                     $scope.FileType = "application/x-zip-compressed";  
  81.                     break;  
  82.                 case "rar":  
  83.                     $scope.FileType = "application/x-rar-compressed";  
  84.                     break;  
  85.             }  
  86.         }  
  87.   
  88.         $scope.setFiles = function (element) {  
  89.             $scope.$apply(function (scope) {  
  90.                 $scope.AttachStatus = "";  
  91.                 $scope.files = []  
  92.                 for (var i = 0; i < element.files.length; i++) {  
  93.                     $scope.files.push(element.files[i])  
  94.                 }  
  95.                 $scope.progressVisible = false  
  96.             });  
  97.         }  
  98.   
  99.     }  
  100. ]);  
There is one thing we need to remember. In a normal scenario, Visual Studio or ASP.NET allows us to upload a file of a maximum size of 4 MB. If we want to upload a larger file then we need to change the web.config file as in the following.
  1. <httpRuntime targetFramework="4.5" maxRequestLength="104857600"  />    
  2.     
  3. <security>    
  4.       <requestFiltering>    
  5.         <requestLimits maxAllowedContentLength="104857600" maxQueryString="104857600"/>    
  6.       </requestFiltering>    
  7.     </security>    
First, provide a maxRequestLength value in byte format that we want.
Secondly, add the requestFiletering tab within security as specified above.
Now, our task is complete and we will run the project. The following is the final output.

Figure 1: Output

Wednesday, 4 July 2018

Multiple File Upload example in AngularJS Using Web API

In this article I am going to share with you a simple example on how to upload multiple files in AngularJS and Asp.Net Web API.

Every new version of AngularJS looks promising and it’s opening new opportunities for frontend developers. If you are working on Single Page Applications using Angular, then I am sure you will find this article and its example, very useful.



A Web API Controller for a Simple File Upload Procedure – C# and Vb.Net


using System;
using System.Net.Http;
using System.Web.Http;

using System.IO;

namespace FileUpload
{
    public class FileUploadController : ApiController
    {
        [HttpPost()]
        public string UploadFiles()
        {
            int iUploadedCnt = 0;

            // DEFINE THE PATH WHERE WE WANT TO SAVE THE FILES.
            string sPath = "";
            sPath = System.Web.Hosting.HostingEnvironment.MapPath("~/locker/");

            System.Web.HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;

            // CHECK THE FILE COUNT.
            for (int iCnt = 0; iCnt <= hfc.Count - 1; iCnt++)
            {
                System.Web.HttpPostedFile hpf = hfc[iCnt];

                if (hpf.ContentLength > 0)
                {
                    // CHECK IF THE SELECTED FILE(S) ALREADY EXISTS IN FOLDER. (AVOID DUPLICATE)
                    if (!File.Exists(sPath + Path.GetFileName(hpf.FileName)))
                    {
                        // SAVE THE FILES IN THE FOLDER.
                        hpf.SaveAs(sPath + Path.GetFileName(hpf.FileName));
                        iUploadedCnt = iUploadedCnt + 1;
                    }
                }
            }

            // RETURN A MESSAGE (OPTIONAL).
            if (iUploadedCnt > 0) {
                return iUploadedCnt + " Files Uploaded Successfully";
            }
            else {
                return "Upload Failed";
            }
        }
    }
}


Once you have created the API, it’s time to create the web page, using few AngularJS directives.


AngularJS View

<!DOCTYPE html>
<html>
<head>
  <title>File Upload Example in AngularJS</title>
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
</head>

<body ng-app="fupApp">

    <div ng-controller="fupController">
        <input type="file" id="file" name="file" multiple
            onchange="angular.element(this).scope().getFileDetails(this)" />

        <input type="button" ng-click="uploadFiles()" value="Upload" />

        <!--ADD A PROGRESS BAR ELEMENT.-->
        <p><progress id="pro" value="0"></progress></p>
    </div>

</body>

The Controller and the Scope

<script>
    var myApp = angular.module('fupApp', []);

    myApp.controller('fupController', function ($scope) {

        // GET THE FILE INFORMATION.
        $scope.getFileDetails = function (e) {

            $scope.files = [];
            $scope.$apply(function () {

                // STORE THE FILE OBJECT IN AN ARRAY.
                for (var i = 0; i < e.files.length; i++) {
                    $scope.files.push(e.files[i])
                }

            });
        };

        // NOW UPLOAD THE FILES.
        $scope.uploadFiles = function () {

            //FILL FormData WITH FILE DETAILS.
            var data = new FormData();

            for (var i in $scope.files) {
                data.append("uploadedFile", $scope.files[i]);
            }

            // ADD LISTENERS.
            var objXhr = new XMLHttpRequest();
            objXhr.addEventListener("progress", updateProgress, false);
            objXhr.addEventListener("load", transferComplete, false);

            // SEND FILE DETAILS TO THE API.
            objXhr.open("POST", "/api/fileupload/");
            objXhr.send(data);
        }

        // UPDATE PROGRESS BAR.
        function updateProgress(e) {
            if (e.lengthComputable) {
                document.getElementById('pro').setAttribute('value', e.loaded);
                document.getElementById('pro').setAttribute('max', e.total);
            }
        }

        // CONFIRMATION.
        function transferComplete(e) {
            alert("Files uploaded successfully.");
        }
    });
</script>

Friday, 29 June 2018

Overview of ASP.NET vNext

Introduction

Changes are very rapid in software world, especially in web development world. In the past decade, there have been many new enhancements in software like embracing agile methodology, adapting decoupled architecture, moving away from proprietary software towards open source.
Some of the important things that have become a standard in the last couple of years and  are expected in any framework today are:
Agile  A framework should be able to easily accommodate upgrades and changes depending on the updates and new patterns in the software world. So the new framework release cycles could be more frequent and with least impact to the existing applications.
This is in contrast with the previous generation of frameworks in which new framework release cycles were relatively infrequent and usually in years.
Cross platform development   Applications should be able to run on many different platforms.
Open source  Since it helps creates a large developer community and allows everyone to contribute.
ASP.NET  has matured as a web development platform over the years. It has come a long way from web forms to MVC to WebAPI. At the same time, web development world has much changed since the initial release of ASP.NET. So there is need to upgrade the underlying ASP.NET core framework.
ASP.NET vNext which is the next version of ASP.NET is redesigned from the ground up and provides solutions to many of the challenges faced while developing web applications of today.
ASP.NET vNext main features
We will have a look into some of the features of ASP.NET  and their shortcomings and how they are addressed in ASP.NET vNext.
NuGet Packages
ASP.NET - Monolithic assemblies
In  ASP.NET ,lot of functionality is encapsulated in different framework assemblies and any updates to the functionality ,no matter how small ,means shipping a new version of the entire assembly.This is not in agreement with the agile development world of today in which changes are very frequent.
Also if we want to use a single class from one of these assemblies then the only way to use the class is to reference the entire assembly , which might consist of ton's of other namespaces which we don't need.
There are assemblies like System.web that contains lots of functionality .It contains classes and interfaces that enable browser server communication. It contains classes like HTTPRequest and HTTPResponse ,it contains classes for different purposes like cookie manipulation and file transfer. Also It contains the entire Web Forms functionality.
If we expand the System.Web assembly node in the object browser we can look into the different namespaces that it contains.
Then there are other assemblies also which contains lot of functionality.It is not incorrect to call them monolithic as they contain a lot functionality.It's an all or nothing approach ,even if we have to use only specific functionality in the assembly we have to reference entire assembly.
Technologies which were introduced later like MVC and WebAPI provided a solution to the monolithic assemblies in the form of NuGet packages. MVC has a dependency on System.Web while WebAPI have no dependency on System.Web .
So to move away from the monolithic approach means to remove the dependency on System.Web.
ASP.NET vNext - Smaller NuGet Packages
ASP.NET vNext removes the dependency on monolithic framework assemblies. Now we will be mostly using NuGet packages instead of assemblies.In fact Cloud optimized framework is just a collection of NuGet  packages.We can say that now Nuget is an important component in all the vNext applications.
One important thing is that there is no System.Web assembly now. The functionality in the System.Web has been moved into smaller nuget packages.
If we want to use some functionality in our application then we need to include only the required dependencies.There is a new file project.json which contains the dependencies of the application.
In the dependencies section below we can add the nugget packages that our application depends upon.
In the solution explorer if we expand the references node ,the nodes displayed represents different NuGet packages that our application depends upon.As we can see that now we don't have a System.Web reference.
Whenever we update any nuget package in the project.json file then it is automatically updated in the references node in the solution explorer.
Now instead of assemblies NuGet packages are the unit of reference.One important thing is that we can replace the NuGet package with  a project or the project with the NuGet package.This is useful in scenarios where the NuGet package might contain a bug ,we can fetch the source for the package from the github and after correcting the bug can add it in our application.
When we specify the NuGet packages in project.json then we only specify the NuGet packages that our application directly need to use.The other packages that our main packages are dependent upon are automatically downloaded.This is unlike the previous versions of ASP.NET in which we had to specify the main packages and also the other required packages in the packages.config file.
We just specify the main dependencies for our application in the project.json file.
Following are the advantages we get as a result of using  NuGet packages
  • Instead of shipping updates to the frameworks ,in monolithic assemblies containing lots of functionality , in many years, the updates to the frameworks can be shipped in smaller nugget packages very frequently.
  • Shipping updates using nugget packages has the least impact to the rest of the framework as a package contain only a specific functionality.
Cross Platform
ASP.NET - Coupled to the windows environment/IIS
As we know ASP.NET is designed to run on a windows OS and IIS web server.Though we can use Mono to run our applications on other platforms but only Xamarin was responsible for maintaining Mono.Also configuring our applications for these platforms required a significant effort.We need to consider the mod_mono/xsp/apache configuration.
Though we can run our applications on other platforms but there was no easy way for us to develop our applications on non-windows platforms.
ASP.NET vNext - Designed as cross platform and host agnostic
Now we can develop and deploy our asp.net vNext applications on different platforms like linux.Also we can host them on servers other then IIS. This is a significant change from the previous versions of ASP.NET.
Microsoft now includes KRE for Mono so that asp.net vNext applications can run across different platforms.
There are few things here that we need to understand when thinking about cross platform development.
Mono  is  a “software platform designed to allow developers to easily create cross platform applications”. 
KRE is a Runtime Environment used to execute ASP.NET vNext applications. It includes things like compilation system and SDK tools. We need to install KRE for Mono to enable cross platform support in our applications.
Command line tools and batch files  because of command line tools we can do most of the things that we do in visual studio.There are batch files for important platforms such as Linux ,so we are able to deploy our ASP.NET vNext applications without needing visual studio and windows.
KVM helps us to retrieve different versions of the KRE and to switch between them.
Because of project.json file we can open vNext projects outside of visual studio and we can even edit them using any text editor such as notepad.This is a big change from project files, such as .proj file, in the earlier versions which were not very easy to edit without visual studio.
If we want to run our application on some other host other then IIS ,such as self hosting ,then we just need to change a single line of code in project.json . We need to use the package Microsoft.AspNet.Server.WebListener instead of   Microsoft.AspNet.Server.IIS  in the project.json file.
So instead of the following dependency for IIS 
"dependencies": {
        "Microsoft.AspNet.Server.IIS": "1.0.0-alpha4"
    }
we need to use the below package for self hosting
"dependencies": {
        "Microsoft.AspNet.Server.WebListener": "1.0.0-alpha4"
            }
Open source 
ASP.NET - Proprietary 
Though MVC and Entity frameworks which were released later are open source and available on codeplex ,previous versions of ASP.NET and it's most of the technologies have been proprietary.
ASP.NET vNext- Fully Open Source
MVC and Entity frameworks are open source and were available on Codeplex ,in previous version of ASP.NET.Now ASP.NET vNext is fully open source and it's code is available on GitHub. 
.NET Foundation is a forum for the development and collaboraiton of open source .NET technmologies .ASP.NET vNext is part of .NET Foundation.
Following are the advantages
Anyone can contribute ,thus it helps create a large and open community.
Side by Side Execution
ASP.NET - Not easy to selectively update the frameworks
Usually we have lots of different applications deployed on the production server.We can have different   applications  on the server which use different versions of the framework. So we can have few applications using the framework 3.0 and other applications using framework 4.0 and these all applications can co-exist happily on the same machine without any issues.
Now suppose we want to use some functionality which is available as an update to framework 4.0.This updated functionality we want to use in only one of our applications.We cannot  selectively update the framework in one of applications as the framework is shared across the entire machine.So we drop the idea of applying the update because just one application needs to use some new functionality, so that the rest of the applications are not impacted.Also testing all the deployed applications is a significant effort.
ASP.NET vNext -Ability to deploy the framework along with the application
In cloud optimized mode we can include a copy of  .NET framework  with our asp.net vNext applications and it will use that framework. This means that since all the applications on the server can use different versions of the framework/runtime ,the framework for each application can be upgraded separately without having any impact on the rest of the applications.
So our new updated libraries cannot effect the other applications which uses the older libraries as our application is now a self contained unit of functionality.
We can set the target framework for our application using the project.json file or using the Active Target framework property in the property pages.


The obvious advantage is side by side execution prevents accidentally updating the older assemblies used by legacy applications.
Cloud Ready
ASP.NET - Need to make changes to deploy applications on the cloud
As cloud is a comparatively newer technology ,ASP.NET  was not initially designed for the cloud environment.We have to make some changes in our applications to deploy them on the cloud.Like making configuration changes.This  means making significant changes to our application.
ASP.NET vNext - Cloud ready
In ASP.NET vNext applications instead of fetching the values from web.config there are value providers which fetches us the correct configuration values.In fact there is no web.config file now.
Configuration settings are fetched from config.json file.This file can be in XML, JSON or INI format.
vNext supports three CLR's.
  • Desktop   The CLR which we are used to in .NET framework.
  • Mono       To run cross platform applications.
  • Cloud Optimized   To run applications on the cloud.
So we can have three runtimes installed on a machine and can easily switch between them using Kvm , which is the version manager.
We can view the runtime's installed on the machine using the Kvm list command.KVM is used to manage different versions of the runtime.
As we can see there are three runtimes's currently installed on the machine out of which the one with alias "d" is the active one.CoreCLR is the cloud optimized CLR.
We can switch to specific KRE using the kvm use version command.As we deploy the runtime with our application each application will use a different runtime.
We can use the 'kpm' command to  pack the project along with the runtime for deployment to azure.And if tomorrow a new NuGet package is released as a part of framework update we can include that package in the framework for application instead of updating the common framework used by all the applications.
Following are the advantages 
Because value providers for .config file our application is decoupled from the environment and we don't need to mess with our configuration values.                                                                                                                                     Cloud optimized version of libraries makes our application more efficient on the cloud.Services such as caching adjust there behaviour for the cloud environment without us bothering about them.                                                           The Cloud optimized framework is just about 11 megabytes in size ,much smaller than the 200 megabytes of full framework .
Composable Pipeline
 ASP.NET - Little Control over the Request pipeline
In  previous versions of ASP.NET the request passes through a well defined request pipeline until it is handled by the HTTPHandler for the request.We can define the event handlers for the HTTP modules and define the HTTP handlers.But the request is passed through fixed set of components over which we have little or no control.
This works fine but may not be the optimal solution in such a scenario where we don't need all the heavy plumbing provided by the pipeline.
ASP.NET vNext - Ability to add components to the pipeline
Now we can explicitly specify the component we want to use in the pipeline.Application host expects a class with the name Startup containing a Configure method that takes IApplicationBuilder parameter.This interface has extension methods of the form builder.UseService() which we need to call to add the service to the request pipeline.
We can use the below method to add Mvc to the pipeline.
using System;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;

namespace MvcApplication
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app)
        {
            app.UseServices(services => { services.AddMvc(); });
            app.UseMvc();
        }
    }
}
This gives us complete control to customize the request pipeline.This is in contrast to the fixed request pipeline in previous versions of ASP.NET.
Following are the advanatages
Our application are faster and simpler.                                                                                                                       We have complete control of the pipeline which allows us to configure the pipeline for different hosts.
MVC 6 - Single framework
ASP.NET WebAPI , MVC and Web Pages have different implementations
Though there is much similarity between MVC ,WebAPI and Web Pages their implementations differs due to historical reasons. This is due to the fact Web API  came after MVC. MVC was released after Web Forms and it changed the approach to web development in .NET. Following are the implications of this:
MVC depends on IIS,System.Web and asp.net pipeline.It depeends on asp.net pipeline components such as HTTP handlers and http modules
Web API does not depend upon IIS , System.Web.
Because of these reasons the implementations of these technologies are different even though they provide many common functionality.
ASP.NET vNext MVC 6 - Commom framework 
MVC,WebAPI,Web Pages and Signal R are unified in a common framework ,MVC 6 . MVC 5 depends upon IIS while MVC 6 can be self hosted and depends on the new asp.net vnext pipeline.
If we want to move to MVC from Web Pages as our application grows we can easily do so now, since they are part of the the common framework MVC 6.
If we select to create a new project following is displayed.
If we look in the solution explorer there are few files in the asp.net that are missing like web.config
and global.asax.Instead there are new files  config.json, project.json and startup.cs.
project.json file contains the NuGet packages and also the build information.                                                          config.json file contains the application configuration
Dependency injection
In MVC 6 Dependency injection is fully sipported and is supported by all the main components like routing.There is dependency injection abstraction IServiceProvider interface.It is because of this abstraction that we can chose any dependency injection container of our choice.Also a default implementation of dependency injection container is provided which we can use.
Following are the advantages
Instead of seaparate implementations of the same concepts such as routing now there is a common implementation. Consistent programming model while using MVC 6 technologies.
Roslyn Compiler
ASP.NET - Need to rebuild the application after code changes
In the previous versions whenever we modify our code we need to rebuild the application for our changes to take effect. Also we do not have access to the compiler API in our code as it was like a black box.
ASP.NET vNext - Dynamic Compilation
ASP.NET vNext  consists of next generation of compilers called Roslyn.Roslyn is an open source compiler platform.It exposes an object oriented API .We can use this API to use features of roslyn such as code analysis in our code.In the previous versions we had to use tools for code analysis.
Because of dynamic compilation we can just make the changes in the code and need to just refresh the browser to reflect our changes.In the previous versions of ASP.NET we have to make code changes then re-build the solution and then refresh the browser for our changes to take effect.
Now we can just change make the code change and  refresh the browser for our change to reflect.
Below is the default code in a MVC application
public IActionResult About()
       {
         ViewBag.Message = "Your application description page.";
         return View();
       }
If we execute the above code we get the below page

if we change the above code 
public IActionResult About()
      {
          ViewBag.Message = "Welcome to ASP.NET vNext";
          return View();
      }
If we refresh the browser we can see our changes are reflected in the browser without rebuilding the solution.