Tech Junkie Blog - Real World Tutorials, Happy Coding!: ASP.NET MVC : Upgrade ASP.NET MVC 4 to ASP.NET MVC 5 Using NuGet Part 2

Monday, March 23, 2015

ASP.NET MVC : Upgrade ASP.NET MVC 4 to ASP.NET MVC 5 Using NuGet Part 2

In the previous blog we went over how to create a simple ASP.NET MVC 4 application.  In this blog we will go over the steps to upgrade our ASP.NET MVC 4 application to ASP.NET MVC 5 application.

Step-By-Step Instructions:

  1. Open the "MyMVC4" project that you've created on the last blog
  2. Right click on the project and select "Manage NuGet Packages..."
Manage NuGet Packages

















3.  Select Microsoft ASP.NET MVC and click "Install", as you can see the latest version is 5.2.3

NuGet ASP.NET MVC Version 5.2.3
















4.  Click "I Accept" on the license agreement screen

APS.NET MVC  License Acceptance























5.  There will be a check mark after ASP.NET MVC 5 has been installed by NuGet


















6.  Before you click the "Close" button make a note of the "Description" section, pay close attention to the "Dependencies" section, it will come in handy later.

Microsoft.AspNet.Mvc Description























7.  Visual Studio will give you a message that to complete the upgrade you have to restart Visual Studio.  Click "OK"

Microsoft Visual Studio MVC Restart









8.  Close Visual Studio and then open the "MyMVC4" project again.

9.  Press "Ctrl+F5"

10.  Instead of seeing the friendly greeting of "Hello World!" you will be greeted with a nasty error message


Server Error in '/' Application.

[A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. Type B originates from 'System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Users\TechJunkie\AppData\Local\Temp\Temporary ASP.NET Files\vs\12822f34\c6cc652d\assembly\dl3\23bbbc5e\1a551bd8_e563d001\System.Web.WebPages.Razor.dll'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidCastException: [A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. Type B originates from 'System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Users\TechJunkie\AppData\Local\Temp\Temporary ASP.NET Files\vs\12822f34\c6cc652d\assembly\dl3\23bbbc5e\1a551bd8_e563d001\System.Web.WebPages.Razor.dll'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[InvalidCastException: [A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from 'System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Web.WebPages.Razor\v4.0_2.0.0.0__31bf3856ad364e35\System.Web.WebPages.Razor.dll'. Type B originates from 'System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' in the context 'Default' at location 'C:\Users\TechJunkie\AppData\Local\Temp\Temporary ASP.NET Files\vs\12822f34\c6cc652d\assembly\dl3\23bbbc5e\1a551bd8_e563d001\System.Web.WebPages.Razor.dll'.]
   System.Web.WebPages.Razor.WebRazorHostFactory.GetRazorSection(String virtualPath) +79
   System.Web.WebPages.Razor.WebRazorHostFactory.CreateHostFromConfig(String virtualPath, String physicalPath) +44
   System.Web.WebPages.Razor.RazorBuildProvider.GetHostFromConfig() +20
   System.Web.WebPages.Razor.RazorBuildProvider.CreateHost() +17
   System.Web.WebPages.Razor.RazorBuildProvider.EnsureGeneratedCode() +60
   System.Web.WebPages.Razor.RazorBuildProvider.get_CodeCompilerType() +32
   System.Web.Compilation.BuildProvider.GetCompilerTypeFromBuildProvider(BuildProvider buildProvider) +59
   System.Web.Compilation.BuildProvidersCompiler.ProcessBuildProviders() +209
   System.Web.Compilation.BuildProvidersCompiler.PerformBuild() +30
   System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath) +9971917
   System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) +299
   System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) +103
   System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean throwIfNotFound) +165
   System.Web.Compilation.BuildManager.GetCompiledType(VirtualPath virtualPath) +10
   System.Web.Compilation.BuildManager.GetCompiledType(String virtualPath) +28
   System.Web.Mvc.BuildManagerWrapper.System.Web.Mvc.IBuildManager.GetCompiledType(String virtualPath) +6
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +54
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +28
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +36
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651116
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155



Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34212              

11.  Remember the ASP.NET MVC 5 Description in NuGet?  It says
"Dependencies

        Microsoft.AspNet.WebPages (≥ 3.2.3 && < 3.3.0)

        Microsoft.AspNet.Razor (≥ 3.2.3 && < 3.3.0)
"
and 

"
Id: Microsoft.AspNet.Mvc
Version: 5.2.3
"

12.  Even though we've already installed ASP.NET MVC 5 on our ASP.NET MVC 4 project.  The Web.Config file still refers to the old ASP.NET MVC 4 version.  NuGet did not change the Web.Config file for us in the "Views" folder.  Although it did change the Web.Config in the root application folder.

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>

13.If you look the Web.Config file under the "Views" folder you will see that the Web.Config file still references the old version of MVC and Razor.
<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <!--
        Enabling request validation in view pages would cause validation to occur
        after the input has already been processed by the controller. By default
        MVC performs request validation before a controller processes the input.
        To change this behavior apply the ValidateInputAttribute to a
        controller or action.
    -->
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>



14. Change the Web.config file to use ASP.NET MVC 5, the Web.config should be changed to the following in order for you to get rid of the error.
<?xml version="1.0"?>

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <!--
        Enabling request validation in view pages would cause validation to occur
        after the input has already been processed by the controller. By default
        MVC performs request validation before a controller processes the input.
        To change this behavior apply the ValidateInputAttribute to a
        controller or action.
    -->
    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

15. Press "Ctrl+F5" and you should see "Hello World!" again instead of the error.

ASP.NET MVC Hello World










There you have that is how you upgrade from ASP.NET MVC 4 to ASP.NET MVC 5.  It's not as straight forward, but it's not too difficult.


16.  Now that we have a working empty ASP.NET MVC 5 project, we need add the items to the projects manually.  You might have noticed that we are missing the "Scripts" folder.  What we want to do is add the "Scripts" folder manually from an existing ASP.NET MVC 5 regular project.  I usually zip up the "Scripts" folder and added it to the empty ASP.NET MVC 5 project.  Here is the "Scripts" folder zipped up.

Scripts.zip

  17. To add the "Scripts" folder to the MvcApp application that we've just created, download the Scripts.zip file then extract it.  Make sure you choose the option to "Extract here.." on your unzip utility program.

You have the following folders, make sure that when you extracted the .zip file that "Scripts" is the root folder and there's only one level to the folder.  If you select "Extract to Scripts\" option on the unzip utility you will get two nested "Scripts" folder, which is something we don't want.




18.  Now drag the extracted "Scripts" folder to Visual Studio at the top level of the MvcApp folder
























As you can see now we have the "Scripts" folder in our empty project, which is not so empty anymore.



Blogs in this series:


  1. ASP.NET MVC : Upgrade ASP.NET MVC 4 to ASP.NET MVC 5 Using NuGet Part 1
  2. ASP.NET MVC : Upgrade ASP.NET MVC 4 to ASP.NET MVC 5 Using NuGet Part 2


3 comments:

  1. Hlw,

    "_Layout.cshtml" page have many issue as below..
    1)The name 'ViewBag' does not exist in the current context
    2)The name 'Styles' does not exist in the current context

    Please suggest and help..

    Regards,tutul




    ReplyDelete
    Replies
    1. This was an old post. I would recommend doing everything through NuGet. I would even skip the copying the Scripts folder over. Just try to figure out how to install the dependencies through NuGet. Or it might even be worthwhile to start a brand new ASP.NET MVC 5+ solution from scratch. That might be the cleaner approach.

      Delete

Search This Blog